prerequisites.py 9.9 KB

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