prerequisites.py 46 KB

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