prerequisites.py 65 KB

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