prerequisites.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. """Everything related to fetching or initializing build prerequisites."""
  2. from __future__ import annotations
  3. import glob
  4. import importlib
  5. import json
  6. import os
  7. import platform
  8. import random
  9. import re
  10. import stat
  11. import sys
  12. import tempfile
  13. import zipfile
  14. from fileinput import FileInput
  15. from pathlib import Path
  16. from types import ModuleType
  17. import httpx
  18. import pkg_resources
  19. import typer
  20. from alembic.util.exc import CommandError
  21. from packaging import version
  22. from redis.asyncio import Redis
  23. from reflex import constants, model
  24. from reflex.compiler import templates
  25. from reflex.config import get_config
  26. from reflex.utils import console, path_ops, processes
  27. def check_latest_package_version(package_name: str):
  28. """Check if the latest version of the package is installed.
  29. Args:
  30. package_name: The name of the package.
  31. """
  32. try:
  33. # Get the latest version from PyPI
  34. current_version = pkg_resources.get_distribution(package_name).version
  35. url = f"https://pypi.org/pypi/{package_name}/json"
  36. response = httpx.get(url)
  37. latest_version = response.json()["info"]["version"]
  38. if version.parse(current_version) < version.parse(latest_version):
  39. console.warn(
  40. f"Your version ({current_version}) of {package_name} is out of date. Upgrade to {latest_version} with 'pip install {package_name} --upgrade'"
  41. )
  42. except Exception:
  43. pass
  44. def check_node_version() -> bool:
  45. """Check the version of Node.js.
  46. Returns:
  47. Whether the version of Node.js is valid.
  48. """
  49. current_version = get_node_version()
  50. if current_version:
  51. # Compare the version numbers
  52. return (
  53. current_version >= version.parse(constants.Node.MIN_VERSION)
  54. if constants.IS_WINDOWS
  55. else current_version == version.parse(constants.Node.VERSION)
  56. )
  57. return False
  58. def get_node_version() -> version.Version | None:
  59. """Get the version of node.
  60. Returns:
  61. The version of node.
  62. """
  63. try:
  64. result = processes.new_process([path_ops.get_node_path(), "-v"], run=True)
  65. # The output will be in the form "vX.Y.Z", but version.parse() can handle it
  66. return version.parse(result.stdout) # type: ignore
  67. except (FileNotFoundError, TypeError):
  68. return None
  69. def get_fnm_version() -> version.Version | None:
  70. """Get the version of fnm.
  71. Returns:
  72. The version of FNM.
  73. """
  74. try:
  75. result = processes.new_process([constants.Fnm.EXE, "--version"], run=True)
  76. return version.parse(result.stdout.split(" ")[1]) # type: ignore
  77. except (FileNotFoundError, TypeError):
  78. return None
  79. def get_bun_version() -> version.Version | None:
  80. """Get the version of bun.
  81. Returns:
  82. The version of bun.
  83. """
  84. try:
  85. # Run the bun -v command and capture the output
  86. result = processes.new_process([get_config().bun_path, "-v"], run=True)
  87. return version.parse(result.stdout) # type: ignore
  88. except FileNotFoundError:
  89. return None
  90. def get_install_package_manager() -> str | None:
  91. """Get the package manager executable for installation.
  92. Currently on unix systems, bun is used for installation only.
  93. Returns:
  94. The path to the package manager.
  95. """
  96. # On Windows, we use npm instead of bun.
  97. if constants.IS_WINDOWS:
  98. return get_package_manager()
  99. # On other platforms, we use bun.
  100. return get_config().bun_path
  101. def get_package_manager() -> str | None:
  102. """Get the package manager executable for running app.
  103. Currently on unix systems, npm is used for running the app only.
  104. Returns:
  105. The path to the package manager.
  106. """
  107. npm_path = path_ops.get_npm_path()
  108. if npm_path is not None:
  109. npm_path = str(Path(npm_path).resolve())
  110. return npm_path
  111. def get_app(reload: bool = False) -> ModuleType:
  112. """Get the app module based on the default config.
  113. Args:
  114. reload: Re-import the app module from disk
  115. Returns:
  116. The app based on the default config.
  117. Raises:
  118. RuntimeError: If the app name is not set in the config.
  119. """
  120. os.environ[constants.RELOAD_CONFIG] = str(reload)
  121. config = get_config()
  122. if not config.app_name:
  123. raise RuntimeError(
  124. "Cannot get the app module because `app_name` is not set in rxconfig! "
  125. "If this error occurs in a reflex test case, ensure that `get_app` is mocked."
  126. )
  127. module = ".".join([config.app_name, config.app_name])
  128. sys.path.insert(0, os.getcwd())
  129. app = __import__(module, fromlist=(constants.CompileVars.APP,))
  130. if reload:
  131. importlib.reload(app)
  132. return app
  133. def get_redis() -> Redis | None:
  134. """Get the redis client.
  135. Returns:
  136. The redis client.
  137. """
  138. config = get_config()
  139. if not config.redis_url:
  140. return None
  141. if config.redis_url.startswith(("redis://", "rediss://", "unix://")):
  142. return Redis.from_url(config.redis_url)
  143. console.deprecate(
  144. feature_name="host[:port] style redis urls",
  145. reason="redis-py url syntax is now being used",
  146. deprecation_version="0.3.6",
  147. removal_version="0.4.0",
  148. )
  149. redis_url, has_port, redis_port = config.redis_url.partition(":")
  150. if not has_port:
  151. redis_port = 6379
  152. console.info(f"Using redis at {config.redis_url}")
  153. return Redis(host=redis_url, port=int(redis_port), db=0)
  154. def get_production_backend_url() -> str:
  155. """Get the production backend URL.
  156. Returns:
  157. The production backend URL.
  158. """
  159. config = get_config()
  160. return constants.PRODUCTION_BACKEND_URL.format(
  161. username=config.username,
  162. app_name=config.app_name,
  163. )
  164. def get_default_app_name() -> str:
  165. """Get the default app name.
  166. The default app name is the name of the current directory.
  167. Returns:
  168. The default app name.
  169. Raises:
  170. Exit: if the app directory name is reflex.
  171. """
  172. app_name = os.getcwd().split(os.path.sep)[-1].replace("-", "_")
  173. # Make sure the app is not named "reflex".
  174. if app_name == constants.Reflex.MODULE_NAME:
  175. console.error(
  176. f"The app directory cannot be named [bold]{constants.Reflex.MODULE_NAME}[/bold]."
  177. )
  178. raise typer.Exit(1)
  179. return app_name
  180. def create_config(app_name: str):
  181. """Create a new rxconfig file.
  182. Args:
  183. app_name: The name of the app.
  184. """
  185. # Import here to avoid circular imports.
  186. from reflex.compiler import templates
  187. config_name = f"{re.sub(r'[^a-zA-Z]', '', app_name).capitalize()}Config"
  188. with open(constants.Config.FILE, "w") as f:
  189. console.debug(f"Creating {constants.Config.FILE}")
  190. f.write(templates.RXCONFIG.render(app_name=app_name, config_name=config_name))
  191. def initialize_gitignore():
  192. """Initialize the template .gitignore file."""
  193. # The files to add to the .gitignore file.
  194. files = constants.GitIgnore.DEFAULTS
  195. # Subtract current ignored files.
  196. if os.path.exists(constants.GitIgnore.FILE):
  197. with open(constants.GitIgnore.FILE, "r") as f:
  198. files |= set([line.strip() for line in f.readlines()])
  199. # Write files to the .gitignore file.
  200. with open(constants.GitIgnore.FILE, "w") as f:
  201. console.debug(f"Creating {constants.GitIgnore.FILE}")
  202. f.write(f"{(path_ops.join(sorted(files))).lstrip()}")
  203. def initialize_requirements_txt():
  204. """Initialize the requirements.txt file.
  205. If absent, generate one for the user.
  206. If the requirements.txt does not have reflex as dependency,
  207. generate a requirement pinning current version and append to
  208. the requirements.txt file.
  209. """
  210. fp = Path(constants.RequirementsTxt.FILE)
  211. fp.touch(exist_ok=True)
  212. try:
  213. with open(fp, "r") as f:
  214. for req in f.readlines():
  215. # Check if we have a package name that is reflex
  216. if re.match(r"^reflex[^a-zA-Z0-9]", req):
  217. console.debug(f"{fp} already has reflex as dependency.")
  218. return
  219. with open(fp, "a") as f:
  220. f.write(
  221. f"\n{constants.RequirementsTxt.DEFAULTS_STUB}{constants.Reflex.VERSION}\n"
  222. )
  223. except Exception:
  224. console.info(f"Unable to check {fp} for reflex dependency.")
  225. def initialize_app_directory(app_name: str, template: constants.Templates.Kind):
  226. """Initialize the app directory on reflex init.
  227. Args:
  228. app_name: The name of the app.
  229. template: The template to use.
  230. """
  231. console.log("Initializing the app directory.")
  232. # Copy the template to the current directory.
  233. template_dir = Path(constants.Templates.Dirs.BASE, "apps", template.value)
  234. # Remove all pyc and __pycache__ dirs in template directory.
  235. for pyc_file in template_dir.glob("**/*.pyc"):
  236. pyc_file.unlink()
  237. for pycache_dir in template_dir.glob("**/__pycache__"):
  238. pycache_dir.rmdir()
  239. for file in template_dir.iterdir():
  240. # Copy the file to current directory but keep the name the same.
  241. path_ops.cp(str(file), file.name)
  242. # Rename the template app to the app name.
  243. path_ops.mv(constants.Templates.Dirs.CODE, app_name)
  244. path_ops.mv(
  245. os.path.join(app_name, template_dir.name + constants.Ext.PY),
  246. os.path.join(app_name, app_name + constants.Ext.PY),
  247. )
  248. # Fix up the imports.
  249. path_ops.find_replace(
  250. app_name,
  251. f"from {constants.Templates.Dirs.CODE}",
  252. f"from {app_name}",
  253. )
  254. def get_project_hash() -> int | None:
  255. """Get the project hash from the reflex.json file if the file exists.
  256. Returns:
  257. project_hash: The app hash.
  258. """
  259. if not os.path.exists(constants.Reflex.JSON):
  260. return None
  261. # Open and read the file
  262. with open(constants.Reflex.JSON, "r") as file:
  263. data = json.load(file)
  264. project_hash = data["project_hash"]
  265. return project_hash
  266. def initialize_web_directory():
  267. """Initialize the web directory on reflex init."""
  268. console.log("Initializing the web directory.")
  269. # Re-use the hash if one is already created, so we don't over-write it when running reflex init
  270. project_hash = get_project_hash()
  271. path_ops.cp(constants.Templates.Dirs.WEB_TEMPLATE, constants.Dirs.WEB)
  272. initialize_package_json()
  273. path_ops.mkdir(constants.Dirs.WEB_ASSETS)
  274. update_next_config()
  275. # Initialize the reflex json file.
  276. init_reflex_json(project_hash=project_hash)
  277. def _compile_package_json():
  278. return templates.PACKAGE_JSON.render(
  279. scripts={
  280. "dev": constants.PackageJson.Commands.DEV,
  281. "export": constants.PackageJson.Commands.EXPORT,
  282. "export_sitemap": constants.PackageJson.Commands.EXPORT_SITEMAP,
  283. "prod": constants.PackageJson.Commands.PROD,
  284. },
  285. dependencies=constants.PackageJson.DEPENDENCIES,
  286. dev_dependencies=constants.PackageJson.DEV_DEPENDENCIES,
  287. )
  288. def initialize_package_json():
  289. """Render and write in .web the package.json file."""
  290. output_path = constants.PackageJson.PATH
  291. code = _compile_package_json()
  292. with open(output_path, "w") as file:
  293. file.write(code)
  294. def init_reflex_json(project_hash: int | None):
  295. """Write the hash of the Reflex project to a REFLEX_JSON.
  296. Re-use the hash if one is already created, therefore do not
  297. overwrite it every time we run the reflex init command
  298. .
  299. Args:
  300. project_hash: The app hash.
  301. """
  302. if project_hash is not None:
  303. console.debug(f"Project hash is already set to {project_hash}.")
  304. else:
  305. # Get a random project hash.
  306. project_hash = random.getrandbits(128)
  307. console.debug(f"Setting project hash to {project_hash}.")
  308. # Write the hash and version to the reflex json file.
  309. reflex_json = {
  310. "version": constants.Reflex.VERSION,
  311. "project_hash": project_hash,
  312. }
  313. path_ops.update_json_file(constants.Reflex.JSON, reflex_json)
  314. def update_next_config(export=False):
  315. """Update Next.js config from Reflex config.
  316. Args:
  317. export: if the method run during reflex export.
  318. """
  319. next_config_file = os.path.join(constants.Dirs.WEB, constants.Next.CONFIG_FILE)
  320. next_config = _update_next_config(get_config(), export=export)
  321. with open(next_config_file, "w") as file:
  322. file.write(next_config)
  323. file.write("\n")
  324. def _update_next_config(config, export=False):
  325. next_config = {
  326. "basePath": config.frontend_path or "",
  327. "compress": config.next_compression,
  328. "reactStrictMode": True,
  329. "trailingSlash": True,
  330. }
  331. if export:
  332. next_config["output"] = "export"
  333. next_config["distDir"] = constants.Dirs.STATIC
  334. next_config_json = re.sub(r'"([^"]+)"(?=:)', r"\1", json.dumps(next_config))
  335. return f"module.exports = {next_config_json};"
  336. def remove_existing_bun_installation():
  337. """Remove existing bun installation."""
  338. console.debug("Removing existing bun installation.")
  339. if os.path.exists(get_config().bun_path):
  340. path_ops.rm(constants.Bun.ROOT_PATH)
  341. def download_and_run(url: str, *args, show_status: bool = False, **env):
  342. """Download and run a script.
  343. Args:
  344. url: The url of the script.
  345. args: The arguments to pass to the script.
  346. show_status: Whether to show the status of the script.
  347. env: The environment variables to use.
  348. """
  349. # Download the script
  350. console.debug(f"Downloading {url}")
  351. response = httpx.get(url)
  352. if response.status_code != httpx.codes.OK:
  353. response.raise_for_status()
  354. # Save the script to a temporary file.
  355. script = tempfile.NamedTemporaryFile()
  356. with open(script.name, "w") as f:
  357. f.write(response.text)
  358. # Run the script.
  359. env = {**os.environ, **env}
  360. process = processes.new_process(["bash", f.name, *args], env=env)
  361. show = processes.show_status if show_status else processes.show_logs
  362. show(f"Installing {url}", process)
  363. def download_and_extract_fnm_zip():
  364. """Download and run a script.
  365. Raises:
  366. Exit: If an error occurs while downloading or extracting the FNM zip.
  367. """
  368. # Download the zip file
  369. url = constants.Fnm.INSTALL_URL
  370. console.debug(f"Downloading {url}")
  371. fnm_zip_file = os.path.join(constants.Fnm.DIR, f"{constants.Fnm.FILENAME}.zip")
  372. # Function to download and extract the FNM zip release.
  373. try:
  374. # Download the FNM zip release.
  375. # TODO: show progress to improve UX
  376. with httpx.stream("GET", url, follow_redirects=True) as response:
  377. response.raise_for_status()
  378. with open(fnm_zip_file, "wb") as output_file:
  379. for chunk in response.iter_bytes():
  380. output_file.write(chunk)
  381. # Extract the downloaded zip file.
  382. with zipfile.ZipFile(fnm_zip_file, "r") as zip_ref:
  383. zip_ref.extractall(constants.Fnm.DIR)
  384. console.debug("FNM package downloaded and extracted successfully.")
  385. except Exception as e:
  386. console.error(f"An error occurred while downloading fnm package: {e}")
  387. raise typer.Exit(1) from e
  388. finally:
  389. # Clean up the downloaded zip file.
  390. path_ops.rm(fnm_zip_file)
  391. def install_node():
  392. """Install fnm and nodejs for use by Reflex.
  393. Independent of any existing system installations.
  394. """
  395. if not constants.Fnm.FILENAME:
  396. # fnm only support Linux, macOS and Windows distros.
  397. console.debug("")
  398. return
  399. path_ops.mkdir(constants.Fnm.DIR)
  400. if not os.path.exists(constants.Fnm.EXE):
  401. download_and_extract_fnm_zip()
  402. if constants.IS_WINDOWS:
  403. # Install node
  404. fnm_exe = Path(constants.Fnm.EXE).resolve()
  405. fnm_dir = Path(constants.Fnm.DIR).resolve()
  406. process = processes.new_process(
  407. [
  408. "powershell",
  409. "-Command",
  410. f'& "{fnm_exe}" install {constants.Node.VERSION} --fnm-dir "{fnm_dir}"',
  411. ],
  412. )
  413. else: # All other platforms (Linux, MacOS).
  414. # TODO we can skip installation if check_node_version() checks out
  415. # Add execute permissions to fnm executable.
  416. os.chmod(constants.Fnm.EXE, stat.S_IXUSR)
  417. # Install node.
  418. # Specify arm64 arch explicitly for M1s and M2s.
  419. architecture_arg = (
  420. ["--arch=arm64"]
  421. if platform.system() == "Darwin" and platform.machine() == "arm64"
  422. else []
  423. )
  424. process = processes.new_process(
  425. [
  426. constants.Fnm.EXE,
  427. "install",
  428. *architecture_arg,
  429. constants.Node.VERSION,
  430. "--fnm-dir",
  431. constants.Fnm.DIR,
  432. ],
  433. )
  434. processes.show_status("Installing node", process)
  435. def install_bun():
  436. """Install bun onto the user's system.
  437. Raises:
  438. FileNotFoundError: If required packages are not found.
  439. """
  440. # Bun is not supported on Windows.
  441. if constants.IS_WINDOWS:
  442. console.debug("Skipping bun installation on Windows.")
  443. return
  444. # Skip if bun is already installed.
  445. if os.path.exists(get_config().bun_path) and get_bun_version() == version.parse(
  446. constants.Bun.VERSION
  447. ):
  448. console.debug("Skipping bun installation as it is already installed.")
  449. return
  450. # if unzip is installed
  451. unzip_path = path_ops.which("unzip")
  452. if unzip_path is None:
  453. raise FileNotFoundError("Reflex requires unzip to be installed.")
  454. # Run the bun install script.
  455. download_and_run(
  456. constants.Bun.INSTALL_URL,
  457. f"bun-v{constants.Bun.VERSION}",
  458. BUN_INSTALL=constants.Bun.ROOT_PATH,
  459. )
  460. def install_frontend_packages(packages: set[str]):
  461. """Installs the base and custom frontend packages.
  462. Args:
  463. packages: A list of package names to be installed.
  464. Example:
  465. >>> install_frontend_packages(["react", "react-dom"])
  466. """
  467. # Install the base packages.
  468. process = processes.new_process(
  469. [get_install_package_manager(), "install", "--loglevel", "silly"],
  470. cwd=constants.Dirs.WEB,
  471. shell=constants.IS_WINDOWS,
  472. )
  473. processes.show_status("Installing base frontend packages", process)
  474. config = get_config()
  475. if config.tailwind is not None:
  476. # install tailwind and tailwind plugins as dev dependencies.
  477. process = processes.new_process(
  478. [
  479. get_install_package_manager(),
  480. "add",
  481. "-d",
  482. constants.Tailwind.VERSION,
  483. *((config.tailwind or {}).get("plugins", [])),
  484. ],
  485. cwd=constants.Dirs.WEB,
  486. shell=constants.IS_WINDOWS,
  487. )
  488. processes.show_status("Installing tailwind", process)
  489. # Install custom packages defined in frontend_packages
  490. if len(packages) > 0:
  491. process = processes.new_process(
  492. [get_install_package_manager(), "add", *packages],
  493. cwd=constants.Dirs.WEB,
  494. shell=constants.IS_WINDOWS,
  495. )
  496. processes.show_status(
  497. "Installing frontend packages from config and components", process
  498. )
  499. def check_initialized(frontend: bool = True):
  500. """Check that the app is initialized.
  501. Args:
  502. frontend: Whether to check if the frontend is initialized.
  503. Raises:
  504. Exit: If the app is not initialized.
  505. """
  506. has_config = os.path.exists(constants.Config.FILE)
  507. has_reflex_dir = not frontend or os.path.exists(constants.Reflex.DIR)
  508. has_web_dir = not frontend or os.path.exists(constants.Dirs.WEB)
  509. # Check if the app is initialized.
  510. if not (has_config and has_reflex_dir and has_web_dir):
  511. console.error(
  512. f"The app is not initialized. Run [bold]{constants.Reflex.MODULE_NAME} init[/bold] first."
  513. )
  514. raise typer.Exit(1)
  515. # Check that the template is up to date.
  516. if frontend and not is_latest_template():
  517. console.error(
  518. "The base app template has updated. Run [bold]reflex init[/bold] again."
  519. )
  520. raise typer.Exit(1)
  521. # Print a warning for Windows users.
  522. if constants.IS_WINDOWS:
  523. console.warn(
  524. """Windows Subsystem for Linux (WSL) is recommended for improving initial install times."""
  525. )
  526. def is_latest_template() -> bool:
  527. """Whether the app is using the latest template.
  528. Returns:
  529. Whether the app is using the latest template.
  530. """
  531. if not os.path.exists(constants.Reflex.JSON):
  532. return False
  533. with open(constants.Reflex.JSON) as f: # type: ignore
  534. app_version = json.load(f)["version"]
  535. return app_version == constants.Reflex.VERSION
  536. def validate_bun():
  537. """Validate bun if a custom bun path is specified to ensure the bun version meets requirements.
  538. Raises:
  539. Exit: If custom specified bun does not exist or does not meet requirements.
  540. """
  541. # if a custom bun path is provided, make sure its valid
  542. # This is specific to non-FHS OS
  543. bun_path = get_config().bun_path
  544. if bun_path != constants.Bun.DEFAULT_PATH:
  545. bun_version = get_bun_version()
  546. if not bun_version:
  547. console.error(
  548. "Failed to obtain bun version. Make sure the specified bun path in your config is correct."
  549. )
  550. raise typer.Exit(1)
  551. elif bun_version < version.parse(constants.Bun.MIN_VERSION):
  552. console.error(
  553. f"Reflex requires bun version {constants.Bun.VERSION} or higher to run, but the detected version is "
  554. f"{bun_version}. If you have specified a custom bun path in your config, make sure to provide one "
  555. f"that satisfies the minimum version requirement."
  556. )
  557. raise typer.Exit(1)
  558. def validate_frontend_dependencies(init=True):
  559. """Validate frontend dependencies to ensure they meet requirements.
  560. Args:
  561. init: whether running `reflex init`
  562. Raises:
  563. Exit: If the package manager is invalid.
  564. """
  565. if not init:
  566. # we only need to validate the package manager when running app.
  567. # `reflex init` will install the deps anyway(if applied).
  568. package_manager = get_package_manager()
  569. if not package_manager:
  570. console.error(
  571. "Could not find NPM package manager. Make sure you have node installed."
  572. )
  573. raise typer.Exit(1)
  574. if not check_node_version():
  575. node_version = get_node_version()
  576. console.error(
  577. f"Reflex requires node version {constants.Node.MIN_VERSION} or higher to run, but the detected version is {node_version}",
  578. )
  579. raise typer.Exit(1)
  580. if constants.IS_WINDOWS:
  581. return
  582. if init:
  583. # we only need bun for package install on `reflex init`.
  584. validate_bun()
  585. def initialize_frontend_dependencies():
  586. """Initialize all the frontend dependencies."""
  587. # Create the reflex directory.
  588. path_ops.mkdir(constants.Reflex.DIR)
  589. # validate dependencies before install
  590. validate_frontend_dependencies()
  591. # Install the frontend dependencies.
  592. processes.run_concurrently(install_node, install_bun)
  593. # Set up the web directory.
  594. initialize_web_directory()
  595. def check_db_initialized() -> bool:
  596. """Check if the database migrations are initialized.
  597. Returns:
  598. True if alembic is initialized (or if database is not used).
  599. """
  600. if get_config().db_url is not None and not Path(constants.ALEMBIC_CONFIG).exists():
  601. console.error(
  602. "Database is not initialized. Run [bold]reflex db init[/bold] first."
  603. )
  604. return False
  605. return True
  606. def check_schema_up_to_date():
  607. """Check if the sqlmodel metadata matches the current database schema."""
  608. if get_config().db_url is None or not Path(constants.ALEMBIC_CONFIG).exists():
  609. return
  610. with model.Model.get_db_engine().connect() as connection:
  611. try:
  612. if model.Model.alembic_autogenerate(
  613. connection=connection,
  614. write_migration_scripts=False,
  615. ):
  616. console.error(
  617. "Detected database schema changes. Run [bold]reflex db makemigrations[/bold] "
  618. "to generate migration scripts.",
  619. )
  620. except CommandError as command_error:
  621. if "Target database is not up to date." in str(command_error):
  622. console.error(
  623. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  624. )
  625. def prompt_for_template() -> constants.Templates.Kind:
  626. """Prompt the user to specify a template.
  627. Returns:
  628. The template the user selected.
  629. """
  630. # Show the user the URLs of each temlate to preview.
  631. console.print("\nGet started with a template:")
  632. console.print("blank (https://blank-template.reflex.run) - A minimal template.")
  633. console.print(
  634. "sidebar (https://sidebar-template.reflex.run) - A template with a sidebar to navigate pages."
  635. )
  636. console.print("")
  637. # Prompt the user to select a template.
  638. template = console.ask(
  639. "Which template would you like to use?",
  640. choices=[
  641. template.value
  642. for template in constants.Templates.Kind
  643. if template.value != "demo"
  644. ],
  645. default=constants.Templates.Kind.BLANK.value,
  646. )
  647. # Return the template.
  648. return constants.Templates.Kind(template)
  649. def migrate_to_reflex():
  650. """Migration from Pynecone to Reflex."""
  651. # Check if the old config file exists.
  652. if not os.path.exists(constants.Config.PREVIOUS_FILE):
  653. return
  654. # Ask the user if they want to migrate.
  655. action = console.ask(
  656. "Pynecone project detected. Automatically upgrade to Reflex?",
  657. choices=["y", "n"],
  658. )
  659. if action == "n":
  660. return
  661. # Rename pcconfig to rxconfig.
  662. console.log(
  663. f"[bold]Renaming {constants.Config.PREVIOUS_FILE} to {constants.Config.FILE}"
  664. )
  665. os.rename(constants.Config.PREVIOUS_FILE, constants.Config.FILE)
  666. # Find all python files in the app directory.
  667. file_pattern = os.path.join(get_config().app_name, "**/*.py")
  668. file_list = glob.glob(file_pattern, recursive=True)
  669. # Add the config file to the list of files to be migrated.
  670. file_list.append(constants.Config.FILE)
  671. # Migrate all files.
  672. updates = {
  673. "Pynecone": "Reflex",
  674. "pynecone as pc": "reflex as rx",
  675. "pynecone.io": "reflex.dev",
  676. "pynecone": "reflex",
  677. "pc.": "rx.",
  678. "pcconfig": "rxconfig",
  679. }
  680. for file_path in file_list:
  681. with FileInput(file_path, inplace=True) as file:
  682. for line in file:
  683. for old, new in updates.items():
  684. line = line.replace(old, new)
  685. print(line, end="")