prerequisites.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. """Everything related to fetching or initializing build prerequisites."""
  2. from __future__ import annotations
  3. import glob
  4. import json
  5. import os
  6. import platform
  7. import random
  8. import re
  9. import stat
  10. import sys
  11. import tempfile
  12. import zipfile
  13. from fileinput import FileInput
  14. from pathlib import Path
  15. from types import ModuleType
  16. import httpx
  17. import typer
  18. from alembic.util.exc import CommandError
  19. from packaging import version
  20. from redis import Redis
  21. from reflex import constants, model
  22. from reflex.config import get_config
  23. from reflex.utils import console, path_ops, processes
  24. def check_node_version() -> bool:
  25. """Check the version of Node.js.
  26. Returns:
  27. Whether the version of Node.js is valid.
  28. """
  29. current_version = get_node_version()
  30. if current_version:
  31. # Compare the version numbers
  32. return (
  33. current_version >= version.parse(constants.NODE_VERSION_MIN)
  34. if constants.IS_WINDOWS
  35. else current_version == version.parse(constants.NODE_VERSION)
  36. )
  37. return False
  38. def get_node_version() -> version.Version | None:
  39. """Get the version of node.
  40. Returns:
  41. The version of node.
  42. """
  43. try:
  44. result = processes.new_process([path_ops.get_node_path(), "-v"], run=True)
  45. # The output will be in the form "vX.Y.Z", but version.parse() can handle it
  46. return version.parse(result.stdout) # type: ignore
  47. except (FileNotFoundError, TypeError):
  48. return None
  49. def get_bun_version() -> version.Version | None:
  50. """Get the version of bun.
  51. Returns:
  52. The version of bun.
  53. """
  54. try:
  55. # Run the bun -v command and capture the output
  56. result = processes.new_process([get_config().bun_path, "-v"], run=True)
  57. return version.parse(result.stdout) # type: ignore
  58. except FileNotFoundError:
  59. return None
  60. def get_install_package_manager() -> str | None:
  61. """Get the package manager executable for installation.
  62. Currently on unix systems, bun is used for installation only.
  63. Returns:
  64. The path to the package manager.
  65. """
  66. # On Windows, we use npm instead of bun.
  67. if constants.IS_WINDOWS:
  68. return path_ops.get_npm_path()
  69. # On other platforms, we use bun.
  70. return get_config().bun_path
  71. def get_package_manager() -> str | None:
  72. """Get the package manager executable for running app.
  73. Currently on unix systems, npm is used for running the app only.
  74. Returns:
  75. The path to the package manager.
  76. """
  77. return path_ops.get_npm_path()
  78. def get_app() -> ModuleType:
  79. """Get the app module based on the default config.
  80. Returns:
  81. The app based on the default config.
  82. """
  83. config = get_config()
  84. module = ".".join([config.app_name, config.app_name])
  85. sys.path.insert(0, os.getcwd())
  86. return __import__(module, fromlist=(constants.APP_VAR,))
  87. def get_redis() -> Redis | None:
  88. """Get the redis client.
  89. Returns:
  90. The redis client.
  91. """
  92. config = get_config()
  93. if config.redis_url is None:
  94. return None
  95. redis_url, redis_port = config.redis_url.split(":")
  96. console.info(f"Using redis at {config.redis_url}")
  97. return Redis(host=redis_url, port=int(redis_port), db=0)
  98. def get_production_backend_url() -> str:
  99. """Get the production backend URL.
  100. Returns:
  101. The production backend URL.
  102. """
  103. config = get_config()
  104. return constants.PRODUCTION_BACKEND_URL.format(
  105. username=config.username,
  106. app_name=config.app_name,
  107. )
  108. def get_default_app_name() -> str:
  109. """Get the default app name.
  110. The default app name is the name of the current directory.
  111. Returns:
  112. The default app name.
  113. Raises:
  114. Exit: if the app directory name is reflex.
  115. """
  116. app_name = os.getcwd().split(os.path.sep)[-1].replace("-", "_")
  117. # Make sure the app is not named "reflex".
  118. if app_name == constants.MODULE_NAME:
  119. console.error(
  120. f"The app directory cannot be named [bold]{constants.MODULE_NAME}[/bold]."
  121. )
  122. raise typer.Exit(1)
  123. return app_name
  124. def create_config(app_name: str):
  125. """Create a new rxconfig file.
  126. Args:
  127. app_name: The name of the app.
  128. """
  129. # Import here to avoid circular imports.
  130. from reflex.compiler import templates
  131. config_name = f"{re.sub(r'[^a-zA-Z]', '', app_name).capitalize()}Config"
  132. with open(constants.CONFIG_FILE, "w") as f:
  133. console.debug(f"Creating {constants.CONFIG_FILE}")
  134. f.write(templates.RXCONFIG.render(app_name=app_name, config_name=config_name))
  135. def initialize_gitignore():
  136. """Initialize the template .gitignore file."""
  137. # The files to add to the .gitignore file.
  138. files = constants.DEFAULT_GITIGNORE
  139. # Subtract current ignored files.
  140. if os.path.exists(constants.GITIGNORE_FILE):
  141. with open(constants.GITIGNORE_FILE, "r") as f:
  142. files |= set([line.strip() for line in f.readlines()])
  143. # Write files to the .gitignore file.
  144. with open(constants.GITIGNORE_FILE, "w") as f:
  145. console.debug(f"Creating {constants.GITIGNORE_FILE}")
  146. f.write(f"{(path_ops.join(sorted(files))).lstrip()}")
  147. def initialize_app_directory(app_name: str, template: constants.Template):
  148. """Initialize the app directory on reflex init.
  149. Args:
  150. app_name: The name of the app.
  151. template: The template to use.
  152. """
  153. console.log("Initializing the app directory.")
  154. path_ops.cp(os.path.join(constants.TEMPLATE_DIR, "apps", template.value), app_name)
  155. path_ops.mv(
  156. os.path.join(app_name, template.value + ".py"),
  157. os.path.join(app_name, app_name + constants.PY_EXT),
  158. )
  159. path_ops.cp(constants.ASSETS_TEMPLATE_DIR, constants.APP_ASSETS_DIR)
  160. def initialize_web_directory():
  161. """Initialize the web directory on reflex init."""
  162. console.log("Initializing the web directory.")
  163. path_ops.cp(constants.WEB_TEMPLATE_DIR, constants.WEB_DIR)
  164. path_ops.mkdir(constants.WEB_ASSETS_DIR)
  165. # update nextJS config based on rxConfig
  166. next_config_file = os.path.join(constants.WEB_DIR, constants.NEXT_CONFIG_FILE)
  167. with open(next_config_file, "r") as file:
  168. lines = file.readlines()
  169. for i, line in enumerate(lines):
  170. if "compress:" in line:
  171. new_line = line.replace(
  172. "true", "true" if get_config().next_compression else "false"
  173. )
  174. lines[i] = new_line
  175. with open(next_config_file, "w") as file:
  176. file.writelines(lines)
  177. # Initialize the reflex json file.
  178. init_reflex_json()
  179. def init_reflex_json():
  180. """Write the hash of the Reflex project to a REFLEX_JSON."""
  181. # Get a random project hash.
  182. project_hash = random.getrandbits(128)
  183. console.debug(f"Setting project hash to {project_hash}.")
  184. # Write the hash and version to the reflex json file.
  185. reflex_json = {
  186. "version": constants.VERSION,
  187. "project_hash": project_hash,
  188. }
  189. path_ops.update_json_file(constants.REFLEX_JSON, reflex_json)
  190. def remove_existing_bun_installation():
  191. """Remove existing bun installation."""
  192. console.debug("Removing existing bun installation.")
  193. if os.path.exists(get_config().bun_path):
  194. path_ops.rm(constants.BUN_ROOT_PATH)
  195. def download_and_run(url: str, *args, show_status: bool = False, **env):
  196. """Download and run a script.
  197. Args:
  198. url: The url of the script.
  199. args: The arguments to pass to the script.
  200. show_status: Whether to show the status of the script.
  201. env: The environment variables to use.
  202. """
  203. # Download the script
  204. console.debug(f"Downloading {url}")
  205. response = httpx.get(url)
  206. if response.status_code != httpx.codes.OK:
  207. response.raise_for_status()
  208. # Save the script to a temporary file.
  209. script = tempfile.NamedTemporaryFile()
  210. with open(script.name, "w") as f:
  211. f.write(response.text)
  212. # Run the script.
  213. env = {**os.environ, **env}
  214. process = processes.new_process(["bash", f.name, *args], env=env)
  215. show = processes.show_status if show_status else processes.show_logs
  216. show(f"Installing {url}", process)
  217. def download_and_extract_fnm_zip():
  218. """Download and run a script.
  219. Raises:
  220. Exit: If an error occurs while downloading or extracting the FNM zip.
  221. """
  222. # Download the zip file
  223. url = constants.FNM_INSTALL_URL
  224. console.debug(f"Downloading {url}")
  225. fnm_zip_file = os.path.join(constants.FNM_DIR, f"{constants.FNM_FILENAME}.zip")
  226. # Function to download and extract the FNM zip release.
  227. try:
  228. # Download the FNM zip release.
  229. # TODO: show progress to improve UX
  230. with httpx.stream("GET", url, follow_redirects=True) as response:
  231. response.raise_for_status()
  232. with open(fnm_zip_file, "wb") as output_file:
  233. for chunk in response.iter_bytes():
  234. output_file.write(chunk)
  235. # Extract the downloaded zip file.
  236. with zipfile.ZipFile(fnm_zip_file, "r") as zip_ref:
  237. zip_ref.extractall(constants.FNM_DIR)
  238. console.debug("FNM package downloaded and extracted successfully.")
  239. except Exception as e:
  240. console.error(f"An error occurred while downloading fnm package: {e}")
  241. raise typer.Exit(1) from e
  242. finally:
  243. # Clean up the downloaded zip file.
  244. path_ops.rm(fnm_zip_file)
  245. def install_node():
  246. """Install fnm and nodejs for use by Reflex.
  247. Independent of any existing system installations.
  248. """
  249. if not constants.FNM_FILENAME:
  250. # fnm only support Linux, macOS and Windows distros.
  251. console.debug("")
  252. return
  253. path_ops.mkdir(constants.FNM_DIR)
  254. if not os.path.exists(constants.FNM_EXE):
  255. download_and_extract_fnm_zip()
  256. if constants.IS_WINDOWS:
  257. # Install node
  258. process = processes.new_process(
  259. [
  260. "powershell",
  261. "-Command",
  262. f'& "{constants.FNM_EXE}" install {constants.NODE_VERSION} --fnm-dir "{constants.FNM_DIR}"',
  263. ],
  264. )
  265. else: # All other platforms (Linux, MacOS).
  266. # TODO we can skip installation if check_node_version() checks out
  267. # Add execute permissions to fnm executable.
  268. os.chmod(constants.FNM_EXE, stat.S_IXUSR)
  269. # Install node.
  270. # Specify arm64 arch explicitly for M1s and M2s.
  271. architecture_arg = (
  272. ["--arch=arm64"]
  273. if platform.system() == "Darwin" and platform.machine() == "arm64"
  274. else []
  275. )
  276. process = processes.new_process(
  277. [
  278. constants.FNM_EXE,
  279. "install",
  280. *architecture_arg,
  281. constants.NODE_VERSION,
  282. "--fnm-dir",
  283. constants.FNM_DIR,
  284. ],
  285. )
  286. processes.show_status("Installing node", process)
  287. def install_bun():
  288. """Install bun onto the user's system.
  289. Raises:
  290. FileNotFoundError: If required packages are not found.
  291. """
  292. # Bun is not supported on Windows.
  293. if constants.IS_WINDOWS:
  294. console.debug("Skipping bun installation on Windows.")
  295. return
  296. # Skip if bun is already installed.
  297. if os.path.exists(get_config().bun_path):
  298. console.debug("Skipping bun installation as it is already installed.")
  299. return
  300. # if unzip is installed
  301. unzip_path = path_ops.which("unzip")
  302. if unzip_path is None:
  303. raise FileNotFoundError("Reflex requires unzip to be installed.")
  304. # Run the bun install script.
  305. download_and_run(
  306. constants.BUN_INSTALL_URL,
  307. f"bun-v{constants.BUN_VERSION}",
  308. BUN_INSTALL=constants.BUN_ROOT_PATH,
  309. )
  310. def install_frontend_packages(packages: list[str]):
  311. """Installs the base and custom frontend packages.
  312. Args:
  313. packages: A list of package names to be installed.
  314. Example:
  315. >>> install_frontend_packages(["react", "react-dom"])
  316. """
  317. # Install the base packages.
  318. process = processes.new_process(
  319. [get_install_package_manager(), "install", "--loglevel", "silly"],
  320. cwd=constants.WEB_DIR,
  321. shell=constants.IS_WINDOWS,
  322. )
  323. processes.show_status("Installing base frontend packages", process)
  324. # Install the custom packages, if any.
  325. if len(packages) > 0:
  326. process = processes.new_process(
  327. [get_install_package_manager(), "add", *packages],
  328. cwd=constants.WEB_DIR,
  329. shell=constants.IS_WINDOWS,
  330. )
  331. processes.show_status("Installing frontend packages for components", process)
  332. def check_initialized(frontend: bool = True):
  333. """Check that the app is initialized.
  334. Args:
  335. frontend: Whether to check if the frontend is initialized.
  336. Raises:
  337. Exit: If the app is not initialized.
  338. """
  339. has_config = os.path.exists(constants.CONFIG_FILE)
  340. has_reflex_dir = not frontend or os.path.exists(constants.REFLEX_DIR)
  341. has_web_dir = not frontend or os.path.exists(constants.WEB_DIR)
  342. # Check if the app is initialized.
  343. if not (has_config and has_reflex_dir and has_web_dir):
  344. console.error(
  345. f"The app is not initialized. Run [bold]{constants.MODULE_NAME} init[/bold] first."
  346. )
  347. raise typer.Exit(1)
  348. # Check that the template is up to date.
  349. if frontend and not is_latest_template():
  350. console.error(
  351. "The base app template has updated. Run [bold]reflex init[/bold] again."
  352. )
  353. raise typer.Exit(1)
  354. # Print a warning for Windows users.
  355. if constants.IS_WINDOWS:
  356. console.warn(
  357. """Windows Subsystem for Linux (WSL) is recommended for improving initial install times."""
  358. )
  359. def is_latest_template() -> bool:
  360. """Whether the app is using the latest template.
  361. Returns:
  362. Whether the app is using the latest template.
  363. """
  364. if not os.path.exists(constants.REFLEX_JSON):
  365. return False
  366. with open(constants.REFLEX_JSON) as f: # type: ignore
  367. app_version = json.load(f)["version"]
  368. return app_version == constants.VERSION
  369. def validate_bun():
  370. """Validate bun if a custom bun path is specified to ensure the bun version meets requirements.
  371. Raises:
  372. Exit: If custom specified bun does not exist or does not meet requirements.
  373. """
  374. # if a custom bun path is provided, make sure its valid
  375. # This is specific to non-FHS OS
  376. bun_path = get_config().bun_path
  377. if bun_path != constants.DEFAULT_BUN_PATH:
  378. bun_version = get_bun_version()
  379. if not bun_version:
  380. console.error(
  381. "Failed to obtain bun version. Make sure the specified bun path in your config is correct."
  382. )
  383. raise typer.Exit(1)
  384. elif bun_version < version.parse(constants.MIN_BUN_VERSION):
  385. console.error(
  386. f"Reflex requires bun version {constants.BUN_VERSION} or higher to run, but the detected version is "
  387. f"{bun_version}. If you have specified a custom bun path in your config, make sure to provide one "
  388. f"that satisfies the minimum version requirement."
  389. )
  390. raise typer.Exit(1)
  391. def validate_frontend_dependencies(init=True):
  392. """Validate frontend dependencies to ensure they meet requirements.
  393. Args:
  394. init: whether running `reflex init`
  395. Raises:
  396. Exit: If the package manager is invalid.
  397. """
  398. if not init:
  399. # we only need to validate the package manager when running app.
  400. # `reflex init` will install the deps anyway(if applied).
  401. package_manager = get_package_manager()
  402. if not package_manager:
  403. console.error(
  404. "Could not find NPM package manager. Make sure you have node installed."
  405. )
  406. raise typer.Exit(1)
  407. if not check_node_version():
  408. node_version = get_node_version()
  409. console.error(
  410. f"Reflex requires node version {constants.NODE_VERSION_MIN} or higher to run, but the detected version is {node_version}",
  411. )
  412. raise typer.Exit(1)
  413. if constants.IS_WINDOWS:
  414. return
  415. if init:
  416. # we only need bun for package install on `reflex init`.
  417. validate_bun()
  418. def initialize_frontend_dependencies():
  419. """Initialize all the frontend dependencies."""
  420. # Create the reflex directory.
  421. path_ops.mkdir(constants.REFLEX_DIR)
  422. # validate dependencies before install
  423. validate_frontend_dependencies()
  424. # Install the frontend dependencies.
  425. processes.run_concurrently(install_node, install_bun)
  426. # Set up the web directory.
  427. initialize_web_directory()
  428. def check_db_initialized() -> bool:
  429. """Check if the database migrations are initialized.
  430. Returns:
  431. True if alembic is initialized (or if database is not used).
  432. """
  433. if get_config().db_url is not None and not Path(constants.ALEMBIC_CONFIG).exists():
  434. console.error(
  435. "Database is not initialized. Run [bold]reflex db init[/bold] first."
  436. )
  437. return False
  438. return True
  439. def check_schema_up_to_date():
  440. """Check if the sqlmodel metadata matches the current database schema."""
  441. if get_config().db_url is None or not Path(constants.ALEMBIC_CONFIG).exists():
  442. return
  443. with model.Model.get_db_engine().connect() as connection:
  444. try:
  445. if model.Model.alembic_autogenerate(
  446. connection=connection,
  447. write_migration_scripts=False,
  448. ):
  449. console.error(
  450. "Detected database schema changes. Run [bold]reflex db makemigrations[/bold] "
  451. "to generate migration scripts.",
  452. )
  453. except CommandError as command_error:
  454. if "Target database is not up to date." in str(command_error):
  455. console.error(
  456. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  457. )
  458. def migrate_to_reflex():
  459. """Migration from Pynecone to Reflex."""
  460. # Check if the old config file exists.
  461. if not os.path.exists(constants.OLD_CONFIG_FILE):
  462. return
  463. # Ask the user if they want to migrate.
  464. action = console.ask(
  465. "Pynecone project detected. Automatically upgrade to Reflex?",
  466. choices=["y", "n"],
  467. )
  468. if action == "n":
  469. return
  470. # Rename pcconfig to rxconfig.
  471. console.log(
  472. f"[bold]Renaming {constants.OLD_CONFIG_FILE} to {constants.CONFIG_FILE}"
  473. )
  474. os.rename(constants.OLD_CONFIG_FILE, constants.CONFIG_FILE)
  475. # Find all python files in the app directory.
  476. file_pattern = os.path.join(get_config().app_name, "**/*.py")
  477. file_list = glob.glob(file_pattern, recursive=True)
  478. # Add the config file to the list of files to be migrated.
  479. file_list.append(constants.CONFIG_FILE)
  480. # Migrate all files.
  481. updates = {
  482. "Pynecone": "Reflex",
  483. "pynecone as pc": "reflex as rx",
  484. "pynecone.io": "reflex.dev",
  485. "pynecone": "reflex",
  486. "pc.": "rx.",
  487. "pcconfig": "rxconfig",
  488. }
  489. for file_path in file_list:
  490. with FileInput(file_path, inplace=True) as file:
  491. for line in file:
  492. for old, new in updates.items():
  493. line = line.replace(old, new)
  494. print(line, end="")