prerequisites.py 52 KB

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