prerequisites.py 52 KB

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