prerequisites.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. """Everything related to fetching or initializing build prerequisites."""
  2. from __future__ import annotations
  3. import glob
  4. import importlib
  5. import inspect
  6. import json
  7. import os
  8. import platform
  9. import random
  10. import re
  11. import stat
  12. import sys
  13. import tempfile
  14. import zipfile
  15. from datetime import datetime
  16. from fileinput import FileInput
  17. from pathlib import Path
  18. from types import ModuleType
  19. from typing import Callable, Optional
  20. import httpx
  21. import pkg_resources
  22. import typer
  23. from alembic.util.exc import CommandError
  24. from packaging import version
  25. from redis import Redis as RedisSync
  26. from redis.asyncio import Redis
  27. import reflex
  28. from reflex import constants, model
  29. from reflex.compiler import templates
  30. from reflex.config import Config, get_config
  31. from reflex.utils import console, path_ops, processes
  32. CURRENTLY_INSTALLING_NODE = False
  33. def check_latest_package_version(package_name: str):
  34. """Check if the latest version of the package is installed.
  35. Args:
  36. package_name: The name of the package.
  37. """
  38. try:
  39. # Get the latest version from PyPI
  40. current_version = pkg_resources.get_distribution(package_name).version
  41. url = f"https://pypi.org/pypi/{package_name}/json"
  42. response = httpx.get(url)
  43. latest_version = response.json()["info"]["version"]
  44. if (
  45. version.parse(current_version) < version.parse(latest_version)
  46. and not get_or_set_last_reflex_version_check_datetime()
  47. ):
  48. # only show a warning when the host version is outdated and
  49. # the last_version_check_datetime is not set in reflex.json
  50. console.warn(
  51. f"Your version ({current_version}) of {package_name} is out of date. Upgrade to {latest_version} with 'pip install {package_name} --upgrade'"
  52. )
  53. except Exception:
  54. pass
  55. def get_or_set_last_reflex_version_check_datetime():
  56. """Get the last time a check was made for the latest reflex version.
  57. This is typically useful for cases where the host reflex version is
  58. less than that on Pypi.
  59. Returns:
  60. The last version check datetime.
  61. """
  62. if not os.path.exists(constants.Reflex.JSON):
  63. return None
  64. # Open and read the file
  65. with open(constants.Reflex.JSON, "r") as file:
  66. data: dict = json.load(file)
  67. last_version_check_datetime = data.get("last_version_check_datetime")
  68. if not last_version_check_datetime:
  69. data.update({"last_version_check_datetime": str(datetime.now())})
  70. path_ops.update_json_file(constants.Reflex.JSON, data)
  71. return last_version_check_datetime
  72. def check_node_version() -> bool:
  73. """Check the version of Node.js.
  74. Returns:
  75. Whether the version of Node.js is valid.
  76. """
  77. current_version = get_node_version()
  78. if current_version:
  79. # Compare the version numbers
  80. return (
  81. current_version >= version.parse(constants.Node.MIN_VERSION)
  82. if constants.IS_WINDOWS
  83. else current_version == version.parse(constants.Node.VERSION)
  84. )
  85. return False
  86. def get_node_version() -> version.Version | None:
  87. """Get the version of node.
  88. Returns:
  89. The version of node.
  90. """
  91. node_path = path_ops.get_node_path()
  92. if node_path is None:
  93. return None
  94. try:
  95. result = processes.new_process([node_path, "-v"], run=True)
  96. # The output will be in the form "vX.Y.Z", but version.parse() can handle it
  97. return version.parse(result.stdout) # type: ignore
  98. except (FileNotFoundError, TypeError):
  99. return None
  100. def get_fnm_version() -> version.Version | None:
  101. """Get the version of fnm.
  102. Returns:
  103. The version of FNM.
  104. """
  105. try:
  106. result = processes.new_process([constants.Fnm.EXE, "--version"], run=True)
  107. return version.parse(result.stdout.split(" ")[1]) # type: ignore
  108. except (FileNotFoundError, TypeError):
  109. return None
  110. def get_bun_version() -> version.Version | None:
  111. """Get the version of bun.
  112. Returns:
  113. The version of bun.
  114. """
  115. try:
  116. # Run the bun -v command and capture the output
  117. result = processes.new_process([get_config().bun_path, "-v"], run=True)
  118. return version.parse(result.stdout) # type: ignore
  119. except FileNotFoundError:
  120. return None
  121. def get_install_package_manager() -> str | None:
  122. """Get the package manager executable for installation.
  123. Currently on unix systems, bun is used for installation only.
  124. Returns:
  125. The path to the package manager.
  126. """
  127. # On Windows, we use npm instead of bun.
  128. if constants.IS_WINDOWS:
  129. return get_package_manager()
  130. # On other platforms, we use bun.
  131. return get_config().bun_path
  132. def get_package_manager() -> str | None:
  133. """Get the package manager executable for running app.
  134. Currently on unix systems, npm is used for running the app only.
  135. Returns:
  136. The path to the package manager.
  137. """
  138. npm_path = path_ops.get_npm_path()
  139. if npm_path is not None:
  140. npm_path = str(Path(npm_path).resolve())
  141. return npm_path
  142. def get_app(reload: bool = False) -> ModuleType:
  143. """Get the app module based on the default config.
  144. Args:
  145. reload: Re-import the app module from disk
  146. Returns:
  147. The app based on the default config.
  148. Raises:
  149. RuntimeError: If the app name is not set in the config.
  150. """
  151. os.environ[constants.RELOAD_CONFIG] = str(reload)
  152. config = get_config()
  153. if not config.app_name:
  154. raise RuntimeError(
  155. "Cannot get the app module because `app_name` is not set in rxconfig! "
  156. "If this error occurs in a reflex test case, ensure that `get_app` is mocked."
  157. )
  158. module = config.module
  159. sys.path.insert(0, os.getcwd())
  160. app = __import__(module, fromlist=(constants.CompileVars.APP,))
  161. if reload:
  162. from reflex.state import reload_state_module
  163. # Reset rx.State subclasses to avoid conflict when reloading.
  164. reload_state_module(module=module)
  165. # Reload the app module.
  166. importlib.reload(app)
  167. return app
  168. def get_compiled_app(reload: bool = False) -> ModuleType:
  169. """Get the app module based on the default config after first compiling it.
  170. Args:
  171. reload: Re-import the app module from disk
  172. Returns:
  173. The compiled app based on the default config.
  174. """
  175. app_module = get_app(reload=reload)
  176. app = getattr(app_module, constants.CompileVars.APP)
  177. # For py3.8 and py3.9 compatibility when redis is used, we MUST add any decorator pages
  178. # before compiling the app in a thread to avoid event loop error (REF-2172).
  179. app._apply_decorated_pages()
  180. app.compile_()
  181. return app_module
  182. def get_redis() -> Redis | None:
  183. """Get the asynchronous redis client.
  184. Returns:
  185. The asynchronous redis client.
  186. """
  187. if isinstance((redis_url_or_options := parse_redis_url()), str):
  188. return Redis.from_url(redis_url_or_options)
  189. elif isinstance(redis_url_or_options, dict):
  190. return Redis(**redis_url_or_options)
  191. return None
  192. def get_redis_sync() -> RedisSync | None:
  193. """Get the synchronous redis client.
  194. Returns:
  195. The synchronous redis client.
  196. """
  197. if isinstance((redis_url_or_options := parse_redis_url()), str):
  198. return RedisSync.from_url(redis_url_or_options)
  199. elif isinstance(redis_url_or_options, dict):
  200. return RedisSync(**redis_url_or_options)
  201. return None
  202. def parse_redis_url() -> str | dict | None:
  203. """Parse the REDIS_URL in config if applicable.
  204. Returns:
  205. If redis-py syntax, return the URL as it is. Otherwise, return the host/port/db as a dict.
  206. """
  207. config = get_config()
  208. if not config.redis_url:
  209. return None
  210. if config.redis_url.startswith(("redis://", "rediss://", "unix://")):
  211. return config.redis_url
  212. console.deprecate(
  213. feature_name="host[:port] style redis urls",
  214. reason="redis-py url syntax is now being used",
  215. deprecation_version="0.3.6",
  216. removal_version="0.5.0",
  217. )
  218. redis_url, has_port, redis_port = config.redis_url.partition(":")
  219. if not has_port:
  220. redis_port = 6379
  221. console.info(f"Using redis at {config.redis_url}")
  222. return dict(host=redis_url, port=int(redis_port), db=0)
  223. def get_production_backend_url() -> str:
  224. """Get the production backend URL.
  225. Returns:
  226. The production backend URL.
  227. """
  228. config = get_config()
  229. return constants.PRODUCTION_BACKEND_URL.format(
  230. username=config.username,
  231. app_name=config.app_name,
  232. )
  233. def validate_app_name(app_name: str | None = None) -> str:
  234. """Validate the app name.
  235. The default app name is the name of the current directory.
  236. Args:
  237. app_name: the name passed by user during reflex init
  238. Returns:
  239. The app name after validation.
  240. Raises:
  241. Exit: if the app directory name is reflex or if the name is not standard for a python package name.
  242. """
  243. app_name = (
  244. app_name if app_name else os.getcwd().split(os.path.sep)[-1].replace("-", "_")
  245. )
  246. # Make sure the app is not named "reflex".
  247. if app_name == constants.Reflex.MODULE_NAME:
  248. console.error(
  249. f"The app directory cannot be named [bold]{constants.Reflex.MODULE_NAME}[/bold]."
  250. )
  251. raise typer.Exit(1)
  252. # Make sure the app name is standard for a python package name.
  253. if not re.match(r"^[a-zA-Z][a-zA-Z0-9_]*$", app_name):
  254. console.error(
  255. "The app directory name must start with a letter and can contain letters, numbers, and underscores."
  256. )
  257. raise typer.Exit(1)
  258. return app_name
  259. def create_config(app_name: str):
  260. """Create a new rxconfig file.
  261. Args:
  262. app_name: The name of the app.
  263. """
  264. # Import here to avoid circular imports.
  265. from reflex.compiler import templates
  266. config_name = f"{re.sub(r'[^a-zA-Z]', '', app_name).capitalize()}Config"
  267. with open(constants.Config.FILE, "w") as f:
  268. console.debug(f"Creating {constants.Config.FILE}")
  269. f.write(templates.RXCONFIG.render(app_name=app_name, config_name=config_name))
  270. def initialize_gitignore(
  271. gitignore_file: str = constants.GitIgnore.FILE,
  272. files_to_ignore: set[str] = constants.GitIgnore.DEFAULTS,
  273. ):
  274. """Initialize the template .gitignore file.
  275. Args:
  276. gitignore_file: The .gitignore file to create.
  277. files_to_ignore: The files to add to the .gitignore file.
  278. """
  279. # Combine with the current ignored files.
  280. if os.path.exists(gitignore_file):
  281. with open(gitignore_file, "r") as f:
  282. files_to_ignore |= set([line.strip() for line in f.readlines()])
  283. # Write files to the .gitignore file.
  284. with open(gitignore_file, "w", newline="\n") as f:
  285. console.debug(f"Creating {gitignore_file}")
  286. f.write(f"{(path_ops.join(sorted(files_to_ignore))).lstrip()}")
  287. def initialize_requirements_txt():
  288. """Initialize the requirements.txt file.
  289. If absent, generate one for the user.
  290. If the requirements.txt does not have reflex as dependency,
  291. generate a requirement pinning current version and append to
  292. the requirements.txt file.
  293. """
  294. fp = Path(constants.RequirementsTxt.FILE)
  295. encoding = "utf-8"
  296. if not fp.exists():
  297. fp.touch()
  298. else:
  299. # Detect the encoding of the original file
  300. import charset_normalizer
  301. charset_matches = charset_normalizer.from_path(fp)
  302. maybe_charset_match = charset_matches.best()
  303. if maybe_charset_match is None:
  304. console.debug(f"Unable to detect encoding for {fp}, exiting.")
  305. return
  306. encoding = maybe_charset_match.encoding
  307. console.debug(f"Detected encoding for {fp} as {encoding}.")
  308. try:
  309. other_requirements_exist = False
  310. with open(fp, "r", encoding=encoding) as f:
  311. for req in f.readlines():
  312. # Check if we have a package name that is reflex
  313. if re.match(r"^reflex[^a-zA-Z0-9]", req):
  314. console.debug(f"{fp} already has reflex as dependency.")
  315. return
  316. other_requirements_exist = True
  317. with open(fp, "a", encoding=encoding) as f:
  318. preceding_newline = "\n" if other_requirements_exist else ""
  319. f.write(
  320. f"{preceding_newline}{constants.RequirementsTxt.DEFAULTS_STUB}{constants.Reflex.VERSION}\n"
  321. )
  322. except Exception:
  323. console.info(f"Unable to check {fp} for reflex dependency.")
  324. def initialize_app_directory(app_name: str, template: constants.Templates.Kind):
  325. """Initialize the app directory on reflex init.
  326. Args:
  327. app_name: The name of the app.
  328. template: The template to use.
  329. """
  330. console.log("Initializing the app directory.")
  331. # Copy the template to the current directory.
  332. template_dir = Path(constants.Templates.Dirs.BASE, "apps", template.value)
  333. # Remove all pyc and __pycache__ dirs in template directory.
  334. for pyc_file in template_dir.glob("**/*.pyc"):
  335. pyc_file.unlink()
  336. for pycache_dir in template_dir.glob("**/__pycache__"):
  337. pycache_dir.rmdir()
  338. for file in template_dir.iterdir():
  339. # Copy the file to current directory but keep the name the same.
  340. path_ops.cp(str(file), file.name)
  341. # Rename the template app to the app name.
  342. path_ops.mv(constants.Templates.Dirs.CODE, app_name)
  343. path_ops.mv(
  344. os.path.join(app_name, template_dir.name + constants.Ext.PY),
  345. os.path.join(app_name, app_name + constants.Ext.PY),
  346. )
  347. # Fix up the imports.
  348. path_ops.find_replace(
  349. app_name,
  350. f"from {constants.Templates.Dirs.CODE}",
  351. f"from {app_name}",
  352. )
  353. def get_project_hash(raise_on_fail: bool = False) -> int | None:
  354. """Get the project hash from the reflex.json file if the file exists.
  355. Args:
  356. raise_on_fail: Whether to raise an error if the file does not exist.
  357. Returns:
  358. project_hash: The app hash.
  359. """
  360. if not os.path.exists(constants.Reflex.JSON) and not raise_on_fail:
  361. return None
  362. # Open and read the file
  363. with open(constants.Reflex.JSON, "r") as file:
  364. data = json.load(file)
  365. return data.get("project_hash")
  366. def initialize_web_directory():
  367. """Initialize the web directory on reflex init."""
  368. console.log("Initializing the web directory.")
  369. # Re-use the hash if one is already created, so we don't over-write it when running reflex init
  370. project_hash = get_project_hash()
  371. path_ops.cp(constants.Templates.Dirs.WEB_TEMPLATE, constants.Dirs.WEB)
  372. initialize_package_json()
  373. path_ops.mkdir(constants.Dirs.WEB_ASSETS)
  374. update_next_config()
  375. # Initialize the reflex json file.
  376. init_reflex_json(project_hash=project_hash)
  377. def _compile_package_json():
  378. return templates.PACKAGE_JSON.render(
  379. scripts={
  380. "dev": constants.PackageJson.Commands.DEV,
  381. "export": constants.PackageJson.Commands.EXPORT,
  382. "export_sitemap": constants.PackageJson.Commands.EXPORT_SITEMAP,
  383. "prod": constants.PackageJson.Commands.PROD,
  384. },
  385. dependencies=constants.PackageJson.DEPENDENCIES,
  386. dev_dependencies=constants.PackageJson.DEV_DEPENDENCIES,
  387. )
  388. def initialize_package_json():
  389. """Render and write in .web the package.json file."""
  390. output_path = constants.PackageJson.PATH
  391. code = _compile_package_json()
  392. with open(output_path, "w") as file:
  393. file.write(code)
  394. def init_reflex_json(project_hash: int | None):
  395. """Write the hash of the Reflex project to a REFLEX_JSON.
  396. Re-use the hash if one is already created, therefore do not
  397. overwrite it every time we run the reflex init command
  398. .
  399. Args:
  400. project_hash: The app hash.
  401. """
  402. if project_hash is not None:
  403. console.debug(f"Project hash is already set to {project_hash}.")
  404. else:
  405. # Get a random project hash.
  406. project_hash = random.getrandbits(128)
  407. console.debug(f"Setting project hash to {project_hash}.")
  408. # Write the hash and version to the reflex json file.
  409. reflex_json = {
  410. "version": constants.Reflex.VERSION,
  411. "project_hash": project_hash,
  412. }
  413. path_ops.update_json_file(constants.Reflex.JSON, reflex_json)
  414. def update_next_config(export=False):
  415. """Update Next.js config from Reflex config.
  416. Args:
  417. export: if the method run during reflex export.
  418. """
  419. next_config_file = os.path.join(constants.Dirs.WEB, constants.Next.CONFIG_FILE)
  420. next_config = _update_next_config(get_config(), export=export)
  421. with open(next_config_file, "w") as file:
  422. file.write(next_config)
  423. file.write("\n")
  424. def _update_next_config(config, export=False):
  425. next_config = {
  426. "basePath": config.frontend_path or "",
  427. "compress": config.next_compression,
  428. "reactStrictMode": True,
  429. "trailingSlash": True,
  430. }
  431. if export:
  432. next_config["output"] = "export"
  433. next_config["distDir"] = constants.Dirs.STATIC
  434. next_config_json = re.sub(r'"([^"]+)"(?=:)', r"\1", json.dumps(next_config))
  435. return f"module.exports = {next_config_json};"
  436. def remove_existing_bun_installation():
  437. """Remove existing bun installation."""
  438. console.debug("Removing existing bun installation.")
  439. if os.path.exists(get_config().bun_path):
  440. path_ops.rm(constants.Bun.ROOT_PATH)
  441. def download_and_run(url: str, *args, show_status: bool = False, **env):
  442. """Download and run a script.
  443. Args:
  444. url: The url of the script.
  445. args: The arguments to pass to the script.
  446. show_status: Whether to show the status of the script.
  447. env: The environment variables to use.
  448. """
  449. # Download the script
  450. console.debug(f"Downloading {url}")
  451. response = httpx.get(url)
  452. if response.status_code != httpx.codes.OK:
  453. response.raise_for_status()
  454. # Save the script to a temporary file.
  455. script = tempfile.NamedTemporaryFile()
  456. with open(script.name, "w") as f:
  457. f.write(response.text)
  458. # Run the script.
  459. env = {**os.environ, **env}
  460. process = processes.new_process(["bash", f.name, *args], env=env)
  461. show = processes.show_status if show_status else processes.show_logs
  462. show(f"Installing {url}", process)
  463. def download_and_extract_fnm_zip():
  464. """Download and run a script.
  465. Raises:
  466. Exit: If an error occurs while downloading or extracting the FNM zip.
  467. """
  468. # Download the zip file
  469. url = constants.Fnm.INSTALL_URL
  470. console.debug(f"Downloading {url}")
  471. fnm_zip_file = os.path.join(constants.Fnm.DIR, f"{constants.Fnm.FILENAME}.zip")
  472. # Function to download and extract the FNM zip release.
  473. try:
  474. # Download the FNM zip release.
  475. # TODO: show progress to improve UX
  476. with httpx.stream("GET", url, follow_redirects=True) as response:
  477. response.raise_for_status()
  478. with open(fnm_zip_file, "wb") as output_file:
  479. for chunk in response.iter_bytes():
  480. output_file.write(chunk)
  481. # Extract the downloaded zip file.
  482. with zipfile.ZipFile(fnm_zip_file, "r") as zip_ref:
  483. zip_ref.extractall(constants.Fnm.DIR)
  484. console.debug("FNM package downloaded and extracted successfully.")
  485. except Exception as e:
  486. console.error(f"An error occurred while downloading fnm package: {e}")
  487. raise typer.Exit(1) from e
  488. finally:
  489. # Clean up the downloaded zip file.
  490. path_ops.rm(fnm_zip_file)
  491. def install_node():
  492. """Install fnm and nodejs for use by Reflex.
  493. Independent of any existing system installations.
  494. """
  495. if not constants.Fnm.FILENAME:
  496. # fnm only support Linux, macOS and Windows distros.
  497. console.debug("")
  498. return
  499. # Skip installation if check_node_version() checks out
  500. if check_node_version():
  501. console.debug("Skipping node installation as it is already installed.")
  502. return
  503. path_ops.mkdir(constants.Fnm.DIR)
  504. if not os.path.exists(constants.Fnm.EXE):
  505. download_and_extract_fnm_zip()
  506. if constants.IS_WINDOWS:
  507. # Install node
  508. fnm_exe = Path(constants.Fnm.EXE).resolve()
  509. fnm_dir = Path(constants.Fnm.DIR).resolve()
  510. process = processes.new_process(
  511. [
  512. "powershell",
  513. "-Command",
  514. f'& "{fnm_exe}" install {constants.Node.VERSION} --fnm-dir "{fnm_dir}"',
  515. ],
  516. )
  517. else: # All other platforms (Linux, MacOS).
  518. # Add execute permissions to fnm executable.
  519. os.chmod(constants.Fnm.EXE, stat.S_IXUSR)
  520. # Install node.
  521. # Specify arm64 arch explicitly for M1s and M2s.
  522. architecture_arg = (
  523. ["--arch=arm64"]
  524. if platform.system() == "Darwin" and platform.machine() == "arm64"
  525. else []
  526. )
  527. process = processes.new_process(
  528. [
  529. constants.Fnm.EXE,
  530. "install",
  531. *architecture_arg,
  532. constants.Node.VERSION,
  533. "--fnm-dir",
  534. constants.Fnm.DIR,
  535. ],
  536. )
  537. processes.show_status("Installing node", process)
  538. def install_bun():
  539. """Install bun onto the user's system.
  540. Raises:
  541. FileNotFoundError: If required packages are not found.
  542. """
  543. # Bun is not supported on Windows.
  544. if constants.IS_WINDOWS:
  545. console.debug("Skipping bun installation on Windows.")
  546. return
  547. # Skip if bun is already installed.
  548. if os.path.exists(get_config().bun_path) and get_bun_version() == version.parse(
  549. constants.Bun.VERSION
  550. ):
  551. console.debug("Skipping bun installation as it is already installed.")
  552. return
  553. # if unzip is installed
  554. unzip_path = path_ops.which("unzip")
  555. if unzip_path is None:
  556. raise FileNotFoundError("Reflex requires unzip to be installed.")
  557. # Run the bun install script.
  558. download_and_run(
  559. constants.Bun.INSTALL_URL,
  560. f"bun-v{constants.Bun.VERSION}",
  561. BUN_INSTALL=constants.Bun.ROOT_PATH,
  562. )
  563. def _write_cached_procedure_file(payload: str, cache_file: str):
  564. with open(cache_file, "w") as f:
  565. f.write(payload)
  566. def _read_cached_procedure_file(cache_file: str) -> str | None:
  567. if os.path.exists(cache_file):
  568. with open(cache_file, "r") as f:
  569. return f.read()
  570. return None
  571. def _clear_cached_procedure_file(cache_file: str):
  572. if os.path.exists(cache_file):
  573. os.remove(cache_file)
  574. def cached_procedure(cache_file: str, payload_fn: Callable[..., str]):
  575. """Decorator to cache the runs of a procedure on disk. Procedures should not have
  576. a return value.
  577. Args:
  578. cache_file: The file to store the cache payload in.
  579. payload_fn: Function that computes cache payload from function args
  580. Returns:
  581. The decorated function.
  582. """
  583. def _inner_decorator(func):
  584. def _inner(*args, **kwargs):
  585. payload = _read_cached_procedure_file(cache_file)
  586. new_payload = payload_fn(*args, **kwargs)
  587. if payload != new_payload:
  588. _clear_cached_procedure_file(cache_file)
  589. func(*args, **kwargs)
  590. _write_cached_procedure_file(new_payload, cache_file)
  591. return _inner
  592. return _inner_decorator
  593. @cached_procedure(
  594. cache_file=os.path.join(
  595. constants.Dirs.WEB, "reflex.install_frontend_packages.cached"
  596. ),
  597. payload_fn=lambda p, c: f"{repr(sorted(list(p)))},{c.json()}",
  598. )
  599. def install_frontend_packages(packages: set[str], config: Config):
  600. """Installs the base and custom frontend packages.
  601. Args:
  602. packages: A list of package names to be installed.
  603. config: The config object.
  604. Example:
  605. >>> install_frontend_packages(["react", "react-dom"], get_config())
  606. """
  607. # Install the base packages.
  608. process = processes.new_process(
  609. [get_install_package_manager(), "install", "--loglevel", "silly"],
  610. cwd=constants.Dirs.WEB,
  611. shell=constants.IS_WINDOWS,
  612. )
  613. processes.show_status("Installing base frontend packages", process)
  614. if config.tailwind is not None:
  615. # install tailwind and tailwind plugins as dev dependencies.
  616. process = processes.new_process(
  617. [
  618. get_install_package_manager(),
  619. "add",
  620. "-d",
  621. constants.Tailwind.VERSION,
  622. *((config.tailwind or {}).get("plugins", [])),
  623. ],
  624. cwd=constants.Dirs.WEB,
  625. shell=constants.IS_WINDOWS,
  626. )
  627. processes.show_status("Installing tailwind", process)
  628. # Install custom packages defined in frontend_packages
  629. if len(packages) > 0:
  630. process = processes.new_process(
  631. [get_install_package_manager(), "add", *packages],
  632. cwd=constants.Dirs.WEB,
  633. shell=constants.IS_WINDOWS,
  634. )
  635. processes.show_status(
  636. "Installing frontend packages from config and components", process
  637. )
  638. def check_initialized(frontend: bool = True):
  639. """Check that the app is initialized.
  640. Args:
  641. frontend: Whether to check if the frontend is initialized.
  642. Raises:
  643. Exit: If the app is not initialized.
  644. """
  645. has_config = os.path.exists(constants.Config.FILE)
  646. has_reflex_dir = not frontend or os.path.exists(constants.Reflex.DIR)
  647. has_web_dir = not frontend or os.path.exists(constants.Dirs.WEB)
  648. # Check if the app is initialized.
  649. if not (has_config and has_reflex_dir and has_web_dir):
  650. console.error(
  651. f"The app is not initialized. Run [bold]{constants.Reflex.MODULE_NAME} init[/bold] first."
  652. )
  653. raise typer.Exit(1)
  654. # Check that the template is up to date.
  655. if frontend and not is_latest_template():
  656. console.error(
  657. "The base app template has updated. Run [bold]reflex init[/bold] again."
  658. )
  659. raise typer.Exit(1)
  660. # Print a warning for Windows users.
  661. if constants.IS_WINDOWS:
  662. console.warn(
  663. """Windows Subsystem for Linux (WSL) is recommended for improving initial install times."""
  664. )
  665. if sys.version_info >= (3, 12):
  666. console.warn(
  667. "Python 3.12 on Windows has known issues with hot reload (reflex-dev/reflex#2335). "
  668. "Python 3.11 is recommended with this release of Reflex."
  669. )
  670. def is_latest_template() -> bool:
  671. """Whether the app is using the latest template.
  672. Returns:
  673. Whether the app is using the latest template.
  674. """
  675. if not os.path.exists(constants.Reflex.JSON):
  676. return False
  677. with open(constants.Reflex.JSON) as f: # type: ignore
  678. app_version = json.load(f)["version"]
  679. return app_version == constants.Reflex.VERSION
  680. def validate_bun():
  681. """Validate bun if a custom bun path is specified to ensure the bun version meets requirements.
  682. Raises:
  683. Exit: If custom specified bun does not exist or does not meet requirements.
  684. """
  685. # if a custom bun path is provided, make sure its valid
  686. # This is specific to non-FHS OS
  687. bun_path = get_config().bun_path
  688. if bun_path != constants.Bun.DEFAULT_PATH:
  689. bun_version = get_bun_version()
  690. if not bun_version:
  691. console.error(
  692. "Failed to obtain bun version. Make sure the specified bun path in your config is correct."
  693. )
  694. raise typer.Exit(1)
  695. elif bun_version < version.parse(constants.Bun.MIN_VERSION):
  696. console.error(
  697. f"Reflex requires bun version {constants.Bun.VERSION} or higher to run, but the detected version is "
  698. f"{bun_version}. If you have specified a custom bun path in your config, make sure to provide one "
  699. f"that satisfies the minimum version requirement."
  700. )
  701. raise typer.Exit(1)
  702. def validate_frontend_dependencies(init=True):
  703. """Validate frontend dependencies to ensure they meet requirements.
  704. Args:
  705. init: whether running `reflex init`
  706. Raises:
  707. Exit: If the package manager is invalid.
  708. """
  709. if not init:
  710. # we only need to validate the package manager when running app.
  711. # `reflex init` will install the deps anyway(if applied).
  712. package_manager = get_package_manager()
  713. if not package_manager:
  714. console.error(
  715. "Could not find NPM package manager. Make sure you have node installed."
  716. )
  717. raise typer.Exit(1)
  718. if not check_node_version():
  719. node_version = get_node_version()
  720. console.error(
  721. f"Reflex requires node version {constants.Node.MIN_VERSION} or higher to run, but the detected version is {node_version}",
  722. )
  723. raise typer.Exit(1)
  724. if constants.IS_WINDOWS:
  725. return
  726. if init:
  727. # we only need bun for package install on `reflex init`.
  728. validate_bun()
  729. def ensure_reflex_installation_id() -> Optional[int]:
  730. """Ensures that a reflex distinct id has been generated and stored in the reflex directory.
  731. Returns:
  732. Distinct id.
  733. """
  734. try:
  735. initialize_reflex_user_directory()
  736. installation_id_file = os.path.join(constants.Reflex.DIR, "installation_id")
  737. installation_id = None
  738. if os.path.exists(installation_id_file):
  739. try:
  740. with open(installation_id_file, "r") as f:
  741. installation_id = int(f.read())
  742. except Exception:
  743. # If anything goes wrong at all... just regenerate.
  744. # Like what? Examples:
  745. # - file not exists
  746. # - file not readable
  747. # - content not parseable as an int
  748. pass
  749. if installation_id is None:
  750. installation_id = random.getrandbits(128)
  751. with open(installation_id_file, "w") as f:
  752. f.write(str(installation_id))
  753. # If we get here, installation_id is definitely set
  754. return installation_id
  755. except Exception as e:
  756. console.debug(f"Failed to ensure reflex installation id: {e}")
  757. return None
  758. def initialize_reflex_user_directory():
  759. """Initialize the reflex user directory."""
  760. # Create the reflex directory.
  761. path_ops.mkdir(constants.Reflex.DIR)
  762. def initialize_frontend_dependencies():
  763. """Initialize all the frontend dependencies."""
  764. # validate dependencies before install
  765. validate_frontend_dependencies()
  766. # Avoid warning about Node installation while we're trying to install it.
  767. global CURRENTLY_INSTALLING_NODE
  768. CURRENTLY_INSTALLING_NODE = True
  769. # Install the frontend dependencies.
  770. processes.run_concurrently(install_node, install_bun)
  771. CURRENTLY_INSTALLING_NODE = False
  772. # Set up the web directory.
  773. initialize_web_directory()
  774. def check_db_initialized() -> bool:
  775. """Check if the database migrations are initialized.
  776. Returns:
  777. True if alembic is initialized (or if database is not used).
  778. """
  779. if get_config().db_url is not None and not Path(constants.ALEMBIC_CONFIG).exists():
  780. console.error(
  781. "Database is not initialized. Run [bold]reflex db init[/bold] first."
  782. )
  783. return False
  784. return True
  785. def check_schema_up_to_date():
  786. """Check if the sqlmodel metadata matches the current database schema."""
  787. if get_config().db_url is None or not Path(constants.ALEMBIC_CONFIG).exists():
  788. return
  789. with model.Model.get_db_engine().connect() as connection:
  790. try:
  791. if model.Model.alembic_autogenerate(
  792. connection=connection,
  793. write_migration_scripts=False,
  794. ):
  795. console.error(
  796. "Detected database schema changes. Run [bold]reflex db makemigrations[/bold] "
  797. "to generate migration scripts.",
  798. )
  799. except CommandError as command_error:
  800. if "Target database is not up to date." in str(command_error):
  801. console.error(
  802. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  803. )
  804. def prompt_for_template() -> constants.Templates.Kind:
  805. """Prompt the user to specify a template.
  806. Returns:
  807. The template the user selected.
  808. """
  809. # Show the user the URLs of each temlate to preview.
  810. console.print("\nGet started with a template:")
  811. console.print("blank (https://blank-template.reflex.run) - A minimal template.")
  812. console.print(
  813. "sidebar (https://sidebar-template.reflex.run) - A template with a sidebar to navigate pages."
  814. )
  815. console.print("")
  816. # Prompt the user to select a template.
  817. template = console.ask(
  818. "Which template would you like to use?",
  819. choices=[
  820. template.value
  821. for template in constants.Templates.Kind
  822. if template.value != "demo"
  823. ],
  824. default=constants.Templates.Kind.BLANK.value,
  825. )
  826. # Return the template.
  827. return constants.Templates.Kind(template)
  828. def should_show_rx_chakra_migration_instructions() -> bool:
  829. """Should we show the migration instructions for rx.chakra.* => rx.*?.
  830. Returns:
  831. bool: True if we should show the migration instructions.
  832. """
  833. if os.getenv("REFLEX_PROMPT_MIGRATE_TO_RX_CHAKRA") == "yes":
  834. return True
  835. if not Path(constants.Config.FILE).exists():
  836. # They are running reflex init for the first time.
  837. return False
  838. existing_init_reflex_version = None
  839. reflex_json = Path(constants.Dirs.REFLEX_JSON)
  840. if reflex_json.exists():
  841. with reflex_json.open("r") as f:
  842. data = json.load(f)
  843. existing_init_reflex_version = data.get("version", None)
  844. if existing_init_reflex_version is None:
  845. # They clone a reflex app from git for the first time.
  846. # That app may or may not be 0.4 compatible.
  847. # So let's just show these instructions THIS TIME.
  848. return True
  849. if constants.Reflex.VERSION < "0.4":
  850. return False
  851. else:
  852. return existing_init_reflex_version < "0.4"
  853. def show_rx_chakra_migration_instructions():
  854. """Show the migration instructions for rx.chakra.* => rx.*."""
  855. console.log(
  856. "Prior to reflex 0.4.0, rx.* components are based on Chakra UI. They are now based on Radix UI. To stick to Chakra UI, use rx.chakra.*."
  857. )
  858. console.log("")
  859. console.log(
  860. "[bold]Run `reflex script keep-chakra` to automatically update your app."
  861. )
  862. console.log("")
  863. console.log(
  864. "For more details, please see https://reflex.dev/blog/2024-02-16-reflex-v0.4.0/"
  865. )
  866. def migrate_to_rx_chakra():
  867. """Migrate rx.button => r.chakra.button, etc."""
  868. file_pattern = os.path.join(get_config().app_name, "**/*.py")
  869. file_list = glob.glob(file_pattern, recursive=True)
  870. # Populate with all rx.<x> components that have been moved to rx.chakra.<x>
  871. patterns = {
  872. rf"\brx\.{name}\b": f"rx.chakra.{name}"
  873. for name in _get_rx_chakra_component_to_migrate()
  874. }
  875. for file_path in file_list:
  876. with FileInput(file_path, inplace=True) as file:
  877. for _line_num, line in enumerate(file):
  878. for old, new in patterns.items():
  879. line = re.sub(old, new, line)
  880. print(line, end="")
  881. def _get_rx_chakra_component_to_migrate() -> set[str]:
  882. from reflex.components.chakra import ChakraComponent
  883. rx_chakra_names = set(dir(reflex.chakra))
  884. names_to_migrate = set()
  885. # whitelist names will always be rewritten as rx.chakra.<x>
  886. whitelist = {
  887. "ColorModeIcon",
  888. "MultiSelect",
  889. "MultiSelectOption",
  890. "color_mode_icon",
  891. "multi_select",
  892. "multi_select_option",
  893. }
  894. for rx_chakra_name in sorted(rx_chakra_names):
  895. if rx_chakra_name.startswith("_"):
  896. continue
  897. rx_chakra_object = getattr(reflex.chakra, rx_chakra_name)
  898. try:
  899. if (
  900. inspect.ismethod(rx_chakra_object)
  901. and inspect.isclass(rx_chakra_object.__self__)
  902. and issubclass(rx_chakra_object.__self__, ChakraComponent)
  903. ):
  904. names_to_migrate.add(rx_chakra_name)
  905. elif inspect.isclass(rx_chakra_object) and issubclass(
  906. rx_chakra_object, ChakraComponent
  907. ):
  908. names_to_migrate.add(rx_chakra_name)
  909. elif rx_chakra_name in whitelist:
  910. names_to_migrate.add(rx_chakra_name)
  911. except Exception:
  912. raise
  913. return names_to_migrate
  914. def migrate_to_reflex():
  915. """Migration from Pynecone to Reflex."""
  916. # Check if the old config file exists.
  917. if not os.path.exists(constants.Config.PREVIOUS_FILE):
  918. return
  919. # Ask the user if they want to migrate.
  920. action = console.ask(
  921. "Pynecone project detected. Automatically upgrade to Reflex?",
  922. choices=["y", "n"],
  923. )
  924. if action == "n":
  925. return
  926. # Rename pcconfig to rxconfig.
  927. console.log(
  928. f"[bold]Renaming {constants.Config.PREVIOUS_FILE} to {constants.Config.FILE}"
  929. )
  930. os.rename(constants.Config.PREVIOUS_FILE, constants.Config.FILE)
  931. # Find all python files in the app directory.
  932. file_pattern = os.path.join(get_config().app_name, "**/*.py")
  933. file_list = glob.glob(file_pattern, recursive=True)
  934. # Add the config file to the list of files to be migrated.
  935. file_list.append(constants.Config.FILE)
  936. # Migrate all files.
  937. updates = {
  938. "Pynecone": "Reflex",
  939. "pynecone as pc": "reflex as rx",
  940. "pynecone.io": "reflex.dev",
  941. "pynecone": "reflex",
  942. "pc.": "rx.",
  943. "pcconfig": "rxconfig",
  944. }
  945. for file_path in file_list:
  946. with FileInput(file_path, inplace=True) as file:
  947. for line in file:
  948. for old, new in updates.items():
  949. line = line.replace(old, new)
  950. print(line, end="")