prerequisites.py 52 KB

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