build.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. """Building the app and initializing all prerequisites."""
  2. from __future__ import annotations
  3. import json
  4. import os
  5. import subprocess
  6. import zipfile
  7. from pathlib import Path
  8. from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
  9. from reflex import constants
  10. from reflex.config import get_config
  11. from reflex.utils import console, path_ops, prerequisites, processes
  12. from reflex.utils.exec import is_in_app_harness
  13. def set_env_json():
  14. """Write the upload url to a REFLEX_JSON."""
  15. path_ops.update_json_file(
  16. str(prerequisites.get_web_dir() / constants.Dirs.ENV_JSON),
  17. {
  18. **{endpoint.name: endpoint.get_url() for endpoint in constants.Endpoint},
  19. "TEST_MODE": is_in_app_harness(),
  20. },
  21. )
  22. def generate_sitemap_config(deploy_url: str, export: bool = False):
  23. """Generate the sitemap config file.
  24. Args:
  25. deploy_url: The URL of the deployed app.
  26. export: If the sitemap are generated for an export.
  27. """
  28. # Import here to avoid circular imports.
  29. from reflex.compiler import templates
  30. config = {
  31. "siteUrl": deploy_url,
  32. "generateRobotsTxt": True,
  33. }
  34. if export:
  35. config["outDir"] = constants.Dirs.STATIC
  36. config = json.dumps(config)
  37. sitemap = prerequisites.get_web_dir() / constants.Next.SITEMAP_CONFIG_FILE
  38. sitemap.write_text(templates.SITEMAP_CONFIG(config=config))
  39. def _zip(
  40. component_name: constants.ComponentName,
  41. target: str | Path,
  42. root_dir: str | Path,
  43. exclude_venv_dirs: bool,
  44. upload_db_file: bool = False,
  45. dirs_to_exclude: set[str] | None = None,
  46. files_to_exclude: set[str] | None = None,
  47. top_level_dirs_to_exclude: set[str] | None = None,
  48. globs_to_include: list[str] | None = None,
  49. ) -> None:
  50. """Zip utility function.
  51. Args:
  52. component_name: The name of the component: backend or frontend.
  53. target: The target zip file.
  54. root_dir: The root directory to zip.
  55. exclude_venv_dirs: Whether to exclude venv directories.
  56. upload_db_file: Whether to include local sqlite db files.
  57. dirs_to_exclude: The directories to exclude.
  58. files_to_exclude: The files to exclude.
  59. top_level_dirs_to_exclude: The top level directory names immediately under root_dir to exclude. Do not exclude folders by these names further in the sub-directories.
  60. globs_to_include: Apply these globs from the root_dir and always include them in the zip.
  61. """
  62. target = Path(target)
  63. root_dir = Path(root_dir)
  64. dirs_to_exclude = dirs_to_exclude or set()
  65. files_to_exclude = files_to_exclude or set()
  66. files_to_zip: list[str] = []
  67. # Traverse the root directory in a top-down manner. In this traversal order,
  68. # we can modify the dirs list in-place to remove directories we don't want to include.
  69. for root, dirs, files in os.walk(root_dir, topdown=True):
  70. root = Path(root)
  71. # Modify the dirs in-place so excluded and hidden directories are skipped in next traversal.
  72. dirs[:] = [
  73. d
  74. for d in dirs
  75. if (basename := Path(d).resolve().name) not in dirs_to_exclude
  76. and not basename.startswith(".")
  77. and (not exclude_venv_dirs or not _looks_like_venv_dir(root / d))
  78. ]
  79. # If we are at the top level with root_dir, exclude the top level dirs.
  80. if top_level_dirs_to_exclude and root == root_dir:
  81. dirs[:] = [d for d in dirs if d not in top_level_dirs_to_exclude]
  82. # Modify the files in-place so the hidden files and db files are excluded.
  83. files[:] = [
  84. f
  85. for f in files
  86. if not f.startswith(".") and (upload_db_file or not f.endswith(".db"))
  87. ]
  88. files_to_zip += [
  89. str(root / file) for file in files if file not in files_to_exclude
  90. ]
  91. if globs_to_include:
  92. for glob in globs_to_include:
  93. files_to_zip += [
  94. str(file)
  95. for file in root_dir.glob(glob)
  96. if file.name not in files_to_exclude
  97. ]
  98. # Create a progress bar for zipping the component.
  99. progress = Progress(
  100. *Progress.get_default_columns()[:-1],
  101. MofNCompleteColumn(),
  102. TimeElapsedColumn(),
  103. )
  104. task = progress.add_task(
  105. f"Zipping {component_name.value}:", total=len(files_to_zip)
  106. )
  107. with progress, zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as zipf:
  108. for file in files_to_zip:
  109. console.debug(f"{target}: {file}", progress=progress)
  110. progress.advance(task)
  111. zipf.write(file, Path(file).relative_to(root_dir))
  112. def zip_app(
  113. frontend: bool = True,
  114. backend: bool = True,
  115. zip_dest_dir: str | Path = Path.cwd(),
  116. upload_db_file: bool = False,
  117. ):
  118. """Zip up the app.
  119. Args:
  120. frontend: Whether to zip up the frontend app.
  121. backend: Whether to zip up the backend app.
  122. zip_dest_dir: The directory to export the zip file to.
  123. upload_db_file: Whether to upload the database file.
  124. """
  125. zip_dest_dir = Path(zip_dest_dir)
  126. files_to_exclude = {
  127. constants.ComponentName.FRONTEND.zip(),
  128. constants.ComponentName.BACKEND.zip(),
  129. }
  130. if frontend:
  131. _zip(
  132. component_name=constants.ComponentName.FRONTEND,
  133. target=zip_dest_dir / constants.ComponentName.FRONTEND.zip(),
  134. root_dir=prerequisites.get_web_dir() / constants.Dirs.STATIC,
  135. files_to_exclude=files_to_exclude,
  136. exclude_venv_dirs=False,
  137. )
  138. if backend:
  139. _zip(
  140. component_name=constants.ComponentName.BACKEND,
  141. target=zip_dest_dir / constants.ComponentName.BACKEND.zip(),
  142. root_dir=Path.cwd(),
  143. dirs_to_exclude={"__pycache__"},
  144. files_to_exclude=files_to_exclude,
  145. top_level_dirs_to_exclude={"assets"},
  146. exclude_venv_dirs=True,
  147. upload_db_file=upload_db_file,
  148. globs_to_include=[
  149. str(Path(constants.Dirs.WEB) / constants.Dirs.BACKEND / "*")
  150. ],
  151. )
  152. def build(
  153. deploy_url: str | None = None,
  154. for_export: bool = False,
  155. ):
  156. """Build the app for deployment.
  157. Args:
  158. deploy_url: The deployment URL.
  159. for_export: Whether the build is for export.
  160. """
  161. wdir = prerequisites.get_web_dir()
  162. # Clean the static directory if it exists.
  163. path_ops.rm(str(wdir / constants.Dirs.STATIC))
  164. # The export command to run.
  165. command = "export"
  166. checkpoints = [
  167. "Linting and checking ",
  168. "Creating an optimized production build",
  169. "Route (pages)",
  170. "prerendered as static HTML",
  171. "Collecting page data",
  172. "Finalizing page optimization",
  173. "Collecting build traces",
  174. ]
  175. # Generate a sitemap if a deploy URL is provided.
  176. if deploy_url is not None:
  177. generate_sitemap_config(deploy_url, export=for_export)
  178. command = "export-sitemap"
  179. checkpoints.extend(["Loading next-sitemap", "Generation completed"])
  180. # Start the subprocess with the progress bar.
  181. process = processes.new_process(
  182. [*prerequisites.get_js_package_executor(raise_on_none=True)[0], "run", command],
  183. cwd=wdir,
  184. shell=constants.IS_WINDOWS,
  185. )
  186. processes.show_progress("Creating Production Build", process, checkpoints)
  187. def setup_frontend(
  188. root: Path,
  189. disable_telemetry: bool = True,
  190. ):
  191. """Set up the frontend to run the app.
  192. Args:
  193. root: The root path of the project.
  194. disable_telemetry: Whether to disable the Next telemetry.
  195. """
  196. # Create the assets dir if it doesn't exist.
  197. path_ops.mkdir(constants.Dirs.APP_ASSETS)
  198. # Copy asset files to public folder.
  199. path_ops.cp(
  200. src=str(root / constants.Dirs.APP_ASSETS),
  201. dest=str(root / prerequisites.get_web_dir() / constants.Dirs.PUBLIC),
  202. )
  203. # Set the environment variables in client (env.json).
  204. set_env_json()
  205. # update the last reflex run time.
  206. prerequisites.set_last_reflex_run_time()
  207. # Disable the Next telemetry.
  208. if disable_telemetry:
  209. processes.new_process(
  210. [
  211. *prerequisites.get_js_package_executor(raise_on_none=True)[0],
  212. "run",
  213. "next",
  214. "telemetry",
  215. "disable",
  216. ],
  217. cwd=prerequisites.get_web_dir(),
  218. stdout=subprocess.DEVNULL,
  219. shell=constants.IS_WINDOWS,
  220. )
  221. def setup_frontend_prod(
  222. root: Path,
  223. disable_telemetry: bool = True,
  224. ):
  225. """Set up the frontend for prod mode.
  226. Args:
  227. root: The root path of the project.
  228. disable_telemetry: Whether to disable the Next telemetry.
  229. """
  230. setup_frontend(root, disable_telemetry)
  231. build(deploy_url=get_config().deploy_url)
  232. def _looks_like_venv_dir(dir_to_check: str | Path) -> bool:
  233. dir_to_check = Path(dir_to_check)
  234. return (dir_to_check / "pyvenv.cfg").exists()