prerequisites.py 60 KB

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