prerequisites.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. """Everything related to fetching or initializing build prerequisites."""
  2. from __future__ import annotations
  3. import json
  4. import os
  5. import platform
  6. import re
  7. import subprocess
  8. import sys
  9. from datetime import datetime
  10. from pathlib import Path
  11. from types import ModuleType
  12. from typing import Optional
  13. import typer
  14. from packaging import version
  15. from redis import Redis
  16. from pynecone import constants
  17. from pynecone.config import get_config
  18. from pynecone.utils import console, path_ops
  19. def check_node_version(min_version=constants.MIN_NODE_VERSION):
  20. """Check the version of Node.js.
  21. Args:
  22. min_version: The minimum version of Node.js required.
  23. Returns:
  24. Whether the version of Node.js is high enough.
  25. """
  26. try:
  27. # Run the node -v command and capture the output
  28. result = subprocess.run(
  29. ["node", "-v"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
  30. )
  31. # The output will be in the form "vX.Y.Z", but version.parse() can handle it
  32. current_version = version.parse(result.stdout.decode())
  33. # Compare the version numbers
  34. return current_version >= version.parse(min_version)
  35. except Exception:
  36. return False
  37. def get_bun_version() -> Optional[version.Version]:
  38. """Get the version of bun.
  39. Returns:
  40. The version of bun.
  41. """
  42. try:
  43. # Run the bun -v command and capture the output
  44. result = subprocess.run(
  45. [os.path.expandvars(get_config().bun_path), "-v"],
  46. stdout=subprocess.PIPE,
  47. stderr=subprocess.PIPE,
  48. )
  49. return version.parse(result.stdout.decode().strip())
  50. except Exception:
  51. return None
  52. def get_package_manager() -> str:
  53. """Get the package manager executable.
  54. Returns:
  55. The path to the package manager.
  56. Raises:
  57. FileNotFoundError: If bun or npm is not installed.
  58. Exit: If the app directory is invalid.
  59. """
  60. config = get_config()
  61. # Check that the node version is valid.
  62. if not check_node_version():
  63. console.print(
  64. f"[red]Node.js version {constants.MIN_NODE_VERSION} or higher is required to run Pynecone."
  65. )
  66. raise typer.Exit()
  67. # On Windows, we use npm instead of bun.
  68. if platform.system() == "Windows" or config.disable_bun:
  69. npm_path = path_ops.which("npm")
  70. if npm_path is None:
  71. raise FileNotFoundError("Pynecone requires npm to be installed on Windows.")
  72. return npm_path
  73. # On other platforms, we use bun.
  74. return os.path.expandvars(get_config().bun_path)
  75. def get_app() -> ModuleType:
  76. """Get the app module based on the default config.
  77. Returns:
  78. The app based on the default config.
  79. """
  80. config = get_config()
  81. module = ".".join([config.app_name, config.app_name])
  82. sys.path.insert(0, os.getcwd())
  83. return __import__(module, fromlist=(constants.APP_VAR,))
  84. def get_redis() -> Optional[Redis]:
  85. """Get the redis client.
  86. Returns:
  87. The redis client.
  88. """
  89. config = get_config()
  90. if config.redis_url is None:
  91. return None
  92. redis_url, redis_port = config.redis_url.split(":")
  93. print("Using redis at", config.redis_url)
  94. return Redis(host=redis_url, port=int(redis_port), db=0)
  95. def get_production_backend_url() -> str:
  96. """Get the production backend URL.
  97. Returns:
  98. The production backend URL.
  99. """
  100. config = get_config()
  101. return constants.PRODUCTION_BACKEND_URL.format(
  102. username=config.username,
  103. app_name=config.app_name,
  104. )
  105. def get_default_app_name() -> str:
  106. """Get the default app name.
  107. The default app name is the name of the current directory.
  108. Returns:
  109. The default app name.
  110. """
  111. return os.getcwd().split(os.path.sep)[-1].replace("-", "_")
  112. def create_config(app_name: str):
  113. """Create a new pcconfig file.
  114. Args:
  115. app_name: The name of the app.
  116. """
  117. # Import here to avoid circular imports.
  118. from pynecone.compiler import templates
  119. config_name = f"{re.sub(r'[^a-zA-Z]', '', app_name).capitalize()}Config"
  120. with open(constants.CONFIG_FILE, "w") as f:
  121. f.write(templates.PCCONFIG.render(app_name=app_name, config_name=config_name))
  122. def create_web_directory(root: Path) -> str:
  123. """Creates a web directory in the given root directory
  124. and returns the path to the directory.
  125. Args:
  126. root (Path): The root directory of the project.
  127. Returns:
  128. The path to the web directory.
  129. """
  130. web_dir = str(root / constants.WEB_DIR)
  131. path_ops.cp(constants.WEB_TEMPLATE_DIR, web_dir, overwrite=False)
  132. return web_dir
  133. def initialize_gitignore():
  134. """Initialize the template .gitignore file."""
  135. # The files to add to the .gitignore file.
  136. files = constants.DEFAULT_GITIGNORE
  137. # Subtract current ignored files.
  138. if os.path.exists(constants.GITIGNORE_FILE):
  139. with open(constants.GITIGNORE_FILE, "r") as f:
  140. files |= set([line.strip() for line in f.readlines()])
  141. # Write files to the .gitignore file.
  142. with open(constants.GITIGNORE_FILE, "w") as f:
  143. f.write(f"{(path_ops.join(sorted(files))).lstrip()}")
  144. def initialize_app_directory(app_name: str, template: constants.Template):
  145. """Initialize the app directory on pc init.
  146. Args:
  147. app_name: The name of the app.
  148. template: The template to use.
  149. """
  150. console.log("Initializing the app directory.")
  151. path_ops.cp(os.path.join(constants.TEMPLATE_DIR, "apps", template.value), app_name)
  152. path_ops.mv(
  153. os.path.join(app_name, template.value + ".py"),
  154. os.path.join(app_name, app_name + constants.PY_EXT),
  155. )
  156. path_ops.cp(constants.ASSETS_TEMPLATE_DIR, constants.APP_ASSETS_DIR)
  157. def initialize_web_directory():
  158. """Initialize the web directory on pc init."""
  159. console.log("Initializing the web directory.")
  160. path_ops.rm(os.path.join(constants.WEB_TEMPLATE_DIR, constants.NODE_MODULES))
  161. path_ops.rm(os.path.join(constants.WEB_TEMPLATE_DIR, constants.PACKAGE_LOCK))
  162. path_ops.cp(constants.WEB_TEMPLATE_DIR, constants.WEB_DIR)
  163. path_ops.mkdir(constants.WEB_ASSETS_DIR)
  164. # Write the current version of distributed pynecone package to a PCVERSION_APP_FILE."""
  165. with open(constants.PCVERSION_APP_FILE, "w") as f:
  166. pynecone_json = {"version": constants.VERSION}
  167. json.dump(pynecone_json, f, ensure_ascii=False)
  168. def validate_and_install_bun(initialize=True):
  169. """Check that bun version requirements are met. If they are not,
  170. ask user whether to install required version.
  171. Args:
  172. initialize: whether this function is called on `pc init` or `pc run`.
  173. Raises:
  174. Exit: If the bun version is not supported.
  175. """
  176. bun_version = get_bun_version()
  177. if bun_version is not None and (
  178. bun_version < version.parse(constants.MIN_BUN_VERSION)
  179. or bun_version > version.parse(constants.MAX_BUN_VERSION)
  180. ):
  181. console.print(
  182. f"""[red]Bun version {bun_version} is not supported by Pynecone. Please change your to bun version to be between {constants.MIN_BUN_VERSION} and {constants.MAX_BUN_VERSION}."""
  183. )
  184. action = console.ask(
  185. "Enter 'yes' to install the latest supported bun version or 'no' to exit.",
  186. choices=["yes", "no"],
  187. default="no",
  188. )
  189. if action == "yes":
  190. remove_existing_bun_installation()
  191. install_bun()
  192. return
  193. else:
  194. raise typer.Exit()
  195. if initialize:
  196. install_bun()
  197. def remove_existing_bun_installation():
  198. """Remove existing bun installation."""
  199. package_manager = get_package_manager()
  200. if os.path.exists(package_manager):
  201. console.log("Removing bun...")
  202. path_ops.rm(os.path.expandvars(constants.BUN_ROOT_PATH))
  203. def install_bun():
  204. """Install bun onto the user's system.
  205. Raises:
  206. FileNotFoundError: if unzip or curl packages are not found.
  207. """
  208. # Bun is not supported on Windows.
  209. if platform.system() == "Windows":
  210. console.log("Skipping bun installation on Windows.")
  211. return
  212. # Only install if bun is not already installed.
  213. if not os.path.exists(get_package_manager()):
  214. console.log("Installing bun...")
  215. # Check if curl is installed
  216. curl_path = path_ops.which("curl")
  217. if curl_path is None:
  218. raise FileNotFoundError("Pynecone requires curl to be installed.")
  219. # Check if unzip is installed
  220. unzip_path = path_ops.which("unzip")
  221. if unzip_path is None:
  222. raise FileNotFoundError("Pynecone requires unzip to be installed.")
  223. os.system(constants.INSTALL_BUN)
  224. def install_frontend_packages(web_dir: str):
  225. """Installs the base and custom frontend packages
  226. into the given web directory.
  227. Args:
  228. web_dir (str): The directory where the frontend code is located.
  229. """
  230. # Install the frontend packages.
  231. console.rule("[bold]Installing frontend packages")
  232. # Install the base packages.
  233. subprocess.run(
  234. [get_package_manager(), "install"],
  235. cwd=web_dir,
  236. stdout=subprocess.PIPE,
  237. )
  238. # Install the app packages.
  239. packages = get_config().frontend_packages
  240. if len(packages) > 0:
  241. subprocess.run(
  242. [get_package_manager(), "add", *packages],
  243. cwd=web_dir,
  244. stdout=subprocess.PIPE,
  245. )
  246. def is_initialized() -> bool:
  247. """Check whether the app is initialized.
  248. Returns:
  249. Whether the app is initialized in the current directory.
  250. """
  251. return os.path.exists(constants.CONFIG_FILE) and os.path.exists(constants.WEB_DIR)
  252. def is_latest_template() -> bool:
  253. """Whether the app is using the latest template.
  254. Returns:
  255. Whether the app is using the latest template.
  256. """
  257. if not os.path.exists(constants.PCVERSION_APP_FILE):
  258. return False
  259. with open(constants.PCVERSION_APP_FILE) as f: # type: ignore
  260. app_version = json.load(f)["version"]
  261. return app_version == constants.VERSION
  262. def check_admin_settings():
  263. """Check if admin settings are set and valid for logging in cli app."""
  264. admin_dash = get_config().admin_dash
  265. current_time = datetime.now()
  266. if admin_dash:
  267. if not admin_dash.models:
  268. console.print(
  269. f"[yellow][Admin Dashboard][/yellow] :megaphone: Admin dashboard enabled, but no models defined in [bold magenta]pcconfig.py[/bold magenta]. Time: {current_time}"
  270. )
  271. else:
  272. console.print(
  273. f"[yellow][Admin Dashboard][/yellow] Admin enabled, building admin dashboard. Time: {current_time}"
  274. )
  275. console.print(
  276. "Admin dashboard running at: [bold green]http://localhost:8000/admin[/bold green]"
  277. )