prerequisites.py 37 KB

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