prerequisites.py 63 KB

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