prerequisites.py 51 KB

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