android_post_build.py 9.3 KB

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