prerequisites.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086
  1. """Everything related to fetching or initializing build prerequisites."""
  2. from __future__ import annotations
  3. import contextlib
  4. import dataclasses
  5. import functools
  6. import importlib
  7. import importlib.metadata
  8. import importlib.util
  9. import io
  10. import json
  11. import os
  12. import platform
  13. import random
  14. import re
  15. import shutil
  16. import sys
  17. import tempfile
  18. import time
  19. import typing
  20. import zipfile
  21. from collections.abc import Callable, Sequence
  22. from datetime import datetime
  23. from pathlib import Path
  24. from types import ModuleType
  25. from typing import NamedTuple
  26. from urllib.parse import urlparse
  27. import click
  28. import httpx
  29. from alembic.util.exc import CommandError
  30. from packaging import version
  31. from redis import Redis as RedisSync
  32. from redis.asyncio import Redis
  33. from redis.exceptions import RedisError
  34. from reflex import constants, model
  35. from reflex.compiler import templates
  36. from reflex.config import Config, environment, get_config
  37. from reflex.utils import console, net, path_ops, processes, redir
  38. from reflex.utils.exceptions import (
  39. GeneratedCodeHasNoFunctionDefsError,
  40. SystemPackageMissingError,
  41. )
  42. from reflex.utils.registry import get_npm_registry
  43. if typing.TYPE_CHECKING:
  44. from reflex.app import App
  45. class AppInfo(NamedTuple):
  46. """A tuple containing the app instance and module."""
  47. app: App
  48. module: ModuleType
  49. @dataclasses.dataclass(frozen=True)
  50. class Template:
  51. """A template for a Reflex app."""
  52. name: str
  53. description: str
  54. code_url: str
  55. @dataclasses.dataclass(frozen=True)
  56. class CpuInfo:
  57. """Model to save cpu info."""
  58. manufacturer_id: str | None
  59. model_name: str | None
  60. address_width: int | None
  61. def get_web_dir() -> Path:
  62. """Get the working directory for the frontend.
  63. Can be overridden with REFLEX_WEB_WORKDIR.
  64. Returns:
  65. The working directory.
  66. """
  67. return environment.REFLEX_WEB_WORKDIR.get()
  68. def get_states_dir() -> Path:
  69. """Get the working directory for the states.
  70. Can be overridden with REFLEX_STATES_WORKDIR.
  71. Returns:
  72. The working directory.
  73. """
  74. return environment.REFLEX_STATES_WORKDIR.get()
  75. def get_backend_dir() -> Path:
  76. """Get the working directory for the backend.
  77. Returns:
  78. The working directory.
  79. """
  80. return get_web_dir() / constants.Dirs.BACKEND
  81. def check_latest_package_version(package_name: str):
  82. """Check if the latest version of the package is installed.
  83. Args:
  84. package_name: The name of the package.
  85. """
  86. if environment.REFLEX_CHECK_LATEST_VERSION.get() is False:
  87. return
  88. try:
  89. console.debug(f"Checking for the latest version of {package_name}...")
  90. # Get the latest version from PyPI
  91. current_version = importlib.metadata.version(package_name)
  92. url = f"https://pypi.org/pypi/{package_name}/json"
  93. response = net.get(url)
  94. latest_version = response.json()["info"]["version"]
  95. console.debug(f"Latest version of {package_name}: {latest_version}")
  96. if get_or_set_last_reflex_version_check_datetime():
  97. # Versions were already checked and saved in reflex.json, no need to warn again
  98. return
  99. if version.parse(current_version) < version.parse(latest_version):
  100. # Show a warning when the host version is older than PyPI version
  101. console.warn(
  102. f"Your version ({current_version}) of {package_name} is out of date. Upgrade to {latest_version} with 'pip install {package_name} --upgrade'"
  103. )
  104. except Exception:
  105. console.debug(f"Failed to check for the latest version of {package_name}.")
  106. pass
  107. def get_or_set_last_reflex_version_check_datetime():
  108. """Get the last time a check was made for the latest reflex version.
  109. This is typically useful for cases where the host reflex version is
  110. less than that on Pypi.
  111. Returns:
  112. The last version check datetime.
  113. """
  114. reflex_json_file = get_web_dir() / constants.Reflex.JSON
  115. if not reflex_json_file.exists():
  116. return None
  117. # Open and read the file
  118. data = json.loads(reflex_json_file.read_text())
  119. last_version_check_datetime = data.get("last_version_check_datetime")
  120. if not last_version_check_datetime:
  121. data.update({"last_version_check_datetime": str(datetime.now())})
  122. path_ops.update_json_file(reflex_json_file, data)
  123. return last_version_check_datetime
  124. def set_last_reflex_run_time():
  125. """Set the last Reflex run time."""
  126. path_ops.update_json_file(
  127. get_web_dir() / constants.Reflex.JSON,
  128. {"last_reflex_run_datetime": str(datetime.now())},
  129. )
  130. def check_node_version() -> bool:
  131. """Check the version of Node.js.
  132. Returns:
  133. Whether the version of Node.js is valid.
  134. """
  135. current_version = get_node_version()
  136. return current_version is not None and current_version >= version.parse(
  137. constants.Node.MIN_VERSION
  138. )
  139. def get_node_version() -> version.Version | None:
  140. """Get the version of node.
  141. Returns:
  142. The version of node.
  143. """
  144. node_path = path_ops.get_node_path()
  145. if node_path is None:
  146. return None
  147. try:
  148. result = processes.new_process([node_path, "-v"], run=True)
  149. # The output will be in the form "vX.Y.Z", but version.parse() can handle it
  150. return version.parse(result.stdout)
  151. except (FileNotFoundError, TypeError):
  152. return None
  153. def get_bun_version(bun_path: Path | None = None) -> version.Version | None:
  154. """Get the version of bun.
  155. Args:
  156. bun_path: The path to the bun executable.
  157. Returns:
  158. The version of bun.
  159. """
  160. bun_path = bun_path or path_ops.get_bun_path()
  161. if bun_path is None:
  162. return None
  163. try:
  164. # Run the bun -v command and capture the output
  165. result = processes.new_process([str(bun_path), "-v"], run=True)
  166. return version.parse(str(result.stdout))
  167. except FileNotFoundError:
  168. return None
  169. except version.InvalidVersion as e:
  170. console.warn(
  171. f"The detected bun version ({e.args[0]}) is not valid. Defaulting to None."
  172. )
  173. return None
  174. def prefer_npm_over_bun() -> bool:
  175. """Check if npm should be preferred over bun.
  176. Returns:
  177. If npm should be preferred over bun.
  178. """
  179. return npm_escape_hatch() or (
  180. constants.IS_WINDOWS and windows_check_onedrive_in_path()
  181. )
  182. def get_nodejs_compatible_package_managers(
  183. raise_on_none: bool = True,
  184. ) -> Sequence[str]:
  185. """Get the package manager executable for installation. Typically, bun is used for installation.
  186. Args:
  187. raise_on_none: Whether to raise an error if the package manager is not found.
  188. Returns:
  189. The path to the package manager.
  190. Raises:
  191. FileNotFoundError: If the package manager is not found and raise_on_none is True.
  192. """
  193. bun_package_manager = (
  194. str(bun_path) if (bun_path := path_ops.get_bun_path()) else None
  195. )
  196. npm_package_manager = (
  197. str(npm_path) if (npm_path := path_ops.get_npm_path()) else None
  198. )
  199. if prefer_npm_over_bun():
  200. package_managers = [npm_package_manager, bun_package_manager]
  201. else:
  202. package_managers = [bun_package_manager, npm_package_manager]
  203. package_managers = list(filter(None, package_managers))
  204. if not package_managers and raise_on_none:
  205. raise FileNotFoundError(
  206. "Bun or npm not found. You might need to rerun `reflex init` or install either."
  207. )
  208. return package_managers
  209. def is_outdated_nodejs_installed():
  210. """Check if the installed Node.js version is outdated.
  211. Returns:
  212. If the installed Node.js version is outdated.
  213. """
  214. current_version = get_node_version()
  215. if current_version is not None and current_version < version.parse(
  216. constants.Node.MIN_VERSION
  217. ):
  218. console.warn(
  219. f"Your version ({current_version}) of Node.js is out of date. Upgrade to {constants.Node.MIN_VERSION} or higher."
  220. )
  221. return True
  222. return False
  223. def get_js_package_executor(raise_on_none: bool = False) -> Sequence[Sequence[str]]:
  224. """Get the paths to package managers for running commands. Ordered by preference.
  225. This is currently identical to get_install_package_managers, but may change in the future.
  226. Args:
  227. raise_on_none: Whether to raise an error if no package managers is not found.
  228. Returns:
  229. The paths to the package managers as a list of lists, where each list is the command to run and its arguments.
  230. Raises:
  231. FileNotFoundError: If no package managers are found and raise_on_none is True.
  232. """
  233. bun_package_manager = (
  234. [str(bun_path)] + (["--bun"] if is_outdated_nodejs_installed() else [])
  235. if (bun_path := path_ops.get_bun_path())
  236. else None
  237. )
  238. npm_package_manager = (
  239. [str(npm_path)] if (npm_path := path_ops.get_npm_path()) else None
  240. )
  241. if prefer_npm_over_bun():
  242. package_managers = [npm_package_manager, bun_package_manager]
  243. else:
  244. package_managers = [bun_package_manager, npm_package_manager]
  245. package_managers = list(filter(None, package_managers))
  246. if not package_managers and raise_on_none:
  247. raise FileNotFoundError(
  248. "Bun or npm not found. You might need to rerun `reflex init` or install either."
  249. )
  250. return package_managers
  251. def windows_check_onedrive_in_path() -> bool:
  252. """For windows, check if oneDrive is present in the project dir path.
  253. Returns:
  254. If oneDrive is in the path of the project directory.
  255. """
  256. return "onedrive" in str(Path.cwd()).lower()
  257. def npm_escape_hatch() -> bool:
  258. """If the user sets REFLEX_USE_NPM, prefer npm over bun.
  259. Returns:
  260. If the user has set REFLEX_USE_NPM.
  261. """
  262. return environment.REFLEX_USE_NPM.get()
  263. def _check_app_name(config: Config):
  264. """Check if the app name is set in the config.
  265. Args:
  266. config: The config object.
  267. Raises:
  268. RuntimeError: If the app name is not set in the config.
  269. """
  270. if not config.app_name:
  271. raise RuntimeError(
  272. "Cannot get the app module because `app_name` is not set in rxconfig! "
  273. "If this error occurs in a reflex test case, ensure that `get_app` is mocked."
  274. )
  275. def get_app(reload: bool = False) -> ModuleType:
  276. """Get the app module based on the default config.
  277. Args:
  278. reload: Re-import the app module from disk
  279. Returns:
  280. The app based on the default config.
  281. Raises:
  282. Exception: If an error occurs while getting the app module.
  283. """
  284. from reflex.utils import telemetry
  285. try:
  286. config = get_config()
  287. _check_app_name(config)
  288. module = config.module
  289. sys.path.insert(0, str(Path.cwd()))
  290. app = (
  291. __import__(module, fromlist=(constants.CompileVars.APP,))
  292. if not config.app_module
  293. else config.app_module
  294. )
  295. if reload:
  296. from reflex.page import DECORATED_PAGES
  297. from reflex.state import reload_state_module
  298. # Reset rx.State subclasses to avoid conflict when reloading.
  299. reload_state_module(module=module)
  300. DECORATED_PAGES.clear()
  301. # Reload the app module.
  302. importlib.reload(app)
  303. except Exception as ex:
  304. telemetry.send_error(ex, context="frontend")
  305. raise
  306. else:
  307. return app
  308. def get_and_validate_app(reload: bool = False) -> AppInfo:
  309. """Get the app instance based on the default config and validate it.
  310. Args:
  311. reload: Re-import the app module from disk
  312. Returns:
  313. The app instance and the app module.
  314. Raises:
  315. RuntimeError: If the app instance is not an instance of rx.App.
  316. """
  317. from reflex.app import App
  318. app_module = get_app(reload=reload)
  319. app = getattr(app_module, constants.CompileVars.APP)
  320. if not isinstance(app, App):
  321. raise RuntimeError(
  322. "The app instance in the specified app_module_import in rxconfig must be an instance of rx.App."
  323. )
  324. return AppInfo(app=app, module=app_module)
  325. def validate_app(reload: bool = False) -> None:
  326. """Validate the app instance based on the default config.
  327. Args:
  328. reload: Re-import the app module from disk
  329. """
  330. get_and_validate_app(reload=reload)
  331. def get_compiled_app(
  332. reload: bool = False, export: bool = False, dry_run: bool = False
  333. ) -> ModuleType:
  334. """Get the app module based on the default config after first compiling it.
  335. Args:
  336. reload: Re-import the app module from disk
  337. export: Compile the app for export
  338. dry_run: If True, do not write the compiled app to disk.
  339. Returns:
  340. The compiled app based on the default config.
  341. """
  342. app, app_module = get_and_validate_app(reload=reload)
  343. # For py3.9 compatibility when redis is used, we MUST add any decorator pages
  344. # before compiling the app in a thread to avoid event loop error (REF-2172).
  345. app._apply_decorated_pages()
  346. app._compile(export=export, dry_run=dry_run)
  347. return app_module
  348. def compile_app(
  349. reload: bool = False, export: bool = False, dry_run: bool = False
  350. ) -> None:
  351. """Compile the app module based on the default config.
  352. Args:
  353. reload: Re-import the app module from disk
  354. export: Compile the app for export
  355. dry_run: If True, do not write the compiled app to disk.
  356. """
  357. get_compiled_app(reload=reload, export=export, dry_run=dry_run)
  358. def _can_colorize() -> bool:
  359. """Check if the output can be colorized.
  360. Copied from _colorize.can_colorize.
  361. https://raw.githubusercontent.com/python/cpython/refs/heads/main/Lib/_colorize.py
  362. Returns:
  363. If the output can be colorized
  364. """
  365. file = sys.stdout
  366. if not sys.flags.ignore_environment:
  367. if os.environ.get("PYTHON_COLORS") == "0":
  368. return False
  369. if os.environ.get("PYTHON_COLORS") == "1":
  370. return True
  371. if os.environ.get("NO_COLOR"):
  372. return False
  373. if os.environ.get("FORCE_COLOR"):
  374. return True
  375. if os.environ.get("TERM") == "dumb":
  376. return False
  377. if not hasattr(file, "fileno"):
  378. return False
  379. if sys.platform == "win32":
  380. try:
  381. import nt
  382. if not nt._supports_virtual_terminal():
  383. return False
  384. except (ImportError, AttributeError):
  385. return False
  386. try:
  387. return os.isatty(file.fileno())
  388. except io.UnsupportedOperation:
  389. return file.isatty()
  390. def compile_or_validate_app(compile: bool = False) -> bool:
  391. """Compile or validate the app module based on the default config.
  392. Args:
  393. compile: Whether to compile the app.
  394. Returns:
  395. If the app is compiled successfully.
  396. """
  397. try:
  398. if compile:
  399. compile_app()
  400. else:
  401. validate_app()
  402. except Exception as e:
  403. if isinstance(e, click.exceptions.Exit):
  404. return False
  405. import traceback
  406. sys_exception = sys.exception()
  407. try:
  408. colorize = _can_colorize()
  409. traceback.print_exception(e, colorize=colorize) # pyright: ignore[reportCallIssue]
  410. except Exception:
  411. traceback.print_exception(sys_exception)
  412. return False
  413. return True
  414. def get_redis() -> Redis | None:
  415. """Get the asynchronous redis client.
  416. Returns:
  417. The asynchronous redis client.
  418. """
  419. if (redis_url := parse_redis_url()) is not None:
  420. return Redis.from_url(
  421. redis_url,
  422. retry_on_error=[RedisError],
  423. )
  424. return None
  425. def get_redis_sync() -> RedisSync | None:
  426. """Get the synchronous redis client.
  427. Returns:
  428. The synchronous redis client.
  429. """
  430. if (redis_url := parse_redis_url()) is not None:
  431. return RedisSync.from_url(
  432. redis_url,
  433. retry_on_error=[RedisError],
  434. )
  435. return None
  436. def parse_redis_url() -> str | None:
  437. """Parse the REDIS_URL in config if applicable.
  438. Returns:
  439. If url is non-empty, return the URL as it is.
  440. Raises:
  441. ValueError: If the REDIS_URL is not a supported scheme.
  442. """
  443. config = get_config()
  444. if not config.redis_url:
  445. return None
  446. if not config.redis_url.startswith(("redis://", "rediss://", "unix://")):
  447. raise ValueError(
  448. "REDIS_URL must start with 'redis://', 'rediss://', or 'unix://'."
  449. )
  450. return config.redis_url
  451. async def get_redis_status() -> dict[str, bool | None]:
  452. """Checks the status of the Redis connection.
  453. Attempts to connect to Redis and send a ping command to verify connectivity.
  454. Returns:
  455. The status of the Redis connection.
  456. """
  457. try:
  458. status = True
  459. redis_client = get_redis_sync()
  460. if redis_client is not None:
  461. redis_client.ping()
  462. else:
  463. status = None
  464. except RedisError:
  465. status = False
  466. return {"redis": status}
  467. def validate_app_name(app_name: str | None = None) -> str:
  468. """Validate the app name.
  469. The default app name is the name of the current directory.
  470. Args:
  471. app_name: the name passed by user during reflex init
  472. Returns:
  473. The app name after validation.
  474. Raises:
  475. Exit: if the app directory name is reflex or if the name is not standard for a python package name.
  476. """
  477. app_name = app_name if app_name else Path.cwd().name.replace("-", "_")
  478. # Make sure the app is not named "reflex".
  479. if app_name.lower() == constants.Reflex.MODULE_NAME:
  480. console.error(
  481. f"The app directory cannot be named [bold]{constants.Reflex.MODULE_NAME}[/bold]."
  482. )
  483. raise click.exceptions.Exit(1)
  484. # Make sure the app name is standard for a python package name.
  485. if not re.match(r"^[a-zA-Z][a-zA-Z0-9_]*$", app_name):
  486. console.error(
  487. "The app directory name must start with a letter and can contain letters, numbers, and underscores."
  488. )
  489. raise click.exceptions.Exit(1)
  490. return app_name
  491. def rename_path_up_tree(full_path: str | Path, old_name: str, new_name: str) -> Path:
  492. """Rename all instances of `old_name` in the path (file and directories) to `new_name`.
  493. The renaming stops when we reach the directory containing `rxconfig.py`.
  494. Args:
  495. full_path: The full path to start renaming from.
  496. old_name: The name to be replaced.
  497. new_name: The replacement name.
  498. Returns:
  499. The updated path after renaming.
  500. """
  501. current_path = Path(full_path)
  502. new_path = None
  503. while True:
  504. directory, base = current_path.parent, current_path.name
  505. # Stop renaming when we reach the root dir (which contains rxconfig.py)
  506. if current_path.is_dir() and (current_path / "rxconfig.py").exists():
  507. new_path = current_path
  508. break
  509. if old_name == base.removesuffix(constants.Ext.PY):
  510. new_base = base.replace(old_name, new_name)
  511. new_path = directory / new_base
  512. current_path.rename(new_path)
  513. console.debug(f"Renamed {current_path} -> {new_path}")
  514. current_path = new_path
  515. else:
  516. new_path = current_path
  517. # Move up the directory tree
  518. current_path = directory
  519. return new_path
  520. def rename_app(new_app_name: str, loglevel: constants.LogLevel):
  521. """Rename the app directory.
  522. Args:
  523. new_app_name: The new name for the app.
  524. loglevel: The log level to use.
  525. Raises:
  526. Exit: If the command is not ran in the root dir or the app module cannot be imported.
  527. """
  528. # Set the log level.
  529. console.set_log_level(loglevel)
  530. if not constants.Config.FILE.exists():
  531. console.error(
  532. "No rxconfig.py found. Make sure you are in the root directory of your app."
  533. )
  534. raise click.exceptions.Exit(1)
  535. sys.path.insert(0, str(Path.cwd()))
  536. config = get_config()
  537. module_path = importlib.util.find_spec(config.module)
  538. if module_path is None:
  539. console.error(f"Could not find module {config.module}.")
  540. raise click.exceptions.Exit(1)
  541. if not module_path.origin:
  542. console.error(f"Could not find origin for module {config.module}.")
  543. raise click.exceptions.Exit(1)
  544. console.info(f"Renaming app directory to {new_app_name}.")
  545. process_directory(
  546. Path.cwd(),
  547. config.app_name,
  548. new_app_name,
  549. exclude_dirs=[constants.Dirs.WEB, constants.Dirs.APP_ASSETS],
  550. )
  551. rename_path_up_tree(Path(module_path.origin), config.app_name, new_app_name)
  552. console.success(f"App directory renamed to [bold]{new_app_name}[/bold].")
  553. def rename_imports_and_app_name(file_path: str | Path, old_name: str, new_name: str):
  554. """Rename imports the file using string replacement as well as app_name in rxconfig.py.
  555. Args:
  556. file_path: The file to process.
  557. old_name: The old name to replace.
  558. new_name: The new name to use.
  559. """
  560. file_path = Path(file_path)
  561. content = file_path.read_text()
  562. # Replace `from old_name.` or `from old_name` with `from new_name`
  563. content = re.sub(
  564. rf"\bfrom {re.escape(old_name)}(\b|\.|\s)",
  565. lambda match: f"from {new_name}{match.group(1)}",
  566. content,
  567. )
  568. # Replace `import old_name` with `import new_name`
  569. content = re.sub(
  570. rf"\bimport {re.escape(old_name)}\b",
  571. f"import {new_name}",
  572. content,
  573. )
  574. # Replace `app_name="old_name"` in rx.Config
  575. content = re.sub(
  576. rf'\bapp_name\s*=\s*["\']{re.escape(old_name)}["\']',
  577. f'app_name="{new_name}"',
  578. content,
  579. )
  580. # Replace positional argument `"old_name"` in rx.Config
  581. content = re.sub(
  582. rf'\brx\.Config\(\s*["\']{re.escape(old_name)}["\']',
  583. f'rx.Config("{new_name}"',
  584. content,
  585. )
  586. file_path.write_text(content)
  587. def process_directory(
  588. directory: str | Path,
  589. old_name: str,
  590. new_name: str,
  591. exclude_dirs: list | None = None,
  592. extensions: list | None = None,
  593. ):
  594. """Process files with specified extensions in a directory, excluding specified directories.
  595. Args:
  596. directory: The root directory to process.
  597. old_name: The old name to replace.
  598. new_name: The new name to use.
  599. exclude_dirs: List of directory names to exclude. Defaults to None.
  600. extensions: List of file extensions to process.
  601. """
  602. exclude_dirs = exclude_dirs or []
  603. extensions = extensions or [
  604. constants.Ext.PY,
  605. constants.Ext.MD,
  606. ] # include .md files, typically used in reflex-web.
  607. extensions_set = {ext.lstrip(".") for ext in extensions}
  608. directory = Path(directory)
  609. root_exclude_dirs = {directory / exclude_dir for exclude_dir in exclude_dirs}
  610. files = (
  611. p.resolve()
  612. for p in directory.glob("**/*")
  613. if p.is_file() and p.suffix.lstrip(".") in extensions_set
  614. )
  615. for file_path in files:
  616. if not any(
  617. file_path.is_relative_to(exclude_dir) for exclude_dir in root_exclude_dirs
  618. ):
  619. rename_imports_and_app_name(file_path, old_name, new_name)
  620. def create_config(app_name: str):
  621. """Create a new rxconfig file.
  622. Args:
  623. app_name: The name of the app.
  624. """
  625. # Import here to avoid circular imports.
  626. from reflex.compiler import templates
  627. config_name = f"{re.sub(r'[^a-zA-Z]', '', app_name).capitalize()}Config"
  628. console.debug(f"Creating {constants.Config.FILE}")
  629. constants.Config.FILE.write_text(
  630. templates.RXCONFIG.render(app_name=app_name, config_name=config_name)
  631. )
  632. def initialize_gitignore(
  633. gitignore_file: Path = constants.GitIgnore.FILE,
  634. files_to_ignore: set[str] | list[str] = constants.GitIgnore.DEFAULTS,
  635. ):
  636. """Initialize the template .gitignore file.
  637. Args:
  638. gitignore_file: The .gitignore file to create.
  639. files_to_ignore: The files to add to the .gitignore file.
  640. """
  641. # Combine with the current ignored files.
  642. current_ignore: list[str] = []
  643. if gitignore_file.exists():
  644. current_ignore = [ln.strip() for ln in gitignore_file.read_text().splitlines()]
  645. if files_to_ignore == current_ignore:
  646. console.debug(f"{gitignore_file} already up to date.")
  647. return
  648. files_to_ignore = [ln for ln in files_to_ignore if ln not in current_ignore]
  649. files_to_ignore += current_ignore
  650. # Write files to the .gitignore file.
  651. gitignore_file.touch(exist_ok=True)
  652. console.debug(f"Creating {gitignore_file}")
  653. gitignore_file.write_text("\n".join(files_to_ignore) + "\n")
  654. def initialize_requirements_txt() -> bool:
  655. """Initialize the requirements.txt file.
  656. If absent and no pyproject.toml file exists, generate one for the user.
  657. If the requirements.txt does not have reflex as dependency,
  658. generate a requirement pinning current version and append to
  659. the requirements.txt file.
  660. Returns:
  661. True if the user has to update the requirements.txt file.
  662. Raises:
  663. Exit: If the requirements.txt file cannot be read or written to.
  664. """
  665. requirements_file_path = Path(constants.RequirementsTxt.FILE)
  666. if (
  667. not requirements_file_path.exists()
  668. and Path(constants.PyprojectToml.FILE).exists()
  669. ):
  670. return True
  671. requirements_file_path.touch(exist_ok=True)
  672. for encoding in [None, "utf-8"]:
  673. try:
  674. content = requirements_file_path.read_text(encoding)
  675. break
  676. except UnicodeDecodeError:
  677. continue
  678. except Exception as e:
  679. console.error(f"Failed to read {requirements_file_path}.")
  680. raise click.exceptions.Exit(1) from e
  681. else:
  682. return True
  683. for line in content.splitlines():
  684. if re.match(r"^reflex[^a-zA-Z0-9]", line):
  685. console.debug(f"{requirements_file_path} already has reflex as dependency.")
  686. return False
  687. console.debug(
  688. f"Appending {constants.RequirementsTxt.DEFAULTS_STUB} to {requirements_file_path}"
  689. )
  690. with requirements_file_path.open("a", encoding=encoding) as f:
  691. f.write(
  692. "\n" + constants.RequirementsTxt.DEFAULTS_STUB + constants.Reflex.VERSION
  693. )
  694. return False
  695. def initialize_app_directory(
  696. app_name: str,
  697. template_name: str = constants.Templates.DEFAULT,
  698. template_code_dir_name: str | None = None,
  699. template_dir: Path | None = None,
  700. ):
  701. """Initialize the app directory on reflex init.
  702. Args:
  703. app_name: The name of the app.
  704. template_name: The name of the template to use.
  705. template_code_dir_name: The name of the code directory in the template.
  706. template_dir: The directory of the template source files.
  707. Raises:
  708. Exit: If template_name, template_code_dir_name, template_dir combination is not supported.
  709. """
  710. console.log("Initializing the app directory.")
  711. # By default, use the blank template from local assets.
  712. if template_name == constants.Templates.DEFAULT:
  713. if template_code_dir_name is not None or template_dir is not None:
  714. console.error(
  715. f"Only {template_name=} should be provided, got {template_code_dir_name=}, {template_dir=}."
  716. )
  717. raise click.exceptions.Exit(1)
  718. template_code_dir_name = constants.Templates.Dirs.CODE
  719. template_dir = Path(constants.Templates.Dirs.BASE, "apps", template_name)
  720. else:
  721. if template_code_dir_name is None or template_dir is None:
  722. console.error(
  723. f"For `{template_name}` template, `template_code_dir_name` and `template_dir` should both be provided."
  724. )
  725. raise click.exceptions.Exit(1)
  726. console.debug(f"Using {template_name=} {template_dir=} {template_code_dir_name=}.")
  727. # Remove __pycache__ dirs in template directory and current directory.
  728. for pycache_dir in [
  729. *template_dir.glob("**/__pycache__"),
  730. *Path.cwd().glob("**/__pycache__"),
  731. ]:
  732. shutil.rmtree(pycache_dir, ignore_errors=True)
  733. for file in template_dir.iterdir():
  734. # Copy the file to current directory but keep the name the same.
  735. path_ops.cp(str(file), file.name)
  736. # Rename the template app to the app name.
  737. path_ops.mv(template_code_dir_name, app_name)
  738. path_ops.mv(
  739. Path(app_name) / (template_name + constants.Ext.PY),
  740. Path(app_name) / (app_name + constants.Ext.PY),
  741. )
  742. # Fix up the imports.
  743. path_ops.find_replace(
  744. app_name,
  745. f"from {template_name}",
  746. f"from {app_name}",
  747. )
  748. def get_project_hash(raise_on_fail: bool = False) -> int | None:
  749. """Get the project hash from the reflex.json file if the file exists.
  750. Args:
  751. raise_on_fail: Whether to raise an error if the file does not exist.
  752. Returns:
  753. project_hash: The app hash.
  754. """
  755. json_file = get_web_dir() / constants.Reflex.JSON
  756. if not json_file.exists() and not raise_on_fail:
  757. return None
  758. data = json.loads(json_file.read_text())
  759. return data.get("project_hash")
  760. def initialize_web_directory():
  761. """Initialize the web directory on reflex init."""
  762. console.log("Initializing the web directory.")
  763. # Reuse the hash if one is already created, so we don't over-write it when running reflex init
  764. project_hash = get_project_hash()
  765. console.debug(f"Copying {constants.Templates.Dirs.WEB_TEMPLATE} to {get_web_dir()}")
  766. path_ops.cp(constants.Templates.Dirs.WEB_TEMPLATE, str(get_web_dir()))
  767. console.debug("Initializing the web directory.")
  768. initialize_package_json()
  769. console.debug("Initializing the bun config file.")
  770. initialize_bun_config()
  771. console.debug("Initializing the .npmrc file.")
  772. initialize_npmrc()
  773. console.debug("Initializing the public directory.")
  774. path_ops.mkdir(get_web_dir() / constants.Dirs.PUBLIC)
  775. console.debug("Initializing the react-router.config.js file.")
  776. update_react_router_config()
  777. console.debug("Initializing the reflex.json file.")
  778. # Initialize the reflex json file.
  779. init_reflex_json(project_hash=project_hash)
  780. def _compile_package_json():
  781. return templates.PACKAGE_JSON.render(
  782. scripts={
  783. "dev": constants.PackageJson.Commands.DEV,
  784. "export": constants.PackageJson.Commands.EXPORT,
  785. "export_sitemap": constants.PackageJson.Commands.EXPORT_SITEMAP,
  786. "prod": constants.PackageJson.Commands.PROD,
  787. },
  788. dependencies=constants.PackageJson.DEPENDENCIES,
  789. dev_dependencies=constants.PackageJson.DEV_DEPENDENCIES,
  790. overrides=constants.PackageJson.OVERRIDES,
  791. )
  792. def initialize_package_json():
  793. """Render and write in .web the package.json file."""
  794. output_path = get_web_dir() / constants.PackageJson.PATH
  795. output_path.write_text(_compile_package_json())
  796. def initialize_bun_config():
  797. """Initialize the bun config file."""
  798. bun_config_path = get_web_dir() / constants.Bun.CONFIG_PATH
  799. if (custom_bunfig := Path(constants.Bun.CONFIG_PATH)).exists():
  800. bunfig_content = custom_bunfig.read_text()
  801. console.info(f"Copying custom bunfig.toml inside {get_web_dir()} folder")
  802. else:
  803. best_registry = get_npm_registry()
  804. bunfig_content = constants.Bun.DEFAULT_CONFIG.format(registry=best_registry)
  805. bun_config_path.write_text(bunfig_content)
  806. def initialize_npmrc():
  807. """Initialize the .npmrc file."""
  808. npmrc_path = get_web_dir() / constants.Node.CONFIG_PATH
  809. if (custom_npmrc := Path(constants.Node.CONFIG_PATH)).exists():
  810. npmrc_content = custom_npmrc.read_text()
  811. console.info(f"Copying custom .npmrc inside {get_web_dir()} folder")
  812. else:
  813. best_registry = get_npm_registry()
  814. npmrc_content = constants.Node.DEFAULT_CONFIG.format(registry=best_registry)
  815. npmrc_path.write_text(npmrc_content)
  816. def init_reflex_json(project_hash: int | None):
  817. """Write the hash of the Reflex project to a REFLEX_JSON.
  818. Reuse the hash if one is already created, therefore do not
  819. overwrite it every time we run the reflex init command
  820. .
  821. Args:
  822. project_hash: The app hash.
  823. """
  824. if project_hash is not None:
  825. console.debug(f"Project hash is already set to {project_hash}.")
  826. else:
  827. # Get a random project hash.
  828. project_hash = random.getrandbits(128)
  829. console.debug(f"Setting project hash to {project_hash}.")
  830. # Write the hash and version to the reflex json file.
  831. reflex_json = {
  832. "version": constants.Reflex.VERSION,
  833. "project_hash": project_hash,
  834. }
  835. path_ops.update_json_file(get_web_dir() / constants.Reflex.JSON, reflex_json)
  836. def update_react_router_config(export: bool = False):
  837. """Update react-router.config.js config from Reflex config.
  838. Args:
  839. export: if the method run during reflex export.
  840. """
  841. react_router_config_file_path = get_web_dir() / constants.ReactRouter.CONFIG_FILE
  842. react_router_config = _update_react_router_config(get_config(), export=export)
  843. # Overwriting the config file triggers a full server reload, so make sure
  844. # there is actually a diff.
  845. orig_next_config = (
  846. react_router_config_file_path.read_text()
  847. if react_router_config_file_path.exists()
  848. else ""
  849. )
  850. if orig_next_config != react_router_config:
  851. react_router_config_file_path.write_text(react_router_config)
  852. def _update_react_router_config(config: Config, export: bool = False):
  853. react_router_config = {
  854. "basename": "/" + (config.frontend_path or "").removeprefix("/"),
  855. "future": {
  856. "unstable_optimizeDeps": True,
  857. },
  858. "ssr": False,
  859. }
  860. if export:
  861. react_router_config["prerender"] = True
  862. react_router_config["build"] = constants.Dirs.BUILD_DIR
  863. return f"export default {json.dumps(react_router_config)};"
  864. def remove_existing_bun_installation():
  865. """Remove existing bun installation."""
  866. console.debug("Removing existing bun installation.")
  867. if Path(get_config().bun_path).exists():
  868. path_ops.rm(constants.Bun.ROOT_PATH)
  869. def download_and_run(url: str, *args, show_status: bool = False, **env):
  870. """Download and run a script.
  871. Args:
  872. url: The url of the script.
  873. args: The arguments to pass to the script.
  874. show_status: Whether to show the status of the script.
  875. env: The environment variables to use.
  876. Raises:
  877. Exit: If the script fails to download.
  878. """
  879. # Download the script
  880. console.debug(f"Downloading {url}")
  881. try:
  882. response = net.get(url)
  883. response.raise_for_status()
  884. except httpx.HTTPError as e:
  885. console.error(
  886. f"Failed to download bun install script. You can install or update bun manually from https://bun.sh \n{e}"
  887. )
  888. raise click.exceptions.Exit(1) from None
  889. # Save the script to a temporary file.
  890. script = Path(tempfile.NamedTemporaryFile().name)
  891. script.write_text(response.text)
  892. # Run the script.
  893. env = {**os.environ, **env}
  894. process = processes.new_process(["bash", str(script), *args], env=env)
  895. show = processes.show_status if show_status else processes.show_logs
  896. show(f"Installing {url}", process)
  897. def install_bun():
  898. """Install bun onto the user's system.
  899. Raises:
  900. SystemPackageMissingError: If "unzip" is missing.
  901. """
  902. one_drive_in_path = windows_check_onedrive_in_path()
  903. if constants.IS_WINDOWS and one_drive_in_path:
  904. console.warn(
  905. "Creating project directories in OneDrive is not recommended for bun usage on windows. This will fallback to npm."
  906. )
  907. bun_path = path_ops.get_bun_path()
  908. # Skip if bun is already installed.
  909. if (
  910. bun_path
  911. and (current_version := get_bun_version(bun_path=bun_path))
  912. and current_version >= version.parse(constants.Bun.MIN_VERSION)
  913. ):
  914. console.debug("Skipping bun installation as it is already installed.")
  915. return
  916. if bun_path and path_ops.use_system_bun():
  917. validate_bun(bun_path=bun_path)
  918. return
  919. # if unzip is installed
  920. if constants.IS_WINDOWS:
  921. processes.new_process(
  922. [
  923. "powershell",
  924. "-c",
  925. f"irm {constants.Bun.WINDOWS_INSTALL_URL}|iex",
  926. ],
  927. env={
  928. "BUN_INSTALL": str(constants.Bun.ROOT_PATH),
  929. "BUN_VERSION": constants.Bun.VERSION,
  930. },
  931. shell=True,
  932. run=True,
  933. show_logs=console.is_debug(),
  934. )
  935. else:
  936. if path_ops.which("unzip") is None:
  937. raise SystemPackageMissingError("unzip")
  938. # Run the bun install script.
  939. download_and_run(
  940. constants.Bun.INSTALL_URL,
  941. f"bun-v{constants.Bun.VERSION}",
  942. BUN_INSTALL=str(constants.Bun.ROOT_PATH),
  943. BUN_VERSION=str(constants.Bun.VERSION),
  944. )
  945. def _write_cached_procedure_file(payload: str, cache_file: str | Path):
  946. cache_file = Path(cache_file)
  947. cache_file.write_text(payload)
  948. def _read_cached_procedure_file(cache_file: str | Path) -> str | None:
  949. cache_file = Path(cache_file)
  950. if cache_file.exists():
  951. return cache_file.read_text()
  952. return None
  953. def _clear_cached_procedure_file(cache_file: str | Path):
  954. cache_file = Path(cache_file)
  955. if cache_file.exists():
  956. cache_file.unlink()
  957. def cached_procedure(
  958. cache_file: str | None,
  959. payload_fn: Callable[..., str],
  960. cache_file_fn: Callable[[], str] | None = None,
  961. ):
  962. """Decorator to cache the runs of a procedure on disk. Procedures should not have
  963. a return value.
  964. Args:
  965. cache_file: The file to store the cache payload in.
  966. payload_fn: Function that computes cache payload from function args.
  967. cache_file_fn: Function that computes the cache file name at runtime.
  968. Returns:
  969. The decorated function.
  970. Raises:
  971. ValueError: If both cache_file and cache_file_fn are provided.
  972. """
  973. if cache_file and cache_file_fn is not None:
  974. raise ValueError("cache_file and cache_file_fn cannot both be provided.")
  975. def _inner_decorator(func: Callable):
  976. def _inner(*args, **kwargs):
  977. _cache_file = cache_file_fn() if cache_file_fn is not None else cache_file
  978. if not _cache_file:
  979. raise ValueError("Unknown cache file, cannot cache result.")
  980. payload = _read_cached_procedure_file(_cache_file)
  981. new_payload = payload_fn(*args, **kwargs)
  982. if payload != new_payload:
  983. _clear_cached_procedure_file(_cache_file)
  984. func(*args, **kwargs)
  985. _write_cached_procedure_file(new_payload, _cache_file)
  986. return _inner
  987. return _inner_decorator
  988. @cached_procedure(
  989. cache_file_fn=lambda: str(
  990. get_web_dir() / "reflex.install_frontend_packages.cached"
  991. ),
  992. payload_fn=lambda p, c: f"{sorted(p)!r},{c.json()}",
  993. cache_file=None,
  994. )
  995. def install_frontend_packages(packages: set[str], config: Config):
  996. """Installs the base and custom frontend packages.
  997. Args:
  998. packages: A list of package names to be installed.
  999. config: The config object.
  1000. Example:
  1001. >>> install_frontend_packages(["react", "react-dom"], get_config())
  1002. """
  1003. install_package_managers = get_nodejs_compatible_package_managers(
  1004. raise_on_none=True
  1005. )
  1006. env = (
  1007. {
  1008. "NODE_TLS_REJECT_UNAUTHORIZED": "0",
  1009. }
  1010. if environment.SSL_NO_VERIFY.get()
  1011. else {}
  1012. )
  1013. primary_package_manager = install_package_managers[0]
  1014. fallbacks = install_package_managers[1:]
  1015. processes.run_process_with_fallbacks(
  1016. [primary_package_manager, "install", "--legacy-peer-deps"],
  1017. fallbacks=fallbacks,
  1018. analytics_enabled=True,
  1019. show_status_message="Installing base frontend packages",
  1020. cwd=get_web_dir(),
  1021. shell=constants.IS_WINDOWS,
  1022. env=env,
  1023. )
  1024. if config.tailwind is not None:
  1025. processes.run_process_with_fallbacks(
  1026. [
  1027. primary_package_manager,
  1028. "add",
  1029. "--legacy-peer-deps",
  1030. "-d",
  1031. constants.Tailwind.VERSION,
  1032. *[
  1033. plugin if isinstance(plugin, str) else plugin.get("name")
  1034. for plugin in (config.tailwind or {}).get("plugins", [])
  1035. ],
  1036. ],
  1037. fallbacks=fallbacks,
  1038. analytics_enabled=True,
  1039. show_status_message="Installing tailwind",
  1040. cwd=get_web_dir(),
  1041. shell=constants.IS_WINDOWS,
  1042. env=env,
  1043. )
  1044. # Install custom packages defined in frontend_packages
  1045. if len(packages) > 0:
  1046. processes.run_process_with_fallbacks(
  1047. [primary_package_manager, "add", "--legacy-peer-deps", *packages],
  1048. fallbacks=fallbacks,
  1049. analytics_enabled=True,
  1050. show_status_message="Installing frontend packages from config and components",
  1051. cwd=get_web_dir(),
  1052. shell=constants.IS_WINDOWS,
  1053. env=env,
  1054. )
  1055. def check_running_mode(frontend: bool, backend: bool) -> tuple[bool, bool]:
  1056. """Check if the app is running in frontend or backend mode.
  1057. Args:
  1058. frontend: Whether to run the frontend of the app.
  1059. backend: Whether to run the backend of the app.
  1060. Returns:
  1061. The running modes.
  1062. """
  1063. if not frontend and not backend:
  1064. return True, True
  1065. return frontend, backend
  1066. def assert_in_reflex_dir():
  1067. """Assert that the current working directory is the reflex directory.
  1068. Raises:
  1069. Exit: If the current working directory is not the reflex directory.
  1070. """
  1071. if not constants.Config.FILE.exists():
  1072. console.error(
  1073. f"[cyan]{constants.Config.FILE}[/cyan] not found. Move to the root folder of your project, or run [bold]{constants.Reflex.MODULE_NAME} init[/bold] to start a new project."
  1074. )
  1075. raise click.exceptions.Exit(1)
  1076. def needs_reinit() -> bool:
  1077. """Check if an app needs to be reinitialized.
  1078. Returns:
  1079. Whether the app needs to be reinitialized.
  1080. """
  1081. # Make sure the .reflex directory exists.
  1082. if not environment.REFLEX_DIR.get().exists():
  1083. return True
  1084. # Make sure the .web directory exists in frontend mode.
  1085. if not get_web_dir().exists():
  1086. return True
  1087. # If the template is out of date, then we need to re-init
  1088. if not is_latest_template():
  1089. return True
  1090. if constants.IS_WINDOWS:
  1091. console.warn(
  1092. """Windows Subsystem for Linux (WSL) is recommended for improving initial install times."""
  1093. )
  1094. if windows_check_onedrive_in_path():
  1095. console.warn(
  1096. "Creating project directories in OneDrive may lead to performance issues. For optimal performance, It is recommended to avoid using OneDrive for your reflex app."
  1097. )
  1098. # No need to reinitialize if the app is already initialized.
  1099. return False
  1100. def is_latest_template() -> bool:
  1101. """Whether the app is using the latest template.
  1102. Returns:
  1103. Whether the app is using the latest template.
  1104. """
  1105. json_file = get_web_dir() / constants.Reflex.JSON
  1106. if not json_file.exists():
  1107. return False
  1108. app_version = json.loads(json_file.read_text()).get("version")
  1109. return app_version == constants.Reflex.VERSION
  1110. def validate_bun(bun_path: Path | None = None):
  1111. """Validate bun if a custom bun path is specified to ensure the bun version meets requirements.
  1112. Args:
  1113. bun_path: The path to the bun executable. If None, the default bun path is used.
  1114. Raises:
  1115. Exit: If custom specified bun does not exist or does not meet requirements.
  1116. """
  1117. bun_path = bun_path or path_ops.get_bun_path()
  1118. if bun_path is None:
  1119. return
  1120. if not path_ops.samefile(bun_path, constants.Bun.DEFAULT_PATH):
  1121. console.info(f"Using custom Bun path: {bun_path}")
  1122. bun_version = get_bun_version()
  1123. if bun_version is None:
  1124. console.error(
  1125. "Failed to obtain bun version. Make sure the specified bun path in your config is correct."
  1126. )
  1127. raise click.exceptions.Exit(1)
  1128. elif bun_version < version.parse(constants.Bun.MIN_VERSION):
  1129. console.warn(
  1130. f"Reflex requires bun version {constants.Bun.MIN_VERSION} or higher to run, but the detected version is "
  1131. f"{bun_version}. If you have specified a custom bun path in your config, make sure to provide one "
  1132. f"that satisfies the minimum version requirement. You can upgrade bun by running [bold]bun upgrade[/bold]."
  1133. )
  1134. def validate_frontend_dependencies(init: bool = True):
  1135. """Validate frontend dependencies to ensure they meet requirements.
  1136. Args:
  1137. init: whether running `reflex init`
  1138. Raises:
  1139. Exit: If the package manager is invalid.
  1140. """
  1141. if not init:
  1142. try:
  1143. get_js_package_executor(raise_on_none=True)
  1144. except FileNotFoundError as e:
  1145. raise click.exceptions.Exit(1) from e
  1146. if prefer_npm_over_bun() and not check_node_version():
  1147. node_version = get_node_version()
  1148. console.error(
  1149. f"Reflex requires node version {constants.Node.MIN_VERSION} or higher to run, but the detected version is {node_version}",
  1150. )
  1151. raise click.exceptions.Exit(1)
  1152. def ensure_reflex_installation_id() -> int | None:
  1153. """Ensures that a reflex distinct id has been generated and stored in the reflex directory.
  1154. Returns:
  1155. Distinct id.
  1156. """
  1157. try:
  1158. console.debug("Ensuring reflex installation id.")
  1159. initialize_reflex_user_directory()
  1160. installation_id_file = environment.REFLEX_DIR.get() / "installation_id"
  1161. installation_id = None
  1162. if installation_id_file.exists():
  1163. with contextlib.suppress(Exception):
  1164. installation_id = int(installation_id_file.read_text())
  1165. # If anything goes wrong at all... just regenerate.
  1166. # Like what? Examples:
  1167. # - file not exists
  1168. # - file not readable
  1169. # - content not parseable as an int
  1170. if installation_id is None:
  1171. installation_id = random.getrandbits(128)
  1172. installation_id_file.write_text(str(installation_id))
  1173. except Exception as e:
  1174. console.debug(f"Failed to ensure reflex installation id: {e}")
  1175. return None
  1176. else:
  1177. # If we get here, installation_id is definitely set
  1178. return installation_id
  1179. def initialize_reflex_user_directory():
  1180. """Initialize the reflex user directory."""
  1181. console.debug(f"Creating {environment.REFLEX_DIR.get()}")
  1182. # Create the reflex directory.
  1183. path_ops.mkdir(environment.REFLEX_DIR.get())
  1184. def initialize_frontend_dependencies():
  1185. """Initialize all the frontend dependencies."""
  1186. # validate dependencies before install
  1187. console.debug("Validating frontend dependencies.")
  1188. validate_frontend_dependencies()
  1189. # Install the frontend dependencies.
  1190. console.debug("Installing or validating bun.")
  1191. install_bun()
  1192. # Set up the web directory.
  1193. initialize_web_directory()
  1194. def check_db_used() -> bool:
  1195. """Check if the database is used.
  1196. Returns:
  1197. True if the database is used.
  1198. """
  1199. return bool(get_config().db_url)
  1200. def check_redis_used() -> bool:
  1201. """Check if Redis is used.
  1202. Returns:
  1203. True if Redis is used.
  1204. """
  1205. return bool(get_config().redis_url)
  1206. def check_db_initialized() -> bool:
  1207. """Check if the database migrations are initialized.
  1208. Returns:
  1209. True if alembic is initialized (or if database is not used).
  1210. """
  1211. if (
  1212. get_config().db_url is not None
  1213. and not environment.ALEMBIC_CONFIG.get().exists()
  1214. ):
  1215. console.error(
  1216. "Database is not initialized. Run [bold]reflex db init[/bold] first."
  1217. )
  1218. return False
  1219. return True
  1220. def check_schema_up_to_date():
  1221. """Check if the sqlmodel metadata matches the current database schema."""
  1222. if get_config().db_url is None or not environment.ALEMBIC_CONFIG.get().exists():
  1223. return
  1224. with model.Model.get_db_engine().connect() as connection:
  1225. try:
  1226. if model.Model.alembic_autogenerate(
  1227. connection=connection,
  1228. write_migration_scripts=False,
  1229. ):
  1230. console.error(
  1231. "Detected database schema changes. Run [bold]reflex db makemigrations[/bold] "
  1232. "to generate migration scripts.",
  1233. )
  1234. except CommandError as command_error:
  1235. if "Target database is not up to date." in str(command_error):
  1236. console.error(
  1237. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  1238. )
  1239. def prompt_for_template_options(templates: list[Template]) -> str:
  1240. """Prompt the user to specify a template.
  1241. Args:
  1242. templates: The templates to choose from.
  1243. Returns:
  1244. The template name the user selects.
  1245. Raises:
  1246. Exit: If the user does not select a template.
  1247. """
  1248. # Show the user the URLs of each template to preview.
  1249. console.print("\nGet started with a template:")
  1250. # Prompt the user to select a template.
  1251. for index, template in enumerate(templates):
  1252. console.print(f"({index}) {template.description}")
  1253. template = console.ask(
  1254. "Which template would you like to use?",
  1255. choices=[str(i) for i in range(len(templates))],
  1256. show_choices=False,
  1257. default="0",
  1258. )
  1259. if not template:
  1260. console.error("No template selected.")
  1261. raise click.exceptions.Exit(1)
  1262. try:
  1263. template_index = int(template)
  1264. except ValueError:
  1265. console.error("Invalid template selected.")
  1266. raise click.exceptions.Exit(1) from None
  1267. if template_index < 0 or template_index >= len(templates):
  1268. console.error("Invalid template selected.")
  1269. raise click.exceptions.Exit(1)
  1270. # Return the template.
  1271. return templates[template_index].name
  1272. def fetch_app_templates(version: str) -> dict[str, Template]:
  1273. """Fetch a dict of templates from the templates repo using github API.
  1274. Args:
  1275. version: The version of the templates to fetch.
  1276. Returns:
  1277. The dict of templates.
  1278. """
  1279. def get_release_by_tag(tag: str) -> dict | None:
  1280. response = net.get(constants.Reflex.RELEASES_URL)
  1281. response.raise_for_status()
  1282. releases = response.json()
  1283. for release in releases:
  1284. if release["tag_name"] == f"v{tag}":
  1285. return release
  1286. return None
  1287. release = get_release_by_tag(version)
  1288. if release is None:
  1289. console.warn(f"No templates known for version {version}")
  1290. return {}
  1291. assets = release.get("assets", [])
  1292. asset = next((a for a in assets if a["name"] == "templates.json"), None)
  1293. if asset is None:
  1294. console.warn(f"Templates metadata not found for version {version}")
  1295. return {}
  1296. else:
  1297. templates_url = asset["browser_download_url"]
  1298. templates_data = net.get(templates_url, follow_redirects=True).json()["templates"]
  1299. for template in templates_data:
  1300. if template["name"] == "blank":
  1301. template["code_url"] = ""
  1302. continue
  1303. template["code_url"] = next(
  1304. (
  1305. a["browser_download_url"]
  1306. for a in assets
  1307. if a["name"] == f"{template['name']}.zip"
  1308. ),
  1309. None,
  1310. )
  1311. filtered_templates = {}
  1312. for tp in templates_data:
  1313. if tp["hidden"] or tp["code_url"] is None:
  1314. continue
  1315. known_fields = {f.name for f in dataclasses.fields(Template)}
  1316. filtered_templates[tp["name"]] = Template(
  1317. **{k: v for k, v in tp.items() if k in known_fields}
  1318. )
  1319. return filtered_templates
  1320. def create_config_init_app_from_remote_template(app_name: str, template_url: str):
  1321. """Create new rxconfig and initialize app using a remote template.
  1322. Args:
  1323. app_name: The name of the app.
  1324. template_url: The path to the template source code as a zip file.
  1325. Raises:
  1326. Exit: If any download, file operations fail or unexpected zip file format.
  1327. """
  1328. # Create a temp directory for the zip download.
  1329. try:
  1330. temp_dir = tempfile.mkdtemp()
  1331. except OSError as ose:
  1332. console.error(f"Failed to create temp directory for download: {ose}")
  1333. raise click.exceptions.Exit(1) from ose
  1334. # Use httpx GET with redirects to download the zip file.
  1335. zip_file_path: Path = Path(temp_dir) / "template.zip"
  1336. try:
  1337. # Note: following redirects can be risky. We only allow this for reflex built templates at the moment.
  1338. response = net.get(template_url, follow_redirects=True)
  1339. console.debug(f"Server responded download request: {response}")
  1340. response.raise_for_status()
  1341. except httpx.HTTPError as he:
  1342. console.error(f"Failed to download the template: {he}")
  1343. raise click.exceptions.Exit(1) from he
  1344. try:
  1345. zip_file_path.write_bytes(response.content)
  1346. console.debug(f"Downloaded the zip to {zip_file_path}")
  1347. except OSError as ose:
  1348. console.error(f"Unable to write the downloaded zip to disk {ose}")
  1349. raise click.exceptions.Exit(1) from ose
  1350. # Create a temp directory for the zip extraction.
  1351. try:
  1352. unzip_dir = Path(tempfile.mkdtemp())
  1353. except OSError as ose:
  1354. console.error(f"Failed to create temp directory for extracting zip: {ose}")
  1355. raise click.exceptions.Exit(1) from ose
  1356. try:
  1357. zipfile.ZipFile(zip_file_path).extractall(path=unzip_dir)
  1358. # The zip file downloaded from github looks like:
  1359. # repo-name-branch/**/*, so we need to remove the top level directory.
  1360. except Exception as uze:
  1361. console.error(f"Failed to unzip the template: {uze}")
  1362. raise click.exceptions.Exit(1) from uze
  1363. if len(subdirs := list(unzip_dir.iterdir())) != 1:
  1364. console.error(f"Expected one directory in the zip, found {subdirs}")
  1365. raise click.exceptions.Exit(1)
  1366. template_dir = unzip_dir / subdirs[0]
  1367. console.debug(f"Template folder is located at {template_dir}")
  1368. # Move the rxconfig file here first.
  1369. path_ops.mv(str(template_dir / constants.Config.FILE), constants.Config.FILE)
  1370. new_config = get_config(reload=True)
  1371. # Get the template app's name from rxconfig in case it is different than
  1372. # the source code repo name on github.
  1373. template_name = new_config.app_name
  1374. create_config(app_name)
  1375. initialize_app_directory(
  1376. app_name,
  1377. template_name=template_name,
  1378. template_code_dir_name=template_name,
  1379. template_dir=template_dir,
  1380. )
  1381. req_file = Path("requirements.txt")
  1382. if req_file.exists() and len(req_file.read_text().splitlines()) > 1:
  1383. console.info(
  1384. "Run `pip install -r requirements.txt` to install the required python packages for this template."
  1385. )
  1386. # Clean up the temp directories.
  1387. shutil.rmtree(temp_dir)
  1388. shutil.rmtree(unzip_dir)
  1389. def initialize_default_app(app_name: str):
  1390. """Initialize the default app.
  1391. Args:
  1392. app_name: The name of the app.
  1393. """
  1394. create_config(app_name)
  1395. initialize_app_directory(app_name)
  1396. def validate_and_create_app_using_remote_template(
  1397. app_name: str, template: str, templates: dict[str, Template]
  1398. ):
  1399. """Validate and create an app using a remote template.
  1400. Args:
  1401. app_name: The name of the app.
  1402. template: The name of the template.
  1403. templates: The available templates.
  1404. Raises:
  1405. Exit: If the template is not found.
  1406. """
  1407. # If user selects a template, it needs to exist.
  1408. if template in templates:
  1409. from reflex_cli.v2.utils import hosting
  1410. authenticated_token = hosting.authenticated_token()
  1411. if not authenticated_token or not authenticated_token[0]:
  1412. console.print(
  1413. f"Please use `reflex login` to access the '{template}' template."
  1414. )
  1415. raise click.exceptions.Exit(3)
  1416. template_url = templates[template].code_url
  1417. else:
  1418. template_parsed_url = urlparse(template)
  1419. # Check if the template is a github repo.
  1420. if template_parsed_url.hostname == "github.com":
  1421. path = template_parsed_url.path.strip("/").removesuffix(".git")
  1422. template_url = f"https://github.com/{path}/archive/main.zip"
  1423. else:
  1424. console.error(f"Template `{template}` not found or invalid.")
  1425. raise click.exceptions.Exit(1)
  1426. if template_url is None:
  1427. return
  1428. create_config_init_app_from_remote_template(
  1429. app_name=app_name, template_url=template_url
  1430. )
  1431. def fetch_remote_templates(
  1432. template: str,
  1433. ) -> tuple[str, dict[str, Template]]:
  1434. """Fetch the available remote templates.
  1435. Args:
  1436. template: The name of the template.
  1437. Returns:
  1438. The selected template and the available templates.
  1439. """
  1440. available_templates = {}
  1441. try:
  1442. # Get the available templates
  1443. available_templates = fetch_app_templates(constants.Reflex.VERSION)
  1444. except Exception as e:
  1445. console.warn("Failed to fetch templates. Falling back to default template.")
  1446. console.debug(f"Error while fetching templates: {e}")
  1447. template = constants.Templates.DEFAULT
  1448. return template, available_templates
  1449. def initialize_app(app_name: str, template: str | None = None) -> str | None:
  1450. """Initialize the app either from a remote template or a blank app. If the config file exists, it is considered as reinit.
  1451. Args:
  1452. app_name: The name of the app.
  1453. template: The name of the template to use.
  1454. Returns:
  1455. The name of the template.
  1456. Raises:
  1457. Exit: If the template is not valid or unspecified.
  1458. """
  1459. # Local imports to avoid circular imports.
  1460. from reflex.utils import telemetry
  1461. # Check if the app is already initialized.
  1462. if constants.Config.FILE.exists():
  1463. telemetry.send("reinit")
  1464. return
  1465. templates: dict[str, Template] = {}
  1466. # Don't fetch app templates if the user directly asked for DEFAULT.
  1467. if template is not None and (template not in (constants.Templates.DEFAULT,)):
  1468. template, templates = fetch_remote_templates(template)
  1469. if template is None:
  1470. template = prompt_for_template_options(get_init_cli_prompt_options())
  1471. if template == constants.Templates.CHOOSE_TEMPLATES:
  1472. redir.reflex_templates()
  1473. raise click.exceptions.Exit(0)
  1474. if template == constants.Templates.AI:
  1475. redir.reflex_build_redirect()
  1476. raise click.exceptions.Exit(0)
  1477. # If the blank template is selected, create a blank app.
  1478. if template == constants.Templates.DEFAULT:
  1479. # Default app creation behavior: a blank app.
  1480. initialize_default_app(app_name)
  1481. else:
  1482. validate_and_create_app_using_remote_template(
  1483. app_name=app_name, template=template, templates=templates
  1484. )
  1485. telemetry.send("init", template=template)
  1486. return template
  1487. def get_init_cli_prompt_options() -> list[Template]:
  1488. """Get the CLI options for initializing a Reflex app.
  1489. Returns:
  1490. The CLI options.
  1491. """
  1492. return [
  1493. Template(
  1494. name=constants.Templates.DEFAULT,
  1495. description="A blank Reflex app.",
  1496. code_url="",
  1497. ),
  1498. Template(
  1499. name=constants.Templates.AI,
  1500. description="[bold]Try our free AI builder.",
  1501. code_url="",
  1502. ),
  1503. Template(
  1504. name=constants.Templates.CHOOSE_TEMPLATES,
  1505. description="Premade templates built by the Reflex team.",
  1506. code_url="",
  1507. ),
  1508. ]
  1509. def initialize_main_module_index_from_generation(app_name: str, generation_hash: str):
  1510. """Overwrite the `index` function in the main module with reflex.build generated code.
  1511. Args:
  1512. app_name: The name of the app.
  1513. generation_hash: The generation hash from reflex.build.
  1514. Raises:
  1515. GeneratedCodeHasNoFunctionDefsError: If the fetched code has no function definitions
  1516. (the refactored reflex code is expected to have at least one root function defined).
  1517. """
  1518. # Download the reflex code for the generation.
  1519. url = constants.Templates.REFLEX_BUILD_CODE_URL.format(
  1520. generation_hash=generation_hash
  1521. )
  1522. resp = net.get(url)
  1523. while resp.status_code == httpx.codes.SERVICE_UNAVAILABLE:
  1524. console.debug("Waiting for the code to be generated...")
  1525. time.sleep(1)
  1526. resp = net.get(url)
  1527. resp.raise_for_status()
  1528. # Determine the name of the last function, which renders the generated code.
  1529. defined_funcs = re.findall(r"def ([a-zA-Z_]+)\(", resp.text)
  1530. if not defined_funcs:
  1531. raise GeneratedCodeHasNoFunctionDefsError(
  1532. f"No function definitions found in generated code from {url!r}."
  1533. )
  1534. render_func_name = defined_funcs[-1]
  1535. def replace_content(_match: re.Match) -> str:
  1536. return "\n".join(
  1537. [
  1538. resp.text,
  1539. "",
  1540. "def index() -> rx.Component:",
  1541. f" return {render_func_name}()",
  1542. "",
  1543. "",
  1544. ],
  1545. )
  1546. main_module_path = Path(app_name, app_name + constants.Ext.PY)
  1547. main_module_code = main_module_path.read_text()
  1548. main_module_code = re.sub(
  1549. r"def index\(\).*:\n([^\n]\s+.*\n+)+",
  1550. replace_content,
  1551. main_module_code,
  1552. )
  1553. # Make the app use light mode until flexgen enforces the conversion of
  1554. # tailwind colors to radix colors.
  1555. main_module_code = re.sub(
  1556. r"app\s*=\s*rx\.App\(\s*\)",
  1557. 'app = rx.App(theme=rx.theme(color_mode="light"))',
  1558. main_module_code,
  1559. )
  1560. main_module_path.write_text(main_module_code)
  1561. def format_address_width(address_width: str | None) -> int | None:
  1562. """Cast address width to an int.
  1563. Args:
  1564. address_width: The address width.
  1565. Returns:
  1566. Address width int
  1567. """
  1568. try:
  1569. return int(address_width) if address_width else None
  1570. except ValueError:
  1571. return None
  1572. def _retrieve_cpu_info() -> CpuInfo | None:
  1573. """Retrieve the CPU info of the host.
  1574. Returns:
  1575. The CPU info.
  1576. """
  1577. platform_os = platform.system()
  1578. cpuinfo = {}
  1579. try:
  1580. if platform_os == "Windows":
  1581. cmd = 'powershell -Command "Get-CimInstance Win32_Processor | Select-Object -First 1 | Select-Object AddressWidth,Manufacturer,Name | ConvertTo-Json"'
  1582. output = processes.execute_command_and_return_output(cmd)
  1583. if output:
  1584. cpu_data = json.loads(output)
  1585. cpuinfo["address_width"] = cpu_data["AddressWidth"]
  1586. cpuinfo["manufacturer_id"] = cpu_data["Manufacturer"]
  1587. cpuinfo["model_name"] = cpu_data["Name"]
  1588. elif platform_os == "Linux":
  1589. output = processes.execute_command_and_return_output("lscpu")
  1590. if output:
  1591. lines = output.split("\n")
  1592. for line in lines:
  1593. if "Architecture" in line:
  1594. cpuinfo["address_width"] = (
  1595. 64 if line.split(":")[1].strip() == "x86_64" else 32
  1596. )
  1597. if "Vendor ID:" in line:
  1598. cpuinfo["manufacturer_id"] = line.split(":")[1].strip()
  1599. if "Model name" in line:
  1600. cpuinfo["model_name"] = line.split(":")[1].strip()
  1601. elif platform_os == "Darwin":
  1602. cpuinfo["address_width"] = format_address_width(
  1603. processes.execute_command_and_return_output("getconf LONG_BIT")
  1604. )
  1605. cpuinfo["manufacturer_id"] = processes.execute_command_and_return_output(
  1606. "sysctl -n machdep.cpu.brand_string"
  1607. )
  1608. cpuinfo["model_name"] = processes.execute_command_and_return_output(
  1609. "uname -m"
  1610. )
  1611. except Exception as err:
  1612. console.error(f"Failed to retrieve CPU info. {err}")
  1613. return None
  1614. return (
  1615. CpuInfo(
  1616. manufacturer_id=cpuinfo.get("manufacturer_id"),
  1617. model_name=cpuinfo.get("model_name"),
  1618. address_width=cpuinfo.get("address_width"),
  1619. )
  1620. if cpuinfo
  1621. else None
  1622. )
  1623. @functools.cache
  1624. def get_cpu_info() -> CpuInfo | None:
  1625. """Get the CPU info of the underlining host.
  1626. Returns:
  1627. The CPU info.
  1628. """
  1629. cpu_info_file = environment.REFLEX_DIR.get() / "cpu_info.json"
  1630. if cpu_info_file.exists() and (cpu_info := json.loads(cpu_info_file.read_text())):
  1631. return CpuInfo(**cpu_info)
  1632. cpu_info = _retrieve_cpu_info()
  1633. if cpu_info:
  1634. cpu_info_file.parent.mkdir(parents=True, exist_ok=True)
  1635. cpu_info_file.write_text(json.dumps(dataclasses.asdict(cpu_info)))
  1636. return cpu_info
  1637. def is_generation_hash(template: str) -> bool:
  1638. """Check if the template looks like a generation hash.
  1639. Args:
  1640. template: The template name.
  1641. Returns:
  1642. True if the template is composed of 32 or more hex characters.
  1643. """
  1644. return re.match(r"^[0-9a-f]{32,}$", template) is not None
  1645. def get_user_tier():
  1646. """Get the current user's tier.
  1647. Returns:
  1648. The current user's tier.
  1649. """
  1650. from reflex_cli.v2.utils import hosting
  1651. authenticated_token = hosting.authenticated_token()
  1652. return (
  1653. authenticated_token[1].get("tier", "").lower()
  1654. if authenticated_token[0]
  1655. else "anonymous"
  1656. )