prerequisites.py 16 KB

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