prerequisites.py 62 KB

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