prerequisites.py 18 KB

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