build.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. """Building the app and initializing all prerequisites."""
  2. from __future__ import annotations
  3. import json
  4. import os
  5. import random
  6. import subprocess
  7. from pathlib import Path
  8. from typing import Optional, Union
  9. from reflex import constants
  10. from reflex.config import get_config
  11. from reflex.utils import console, path_ops, prerequisites
  12. from reflex.utils.processes import new_process, show_progress
  13. def update_json_file(file_path: str, update_dict: dict[str, Union[int, str]]):
  14. """Update the contents of a json file.
  15. Args:
  16. file_path: the path to the JSON file.
  17. update_dict: object to update json.
  18. """
  19. fp = Path(file_path)
  20. # create file if it doesn't exist
  21. fp.touch(exist_ok=True)
  22. # create an empty json object if file is empty
  23. fp.write_text("{}") if fp.stat().st_size == 0 else None
  24. with open(fp) as f: # type: ignore
  25. json_object: dict = json.load(f)
  26. json_object.update(update_dict)
  27. with open(fp, "w") as f:
  28. json.dump(json_object, f, ensure_ascii=False)
  29. def set_reflex_project_hash():
  30. """Write the hash of the Reflex project to a REFLEX_JSON."""
  31. project_hash = random.getrandbits(128)
  32. console.debug(f"Setting project hash to {project_hash}.")
  33. update_json_file(constants.REFLEX_JSON, {"project_hash": project_hash})
  34. def set_environment_variables():
  35. """Write the upload url to a REFLEX_JSON."""
  36. update_json_file(
  37. constants.ENV_JSON,
  38. {
  39. "uploadUrl": constants.Endpoint.UPLOAD.get_url(),
  40. "eventUrl": constants.Endpoint.EVENT.get_url(),
  41. "pingUrl": constants.Endpoint.PING.get_url(),
  42. },
  43. )
  44. def set_os_env(**kwargs):
  45. """Set os environment variables.
  46. Args:
  47. kwargs: env key word args.
  48. """
  49. for key, value in kwargs.items():
  50. if not value:
  51. continue
  52. os.environ[key.upper()] = value
  53. def generate_sitemap_config(deploy_url: str):
  54. """Generate the sitemap config file.
  55. Args:
  56. deploy_url: The URL of the deployed app.
  57. """
  58. # Import here to avoid circular imports.
  59. from reflex.compiler import templates
  60. config = json.dumps(
  61. {
  62. "siteUrl": deploy_url,
  63. "generateRobotsTxt": True,
  64. }
  65. )
  66. with open(constants.SITEMAP_CONFIG_FILE, "w") as f:
  67. f.write(templates.SITEMAP_CONFIG(config=config))
  68. def export(
  69. backend: bool = True,
  70. frontend: bool = True,
  71. zip: bool = False,
  72. deploy_url: Optional[str] = None,
  73. ):
  74. """Export the app for deployment.
  75. Args:
  76. backend: Whether to zip up the backend app.
  77. frontend: Whether to zip up the frontend app.
  78. zip: Whether to zip the app.
  79. deploy_url: The URL of the deployed app.
  80. """
  81. # Remove the static folder.
  82. path_ops.rm(constants.WEB_STATIC_DIR)
  83. # Generate the sitemap file.
  84. command = "export"
  85. if deploy_url is not None:
  86. generate_sitemap_config(deploy_url)
  87. command = "export-sitemap"
  88. checkpoints = [
  89. "Linting and checking ",
  90. "Compiled successfully",
  91. "Route (pages)",
  92. "Collecting page data",
  93. "automatically rendered as static HTML",
  94. 'Copying "static build" directory',
  95. 'Copying "public" directory',
  96. "Finalizing page optimization",
  97. "Export successful",
  98. ]
  99. # Start the subprocess with the progress bar.
  100. process = new_process(
  101. [prerequisites.get_package_manager(), "run", command],
  102. cwd=constants.WEB_DIR,
  103. )
  104. show_progress("Creating Production Build", process, checkpoints)
  105. # Zip up the app.
  106. if zip:
  107. if os.name == "posix":
  108. posix_export(backend, frontend)
  109. if os.name == "nt":
  110. nt_export(backend, frontend)
  111. def nt_export(backend: bool = True, frontend: bool = True):
  112. """Export for nt (Windows) systems.
  113. Args:
  114. backend: Whether to zip up the backend app.
  115. frontend: Whether to zip up the frontend app.
  116. """
  117. cmd = r""
  118. if frontend:
  119. cmd = r'''powershell -Command "Set-Location .web/_static; Compress-Archive -Path .\* -DestinationPath ..\..\frontend.zip -Force"'''
  120. os.system(cmd)
  121. if backend:
  122. cmd = r'''powershell -Command "Get-ChildItem -File | Where-Object { $_.Name -notin @('.web', 'assets', 'frontend.zip', 'backend.zip') } | Compress-Archive -DestinationPath backend.zip -Update"'''
  123. os.system(cmd)
  124. def posix_export(backend: bool = True, frontend: bool = True):
  125. """Export for posix (Linux, OSX) systems.
  126. Args:
  127. backend: Whether to zip up the backend app.
  128. frontend: Whether to zip up the frontend app.
  129. """
  130. cmd = r""
  131. if frontend:
  132. cmd = r"cd .web/_static && zip -r ../../frontend.zip ./*"
  133. os.system(cmd)
  134. if backend:
  135. cmd = r"zip -r backend.zip ./* -x .web/\* ./assets\* ./frontend.zip\* ./backend.zip\*"
  136. os.system(cmd)
  137. def setup_frontend(
  138. root: Path,
  139. disable_telemetry: bool = True,
  140. ):
  141. """Set up the frontend to run the app.
  142. Args:
  143. root: The root path of the project.
  144. disable_telemetry: Whether to disable the Next telemetry.
  145. """
  146. # Install frontend packages.
  147. prerequisites.install_frontend_packages()
  148. # Copy asset files to public folder.
  149. path_ops.cp(
  150. src=str(root / constants.APP_ASSETS_DIR),
  151. dest=str(root / constants.WEB_ASSETS_DIR),
  152. )
  153. # Set the environment variables in client (env.json).
  154. set_environment_variables()
  155. # Disable the Next telemetry.
  156. if disable_telemetry:
  157. new_process(
  158. [
  159. prerequisites.get_package_manager(),
  160. "run",
  161. "next",
  162. "telemetry",
  163. "disable",
  164. ],
  165. cwd=constants.WEB_DIR,
  166. stdout=subprocess.DEVNULL,
  167. )
  168. def setup_frontend_prod(
  169. root: Path,
  170. disable_telemetry: bool = True,
  171. ):
  172. """Set up the frontend for prod mode.
  173. Args:
  174. root: The root path of the project.
  175. disable_telemetry: Whether to disable the Next telemetry.
  176. """
  177. setup_frontend(root, disable_telemetry)
  178. export(deploy_url=get_config().deploy_url)