prerequisites.py 20 KB

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