prerequisites.py 64 KB

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