1
0

prerequisites.py 57 KB

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