android_post_build.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. #
  2. # Copyright (c) Contributors to the Open 3D Engine Project.
  3. # For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. #
  5. # SPDX-License-Identifier: Apache-2.0 OR MIT
  6. #
  7. #
  8. import argparse
  9. import re
  10. import shutil
  11. import sys
  12. import platform
  13. import logging
  14. from packaging.version import Version
  15. from pathlib import Path
  16. logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
  17. logger = logging.getLogger('o3de.android')
  18. ANDROID_ARCH = 'arm64-v8a'
  19. ASSET_MODE_PAK = 'PAK'
  20. ASSET_MODE_LOOSE = 'LOOSE'
  21. SUPPORTED_ASSET_MODES = [ASSET_MODE_PAK, ASSET_MODE_LOOSE]
  22. ASSET_PLATFORM_KEY = 'android'
  23. SUPPORTED_BUILD_CONFIGS = ['debug', 'profile', 'release']
  24. MINIMUM_ANDROID_GRADLE_PLUGIN_VER = Version("4.2")
  25. IS_PLATFORM_WINDOWS = platform.system() == 'Windows'
  26. PAK_FILE_INSTRUCTIONS = "Make sure to create release bundles (Pak files) before building and deploying to an android device. Refer to " \
  27. "https://www.docs.o3de.org/docs/user-guide/packaging/asset-bundler/bundle-assets-for-release/ for more" \
  28. "information."
  29. class AndroidPostBuildError(Exception):
  30. pass
  31. def create_link(src: Path, tgt: Path):
  32. """
  33. Create a link/junction depending on the source type. If this is a file, then perform file copy from the
  34. source to the target. If it is a directory, then create a junction(windows) or symlink(linux/mac) from the source to
  35. the target
  36. :param src: The source to link from
  37. :param tgt: The target tp link to
  38. """
  39. assert src.exists()
  40. assert not tgt.exists()
  41. try:
  42. if src.is_file():
  43. tgt.symlink_to(src)
  44. logger.info(f"Created symbolic link {str(tgt)} => {str(src)}")
  45. else:
  46. if IS_PLATFORM_WINDOWS:
  47. import _winapi
  48. _winapi.CreateJunction(str(src.resolve().absolute()), str(tgt.resolve().absolute()))
  49. logger.info(f'Created Junction {str(tgt)} => {str(src)}')
  50. else:
  51. tgt.symlink_to(src, target_is_directory=True)
  52. logger.info(f'Created symbolic link {str(tgt)} => {str(src)}')
  53. except OSError as os_err:
  54. raise AndroidPostBuildError(f"Error trying to link {tgt} => {src} : {os_err}")
  55. # deprecated: The functionality has been replaced with a single call to remove_link_to_directory()
  56. # Go to commit e302882 to get this functionality back.
  57. # def safe_clear_folder(target_folder: Path) -> None:
  58. def remove_link_to_directory(link_to_directory: Path) -> None:
  59. """
  60. Removes a Symbolic Link or Junction(Windows) that points to a directory
  61. Throws an exception if the link exists, and it points to a directory and could not be deleted.
  62. :param link_to_directory: The symbolic link or junction which should point to a directory.
  63. """
  64. if link_to_directory.is_dir():
  65. try:
  66. link_to_directory.unlink()
  67. except OSError as os_err:
  68. raise AndroidPostBuildError(f"Error trying to unlink/delete {link_to_directory}: {os_err}")
  69. # deprecated: The functionality has been replaced with a single call to create_link()
  70. # Go to commit e302882 to get this functionality back.
  71. # def synchronize_folders(src: Path, tgt: Path) -> None:
  72. def apply_pak_layout(project_root: Path, asset_bundle_folder: str, target_layout_root: Path) -> None:
  73. """
  74. Apply the pak folder layout to the target assets folder
  75. :param project_root: The project root folder to base the search for the location of the pak files (Bundle)
  76. :param asset_bundle_folder: The sub path within the project root folder of the location of the pak files
  77. :param target_layout_root: The target layout destination of the pak files
  78. """
  79. src_pak_file_full_path = project_root / asset_bundle_folder
  80. # Make sure that the source bundle folder where we look up the paks exist
  81. if not src_pak_file_full_path.is_dir():
  82. raise AndroidPostBuildError(f"Pak files are expected at location {src_pak_file_full_path}, but the folder doesnt exist. {PAK_FILE_INSTRUCTIONS}")
  83. # Make sure that we have at least the engine_android.pak file
  84. has_engine_android_pak = False
  85. for pak_dir_item in src_pak_file_full_path.iterdir():
  86. if pak_dir_item.is_file and str(pak_dir_item.name).lower() == f'engine_{ASSET_PLATFORM_KEY}.pak':
  87. has_engine_android_pak = True
  88. break
  89. if not has_engine_android_pak:
  90. raise AndroidPostBuildError(f"Unable to located the required 'engine_android.pak' file at location specified at {src_pak_file_full_path}. "
  91. f"{PAK_FILE_INSTRUCTIONS}")
  92. # Remove the link to the source assets folder, if it exists.
  93. remove_link_to_directory(target_layout_root)
  94. # Create the link to the asset bundle folder.
  95. create_link(src_pak_file_full_path, target_layout_root)
  96. def apply_loose_layout(project_root: Path, target_layout_root: Path) -> None:
  97. """
  98. Apply the loose assets folder layout rules to the target assets folder
  99. :param project_root: The project folder root to look for the loose assets
  100. :param target_layout_root: The target layout destination of the loose assets
  101. """
  102. android_cache_folder = project_root / 'Cache' / ASSET_PLATFORM_KEY
  103. engine_json_marker = android_cache_folder / 'engine.json'
  104. if not engine_json_marker.is_file():
  105. raise AndroidPostBuildError(f"Assets have not been built for this project at ({project_root}) yet. "
  106. f"Please run the AssetProcessor for this project first.")
  107. # Remove the link to the source assets folder, if it exists.
  108. remove_link_to_directory(target_layout_root)
  109. # Create a symlink or junction {target_layout_root} to this
  110. # project Cache folder for the android platform {android_cache_folder}.
  111. create_link(android_cache_folder, target_layout_root)
  112. def post_build_action(android_app_root: Path, project_root: Path, gradle_version: Version,
  113. asset_mode: str, asset_bundle_folder: str):
  114. """
  115. Perform the post-build logic for android native builds that will prepare the output folders by laying out the asset files
  116. to their locations before the APK is generated.
  117. :param android_app_root: The root path of the 'app' project within the Android Gradle build script
  118. :param project_root: The root of the project that the APK is being built for
  119. :param gradle_version: The version of Gradle used to build the APK (for validation)
  120. :param asset_mode: The desired asset mode to determine the layout rules
  121. :param asset_bundle_folder: (For PAK asset modes) the location of where the PAK files are expected.
  122. """
  123. if not android_app_root.is_dir():
  124. raise AndroidPostBuildError(f"Invalid Android Gradle build path: {android_app_root} is not a directory or does not exist.")
  125. if gradle_version < MINIMUM_ANDROID_GRADLE_PLUGIN_VER:
  126. raise AndroidPostBuildError(f"Android gradle plugin versions below version {MINIMUM_ANDROID_GRADLE_PLUGIN_VER} is not supported.")
  127. logger.info(f"Applying post-build for android gradle plugin version {gradle_version}")
  128. # Validate the build directory exists
  129. app_build_root = android_app_root / 'build'
  130. if not app_build_root.is_dir():
  131. raise AndroidPostBuildError(f"Android gradle build path: {app_build_root} is not a directory or does not exist.")
  132. target_layout_root = android_app_root / 'src' / 'main' / 'assets'
  133. if asset_mode == ASSET_MODE_LOOSE:
  134. apply_loose_layout(project_root=project_root,
  135. target_layout_root=target_layout_root)
  136. elif asset_mode == ASSET_MODE_PAK:
  137. apply_pak_layout(project_root=project_root,
  138. target_layout_root=target_layout_root,
  139. asset_bundle_folder=asset_bundle_folder)
  140. else:
  141. raise AndroidPostBuildError(f"Invalid Asset Mode '{asset_mode}'.")
  142. if __name__ == '__main__':
  143. try:
  144. parser = argparse.ArgumentParser(description="Android post Gradle build step handler")
  145. parser.add_argument('android_app_root', type=str, help="The base of the 'app' in the O3DE generated gradle script.")
  146. parser.add_argument('--project-root', type=str, help="The project root.", required=True)
  147. parser.add_argument('--gradle-version', type=str, help="The version of Gradle.", required=True)
  148. parser.add_argument('--asset-mode', type=str, help="The asset mode of deployment", default=ASSET_MODE_LOOSE, choices=SUPPORTED_ASSET_MODES)
  149. parser.add_argument('--asset-bundle-folder', type=str, help="The sub folder from the project root where the pak files are located (For Pak Asset Mode)",
  150. default="AssetBundling/Bundles")
  151. args = parser.parse_args(sys.argv[1:])
  152. post_build_action(android_app_root=Path(args.android_app_root),
  153. project_root=Path(args.project_root),
  154. gradle_version=Version(args.gradle_version),
  155. asset_mode=args.asset_mode,
  156. asset_bundle_folder=args.asset_bundle_folder)
  157. exit(0)
  158. except AndroidPostBuildError as err:
  159. logging.error(str(err))
  160. exit(1)