pull_and_build_from_git.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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 fnmatch
  10. import glob
  11. import json
  12. import os
  13. import pathlib
  14. import platform
  15. import re
  16. import shutil
  17. import string
  18. import subprocess
  19. import sys
  20. from package_downloader import PackageDownloader
  21. SCHEMA_DESCRIPTION = """
  22. Build Config Description:
  23. The build configuration (build_config.json) accepts keys that are root level only, and some keys that can be
  24. either global or target platform specific. Root level only keys are keys that define the project and cannot
  25. be different by platform, and all are required. The keys are:
  26. * package_name : The base name of the package, used for constructing the filename and folder structures
  27. * package_url : The package url that will be placed in the PackageInfo.json
  28. * package_license : The type of license that will be described in the PackageInfo.json
  29. * package_license_file : The name of the source code license file (expected at the root of the source folder pulled from git)
  30. The following keys can exist at the root level or the target-platform level:
  31. * git_url : The git clone url for the source to pull for building
  32. * git_tag : The git tag or branch to identify the branch to pull from for building
  33. * git_commit : (optional) A specific git commit to check out. This is useful for upstream repos that do not tag their releases.
  34. * package_version : (required) The string to describe the package version. This string is used to build the full package name.
  35. This can be uniform for all platforms or can be set for a specific platform
  36. * prebuilt_source : (optional) If the 3rd party library files are prebuilt and accessible, then setting this key to the relative location of
  37. the folder will cause the workflow to perform copy operations into the generated target library folder directly (see
  38. 'prebuilt_args' below.
  39. * prebuild_args : (required if prebuilt_source is set) A map of target subfolders within the target 3rd party folder against a glob pattern of
  40. file(s) to copy to the target subfolders.
  41. * cmake_find_source : The name of the source find*.cmake file that will be used in the target package
  42. that is ingested by the lumberyard 3P system.
  43. * cmake_find_template : If the find*.cmake in the target package requires template processing, then this is name of the template file that is used to
  44. generate the contents of the find*.cmake file in the target package.
  45. * Note that either 'cmake_find_source' or 'cmake_fine_template' must be declared.
  46. * cmake_find_target : (required if prebuilt_source is not set) The name of the target find*.cmake file that is generated based on the template file and
  47. additional arguments (described below)
  48. * build_configs : (optional) A list of configurations to build during the build process. This is available
  49. to restrict building to a specific configuration rather than building all configurations
  50. (provided by the default value: ['Debug', 'Release'])
  51. * patch_file : (optional) Option patch file to apply to the synced source before performing a build
  52. * source_path : (optional) Option to provide a path to the project source rather than getting it from github
  53. * git_skip : (optional) Option to skip all git commands, requires source_path
  54. * cmake_src_subfolder : (optional) Some packages don't have a CMakeLists at the root and instead its in a subfolder.
  55. In this case, set this to be the relative path from the src root to the folder that
  56. contains the CMakeLists.txt.
  57. * cmake_generate_args_common : (optional) When used at the root, this provides a set of cmake arguments for generation which will
  58. apply to ALL platforms and configs (appended to cmake_generate_args).
  59. Can be overriden by a specific platform by specifying it in the platform specific section.
  60. The final args will be (cmake_generate_args || cmake_generation_args_CONFIG) + cmake_generate_args_common
  61. * cmake_build_args_common : (optional) When used at the root, provides a set of cmake arguments for building which will apply to ALL
  62. platforms and configurations.
  63. The final args will be (cmake_build_args || cmake_build_args_CONFIG) + cmake_build_args_common
  64. `cmake --build (build folder) --config config` will automatically be supplied.
  65. The following keys can only exist at the target platform level as they describe the specifics for that platform.
  66. * cmake_generate_args : The cmake generation arguments (minus the build folder target or any configuration) for generating
  67. the project for the platform (for all configurations). To perform specific generation commands (i.e.
  68. for situations where the generator does not support multiple configs) the key can contain the
  69. suffix of the configuration name (cmake_generate_args_debug, cmake_generate_args_release).
  70. For common args that should apply to every config, see cmake_generate_args_common above.
  71. * cmake_build_args : Additional build args to pass to cmake during the cmake build command
  72. * cmake_install_filter : Optional list of filename patterns to filter what is actually copied to the target package based on
  73. the 3rd party library's install definition. (For example, a library may install headers and static
  74. libraries when all you want in the package is just the binary executables). If omitted, then the entire
  75. install tree will be copied to the target package
  76. * custom_build_cmd : A list of custom scripts to run to build from the source that was pulled from git. This option is
  77. mutually exclusive from the cmake_generate_args and cmake_build_args options.
  78. see the note about environment variables below.
  79. * custom_install_cmd : A list of custom scripts to run (after the custom_build_cmd) to copy and assemble the built binaries
  80. into the target package folder.
  81. this argument is optional. You could do the install in your custom build command instead.
  82. see the note about environment variables below.
  83. * custom_install_json : A list of files to copy into the target package folder from the built SDK. This argument is optional.
  84. * custom_test_cmd : after making the package, it will run this and expect exit code 0
  85. this argument is optional.
  86. see the note about environment variables below.
  87. * custom_additional_compile_definitions : Any additional compile definitions to apply in the find*.cmake file for the library that will applied
  88. to targets that consume this 3P library
  89. * custom_additional_link_options : Any additional linker options to apply in the find*.cmake file for the library that will applied
  90. to targets that consume this 3P library during linking
  91. * custom_additional_libraries : Any additional dependent system library to include in the find*.cmake file for the library that will
  92. applied to targets that consume this 3P library during linking
  93. * custom_cmake_install : Custom flag for certain platforms (ie iOS) that needs the installation arguments applied during the
  94. cmake generation, and not to apply the cmake install process
  95. * depends_on_packages : list of name of 3-TUPLES of [package name, package hash, subfolder] that 'find' files live in]
  96. [ ["zlib-1.5.3-rev5", "some hash", ""],
  97. ["some other package", "some other hash", "subfoldername"],
  98. ...
  99. ]
  100. that we need to download and use).
  101. - note that we don't check recursively - you must name your recursive deps!
  102. - The packages must be on a public CDN or locally tested with FILE:// - it uses env var
  103. "LY_PACKAGE_SERVER_URLS" which can be a semicolon seperated list of places to try.
  104. - The packages unzip path + subfolder is added to CMAKE_MODULE_PATH if you use cmake commands.
  105. - Otherwise you can use DOWNLOADED_PACKAGE_FOLDERS env var in your custom script and set
  106. - CMAKE_MODULE_PATH to be that value, yourself.
  107. - The subfolder can be empty, in which case the root of the package will be used.
  108. Note about environment variables:
  109. When custom commands are issued (build, install, and test), the following environment variables will be set
  110. for the process:
  111. PACKAGE_ROOT = root of the package being made (where PackageInfo.json is generated/copied)
  112. TARGET_INSTALL_ROOT = $PACKAGE_ROOT/$PACKAGE_NAME - usually where you target cmake install to
  113. TEMP_FOLDER = the temp folder. This folder usually has subfolder 'build' and 'src'
  114. PYTHON_BINARY = the path to the python binary that launched the build script. This can be useful if
  115. one of the custom build/install scripts (e.g. my_script.sh/.cmd) want to invoke
  116. a python script using the same python executable that launched the build.
  117. DOWNLOADED_PACKAGE_FOLDERS = semicolon seperated list of abs paths to each downloaded package Find folder.
  118. - usually used to set CMAKE_MODULE_PATH so it can find the packages.
  119. - unset if there are no dependencies declared
  120. Note that any of the above environment variables that contain paths will use system native slashes for script
  121. compatibility, and may need to be converted to forward slash in your script on windows
  122. if you feed it to cmake.
  123. Also note that the working directory for all custom commands will the folder containing the build_config.json file.
  124. The general layout of the build_config.json file is as follows:
  125. {
  126. ${root level keys}
  127. ${global keys}
  128. "Platforms": {
  129. ${Host Platforms}: {
  130. ${Target Platform}: {
  131. ${platform specific general keys}
  132. ${platform specific required keys}
  133. }
  134. }
  135. }
  136. }
  137. """
  138. # The current path of this script, expected to be under '3rdPartySource/Scripts'
  139. CURRENT_PATH = pathlib.Path(os.path.dirname(__file__)).resolve()
  140. # Expected package-system folder as the parent of this folder
  141. PACKAGE_SYSTEM_PATH = CURRENT_PATH.parent.parent / 'package-system'
  142. assert PACKAGE_SYSTEM_PATH.is_dir(), "Missing package-system folder, make sure it is synced from source control"
  143. # Some platforms required environment variables to be set before the build, create the appropriate pattern to search for it
  144. if platform.system() == 'Windows':
  145. ENV_PATTERN = re.compile(r"(%([a-zA-Z0-9_]*)%)")
  146. else:
  147. ENV_PATTERN = re.compile(r"($([a-zA-Z0-9_]*))")
  148. DEFAULT_BUILD_CONFIG_FILENAME = "build_config.json"
  149. class BuildError(Exception):
  150. """
  151. Manage Package Build specific exceptions
  152. """
  153. pass
  154. class PackageInfo(object):
  155. """
  156. This class manages general information for the package based on the build config and target platform
  157. information. It does not manage the actual cmake commands
  158. """
  159. PACKAGE_INFO_TEMPLATE = """{
  160. "PackageName" : "$package_name-$package_version-$platform_name",
  161. "URL" : "$package_url",
  162. "License" : "$package_license",
  163. "LicenseFile" : "$package_name/$package_license_file"
  164. }
  165. """
  166. def __init__(self, build_config, target_platform_name, target_platform_config):
  167. """
  168. Initialize the PackageInfo
  169. :param build_config: The entire build configuration dictionary (from the build config json file)
  170. :param target_platform_name: The target platform name that is being packaged for
  171. :param target_platform_config: The target platform configuration (from the build configuration dictionary)
  172. """
  173. self.platform_name = target_platform_name
  174. try:
  175. self.package_name = build_config["package_name"]
  176. self.package_url = build_config["package_url"]
  177. self.package_license = build_config["package_license"]
  178. self.package_license_file = build_config["package_license_file"]
  179. except KeyError as e:
  180. raise BuildError(f"Invalid build config. Missing required key : {str(e)}")
  181. def _get_value(value_key, required=True, default=None):
  182. result = target_platform_config.get(value_key, build_config.get(value_key, default))
  183. if required and result is None:
  184. raise BuildError(f"Required key '{value_key}' not found in build config")
  185. return result
  186. self.git_url = _get_value("git_url")
  187. self.git_tag = _get_value("git_tag")
  188. self.package_version = _get_value("package_version")
  189. self.patch_file = _get_value("patch_file", required=False)
  190. self.git_commit = _get_value("git_commit", required=False)
  191. self.cmake_find_template = _get_value("cmake_find_template", required=False)
  192. self.cmake_find_source = _get_value("cmake_find_source", required=False)
  193. self.cmake_find_target = _get_value("cmake_find_target")
  194. self.cmake_find_template_custom_indent = _get_value("cmake_find_template_custom_indent", default=1)
  195. self.additional_src_files = _get_value("additional_src_files", required=False)
  196. self.depends_on_packages = _get_value("depends_on_packages", required=False)
  197. self.cmake_src_subfolder = _get_value("cmake_src_subfolder", required=False)
  198. self.cmake_generate_args_common = _get_value("cmake_generate_args_common", required=False)
  199. self.cmake_build_args_common = _get_value("cmake_build_args_common", required=False)
  200. if self.cmake_find_template and self.cmake_find_source:
  201. raise BuildError("Bad build config file. 'cmake_find_template' and 'cmake_find_source' cannot both be set in the configuration.")
  202. if not self.cmake_find_template and not self.cmake_find_source:
  203. raise BuildError("Bad build config file. 'cmake_find_template' or 'cmake_find_source' must be set in the configuration.")
  204. def write_package_info(self, install_path):
  205. """
  206. Write to the target 'PackageInfo.json' file for the package
  207. :param install_path: The folder to write the file to
  208. """
  209. package_info_target_file = install_path / "PackageInfo.json"
  210. if package_info_target_file.is_file():
  211. package_info_target_file.unlink()
  212. package_info_env = {
  213. 'package_name': self.package_name,
  214. 'package_version': self.package_version,
  215. 'platform_name': self.platform_name.lower(),
  216. 'package_url': self.package_url,
  217. 'package_license': self.package_license,
  218. 'package_license_file': os.path.basename(self.package_license_file)
  219. }
  220. package_info_content = string.Template(PackageInfo.PACKAGE_INFO_TEMPLATE).substitute(package_info_env)
  221. package_info_target_file.write_text(package_info_content)
  222. def subp_args(args):
  223. """
  224. According to subcommand, when using shell=True, its recommended not to pass in an argument list but the full command line as a single string.
  225. That means in the argument list in the configuration make sure to provide the proper escapements or double-quotes for paths with spaces
  226. :param args: The list of arguments to transform
  227. """
  228. arg_string = " ".join([arg for arg in args])
  229. print(f"Command: {arg_string}")
  230. return arg_string
  231. def validate_git():
  232. """
  233. If make sure git is available
  234. :return: String describing the version of the detected git
  235. """
  236. call_result = subprocess.run(subp_args(['git', '--version']), shell=True, capture_output=True)
  237. if call_result.returncode != 0 and call_result.returncode != 1:
  238. raise BuildError("Git is not installed on the default path. Make sure its installed")
  239. version_result = call_result.stdout.decode('UTF-8', 'ignore').strip()
  240. return version_result
  241. def validate_cmake(cmake_path):
  242. """
  243. Make sure that the cmake command being used is available and confirm the version
  244. :return: String describing the version of cmake
  245. """
  246. call_result = subprocess.run(subp_args([cmake_path, '--version']), shell=True, capture_output=True)
  247. if call_result.returncode != 0:
  248. raise BuildError(f"Unable to detect CMake ({cmake_path})")
  249. version_result_lines = call_result.stdout.decode('UTF-8', 'ignore').split('\n')
  250. version_result = version_result_lines[0]
  251. print(f"Detected CMake: {version_result}")
  252. return cmake_path
  253. def validate_patch():
  254. """
  255. Make sure patch is installed and on the default path
  256. :return: String describing the version of patch
  257. """
  258. call_result = subprocess.run(subp_args(['patch', '--version']), shell=True, capture_output=True)
  259. if call_result.returncode != 0:
  260. raise BuildError("'Patch' is not installed on the default path. Make sure its installed")
  261. version_result_lines = call_result.stdout.decode('UTF-8', 'ignore').split('\n')
  262. version_result = version_result_lines[0]
  263. return version_result
  264. def delete_folder(folder):
  265. """
  266. Use the system's remove folder command instead of os.rmdir
  267. """
  268. if platform.system() == 'Windows':
  269. call_result = subprocess.run(subp_args(['rmdir', '/Q', '/S', str(folder.name)]),
  270. shell=True,
  271. capture_output=True,
  272. cwd=str(folder.parent.absolute()))
  273. else:
  274. call_result = subprocess.run(subp_args(['rm', '-rf', str(folder.name)]),
  275. shell=True,
  276. capture_output=True,
  277. cwd=str(folder.parent.absolute()))
  278. if call_result.returncode != 0:
  279. raise BuildError(f"Unable to delete folder {str(folder)}: {str(call_result.stderr)}")
  280. def validate_args(input_args):
  281. """
  282. Validate and make sure that if any environment variables are passed into the argument that the environment variable is actually set
  283. """
  284. if input_args:
  285. for arg in input_args:
  286. match_env = ENV_PATTERN.search(arg)
  287. if not match_env:
  288. continue
  289. env_var_name = match_env.group(2)
  290. if not env_var_name:
  291. continue
  292. env_var_value = os.environ.get(env_var_name)
  293. if not env_var_value:
  294. raise BuildError(f"Required environment variable '{env_var_name}' not set")
  295. return input_args
  296. class BuildInfo(object):
  297. """
  298. This is the Build management class that will perform the entire build from source and preparing a folder for packaging
  299. """
  300. def __init__(self, package_info, platform_config, base_folder, build_folder, package_install_root,
  301. custom_toolchain_file, cmake_command, clean_build, cmake_find_template,
  302. cmake_find_source, prebuilt_source, prebuilt_args, src_folder, skip_git):
  303. """
  304. Initialize the Build management object with information needed
  305. :param package_info: The PackageInfo object constructed from the build config
  306. :param platform_config: The target platform configuration from the build config dictionary
  307. :param base_folder: The base folder where the build_config exists
  308. :param build_folder: The root folder to build into
  309. :param package_install_root: The root of the package folder where the new package will be assembled
  310. :param custom_toolchain_file: Option toolchain file to use for specific target platforms
  311. :param cmake_command: The cmake executable command to use for cmake
  312. :param clean_build: Option to clean any existing build folder before proceeding
  313. :param cmake_find_template: The template for the find*.cmake generated file
  314. :param cmake_find_source: The source file for the find*.cmake generated file
  315. :param prebuilt_source: If provided, the git fetch / build flow will be replaced with a copy from a prebuilt folder
  316. :param prebuilt_args: If prebuilt_source is provided, then this argument is required to specify the copy rules to assemble the package from the prebuilt package
  317. :param src_folder: Path to the source code / where to clone the git repo.
  318. :param skip_git: If true skip all git interaction and .
  319. """
  320. assert (cmake_find_template is not None and cmake_find_source is None) or \
  321. (cmake_find_template is None and cmake_find_source is not None), "Either cmake_find_template or cmake_find_source must be set, but not both"
  322. self.package_info = package_info
  323. self.platform_config = platform_config
  324. self.custom_toolchain_file = custom_toolchain_file
  325. self.cmake_command = cmake_command
  326. self.base_folder = base_folder
  327. self.base_temp_folder = build_folder
  328. self.src_folder = src_folder
  329. self.build_folder = self.base_temp_folder / "build"
  330. self.package_install_root = package_install_root / f"{package_info.package_name}-{package_info.platform_name.lower()}"
  331. self.build_install_folder = self.package_install_root / package_info.package_name
  332. self.clean_build = clean_build
  333. self.cmake_find_template = cmake_find_template
  334. self.cmake_find_source = cmake_find_source
  335. self.build_configs = platform_config.get('build_configs', ['Debug', 'Release'])
  336. self.prebuilt_source = prebuilt_source
  337. self.prebuilt_args = prebuilt_args
  338. self.skip_git = skip_git
  339. def clone_to_local(self):
  340. """
  341. Perform a clone to the local temp folder
  342. """
  343. print(f"Cloning {self.package_info.package_name}/{self.package_info.git_tag} to {str(self.src_folder.absolute())}")
  344. working_dir = str(self.src_folder.parent.absolute())
  345. relative_src_dir = self.src_folder.name
  346. clone_cmd = ['git',
  347. 'clone',
  348. '--single-branch',
  349. '--recursive',
  350. '--branch',
  351. self.package_info.git_tag,
  352. self.package_info.git_url,
  353. relative_src_dir]
  354. clone_result = subprocess.run(subp_args(clone_cmd),
  355. shell=True,
  356. capture_output=True,
  357. cwd=working_dir)
  358. if clone_result.returncode != 0:
  359. raise BuildError(f"Error cloning from GitHub: {clone_result.stderr.decode('UTF-8', 'ignore')}")
  360. if self.package_info.git_commit is not None:
  361. # Allow the package to specify a specific commit to check out. This is useful for upstream repos that do
  362. # not tag their releases.
  363. checkout_result = subprocess.run(
  364. ['git', 'checkout', self.package_info.git_commit],
  365. capture_output=True,
  366. cwd=self.src_folder)
  367. if checkout_result.returncode != 0:
  368. raise BuildError(f"Error checking out {self.package_info.git_commit}: {checkout_result.stderr.decode('UTF-8', 'ignore')}")
  369. def prepare_temp_folders(self):
  370. """
  371. Prepare the temp folders for cloning, building, and local installing
  372. """
  373. # Always clean the target package install folder to prevent stale files from being included
  374. if self.package_install_root.is_dir():
  375. delete_folder(self.package_install_root)
  376. if not self.build_folder.is_dir():
  377. self.build_folder.mkdir(parents=True)
  378. elif self.clean_build:
  379. delete_folder(self.build_folder)
  380. self.build_folder.mkdir(parents=True)
  381. if not self.build_install_folder.is_dir():
  382. self.build_install_folder.mkdir(parents=True)
  383. def sync_source(self):
  384. """
  385. Sync the 3rd party from its git source location (either cloning if its not there or syncing)
  386. """
  387. if self.skip_git:
  388. return
  389. # Validate Git is installed
  390. git_version = validate_git()
  391. print(f"Detected Git: {git_version}")
  392. # Sync to the source folder
  393. if self.src_folder.is_dir():
  394. # If the folder exists, see if git stash works or not
  395. git_pull_cmd = ['git',
  396. 'stash']
  397. call_result = subprocess.run(subp_args(git_pull_cmd),
  398. shell=True,
  399. capture_output=True,
  400. cwd=str(self.src_folder.absolute()))
  401. if call_result.returncode != 0:
  402. # Not a valid git folder, okay to remove and re-clone
  403. delete_folder(self.src_folder)
  404. self.clone_to_local()
  405. else:
  406. # Do a re-pull
  407. git_pull_cmd = ['git',
  408. 'pull']
  409. call_result = subprocess.run(subp_args(git_pull_cmd),
  410. shell=True,
  411. capture_output=True,
  412. cwd=str(self.src_folder.absolute()))
  413. if call_result.returncode != 0:
  414. raise BuildError(f"Error pulling source from GitHub: {call_result.stderr.decode('UTF-8', 'ignore')}")
  415. else:
  416. self.clone_to_local()
  417. if self.package_info.additional_src_files:
  418. for additional_src in self.package_info.additional_src_files:
  419. additional_src_path = self.base_folder / additional_src
  420. if not additional_src_path.is_file():
  421. raise BuildError(f"Invalid additional src file: : {additional_src}")
  422. additional_tgt_path = self.src_folder / additional_src
  423. if additional_tgt_path.is_file():
  424. additional_tgt_path.unlink()
  425. shutil.copy2(str(additional_src_path), str(additional_tgt_path))
  426. # Check/Validate the license file from the package, and copy over to install path
  427. if self.package_info.package_license_file:
  428. package_license_src = self.src_folder / self.package_info.package_license_file
  429. if not package_license_src.is_file():
  430. package_license_src = self.src_folder / os.path.basename(self.package_info.package_license_file)
  431. if not package_license_src.is_file():
  432. raise BuildError(f"Invalid/missing license file '{self.package_info.package_license_file}' specified in the build config.")
  433. license_file_content = package_license_src.read_text("UTF-8", "ignore")
  434. if "Copyright" not in license_file_content and "OPEN 3D ENGINE LICENSING" not in license_file_content and "copyright" not in license_file_content:
  435. raise BuildError(f"Unable to find 'Copyright' or the O3DE licensing text in the license file {str(self.package_info.package_license_file)}. Is this a valid license file?")
  436. target_license_copy = self.build_install_folder / os.path.basename(package_license_src)
  437. if target_license_copy.is_file():
  438. target_license_copy.unlink()
  439. shutil.copy2(str(package_license_src), str(target_license_copy))
  440. # Check if there is a patch to apply
  441. if self.package_info.patch_file:
  442. patch_file_path = self.base_folder / self.package_info.patch_file
  443. if not patch_file_path.is_file():
  444. raise BuildError(f"Invalid/missing patch file '{patch_file_path}' specified in the build config.")
  445. patch_cmd = ['git',
  446. 'apply',
  447. "--ignore-whitespace",
  448. str(patch_file_path.absolute())]
  449. patch_result = subprocess.run(subp_args(patch_cmd),
  450. shell=True,
  451. capture_output=True,
  452. cwd=str(self.src_folder.absolute()))
  453. if patch_result.returncode != 0:
  454. raise BuildError(f"Error Applying patch {str(patch_file_path.absolute())}: {patch_result.stderr.decode('UTF-8', 'ignore')}")
  455. # Check if there are any package dependencies.
  456. if self.package_info.depends_on_packages:
  457. for package_name, package_hash, _ in self.package_info.depends_on_packages:
  458. temp_packages_folder = self.base_temp_folder
  459. if not PackageDownloader.DownloadAndUnpackPackage(package_name, package_hash, str(temp_packages_folder)):
  460. raise BuildError(f"Failed to download a required dependency: {package_name}")
  461. def build_and_install_cmake(self):
  462. """
  463. Build and install to a local folder to prepare for packaging
  464. """
  465. is_multi_config = 'cmake_generate_args' in self.platform_config
  466. if not is_multi_config:
  467. if 'cmake_generate_args_debug' not in self.platform_config and 'cmake_generate_args_release' not in self.platform_config:
  468. raise BuildError("Invalid configuration")
  469. custom_cmake_install = self.platform_config.get('custom_cmake_install', False)
  470. # Check for the optional install filter
  471. cmake_install_filter = self.platform_config.get('cmake_install_filter', None)
  472. if cmake_install_filter:
  473. # If there is a custom install filter, then we need to install to another temp folder and copy over based on the filter rules
  474. install_target_folder = self.base_temp_folder / 'working_install'
  475. if not install_target_folder.is_dir():
  476. install_target_folder.mkdir(parents=True)
  477. else:
  478. # Otherwise install directly to the target
  479. install_target_folder = self.build_install_folder
  480. can_skip_generate = False
  481. for config in self.build_configs:
  482. if not can_skip_generate:
  483. cmake_generator_args = self.platform_config.get(f'cmake_generate_args_{config.lower()}')
  484. if not cmake_generator_args:
  485. cmake_generator_args = self.platform_config.get('cmake_generate_args')
  486. # Can skip generate the next time since there is only 1 unique cmake generation
  487. can_skip_generate = True
  488. # if there is a cmake_generate_args_common key in the build config, then start with that.
  489. if self.package_info.cmake_generate_args_common:
  490. cmake_generator_args = cmake_generator_args + self.package_info.cmake_generate_args_common
  491. validate_args(cmake_generator_args)
  492. cmakelists_folder = self.src_folder
  493. if self.package_info.cmake_src_subfolder:
  494. cmakelists_folder = cmakelists_folder / self.package_info.cmake_src_subfolder
  495. cmake_generate_cmd = [self.cmake_command,
  496. '-S', str(cmakelists_folder.absolute()),
  497. '-B', str(self.build_folder.name)]
  498. if self.custom_toolchain_file:
  499. cmake_generator_args.append( f'-DCMAKE_TOOLCHAIN_FILE="{self.custom_toolchain_file}"')
  500. cmake_module_path = ""
  501. paths_to_join = []
  502. if self.package_info.depends_on_packages:
  503. paths_to_join = []
  504. for package_name, package_hash, subfolder_name in self.package_info.depends_on_packages:
  505. package_download_location = self.base_temp_folder / package_name / subfolder_name
  506. paths_to_join.append(str(package_download_location.resolve()))
  507. cmake_module_path = ';'.join(paths_to_join).replace('\\', '/')
  508. if cmake_module_path:
  509. cmake_generate_cmd.extend([f"-DCMAKE_MODULE_PATH={cmake_module_path}"])
  510. cmake_generate_cmd.extend(cmake_generator_args)
  511. if custom_cmake_install:
  512. cmake_generate_cmd.extend([f"-DCMAKE_INSTALL_PREFIX={str(self.build_install_folder.resolve())}"])
  513. call_result = subprocess.run(subp_args(cmake_generate_cmd),
  514. shell=True,
  515. capture_output=False,
  516. cwd=str(self.build_folder.parent.resolve()))
  517. if call_result.returncode != 0:
  518. raise BuildError(f"Error generating project for platform {self.package_info.platform_name}")
  519. cmake_build_args = self.platform_config.get(f'cmake_build_args_{config.lower()}') or \
  520. self.platform_config.get('cmake_build_args') or \
  521. []
  522. if self.package_info.cmake_build_args_common:
  523. cmake_build_args = cmake_build_args + self.package_info.cmake_build_args_common
  524. validate_args(cmake_build_args)
  525. cmake_build_cmd = [self.cmake_command,
  526. '--build', str(self.build_folder.name),
  527. '--config', config]
  528. if custom_cmake_install:
  529. cmake_build_cmd.extend(['--target', 'install'])
  530. cmake_build_cmd.extend(cmake_build_args)
  531. call_result = subprocess.run(subp_args(cmake_build_cmd),
  532. shell=True,
  533. capture_output=False,
  534. cwd=str(self.build_folder.parent.resolve()))
  535. if call_result.returncode != 0:
  536. raise BuildError(f"Error building project for platform {self.package_info.platform_name}")
  537. if not custom_cmake_install:
  538. cmake_install_cmd = [self.cmake_command,
  539. '--install', str(self.build_folder.name),
  540. '--prefix', str(install_target_folder.resolve()),
  541. '--config', config]
  542. call_result = subprocess.run(subp_args(cmake_install_cmd),
  543. shell=True,
  544. capture_output=False,
  545. cwd=str(self.build_folder.parent.resolve()))
  546. if call_result.returncode != 0:
  547. raise BuildError(f"Error installing project for platform {self.package_info.platform_name}")
  548. if cmake_install_filter:
  549. # If an install filter was specified, then perform a copy from the intermediate temp install folder
  550. # to the target package folder, applying the filter rules defined in the 'cmake_install_filter'
  551. # attribute.
  552. source_root_folder = str(install_target_folder.resolve())
  553. glob_results = glob.glob(f'{source_root_folder}/**', recursive=True)
  554. for glob_result in glob_results:
  555. if os.path.isdir(glob_result):
  556. continue
  557. print(glob_result)
  558. source_relative = os.path.relpath(glob_result, source_root_folder)
  559. matched = False
  560. for pattern in cmake_install_filter:
  561. if fnmatch.fnmatch(source_relative, pattern):
  562. matched = True
  563. break
  564. if matched:
  565. target_path = self.build_install_folder / source_relative
  566. target_folder_path = target_path.parent
  567. if not target_folder_path.is_dir():
  568. target_folder_path.mkdir(parents=True)
  569. shutil.copy2(glob_result, str(target_folder_path.resolve()), follow_symlinks=False)
  570. def create_custom_env(self):
  571. custom_env = os.environ.copy()
  572. custom_env['TARGET_INSTALL_ROOT'] = str(self.build_install_folder.resolve())
  573. custom_env['PACKAGE_ROOT'] = str(self.package_install_root.resolve())
  574. custom_env['TEMP_FOLDER'] = str(self.base_temp_folder.resolve())
  575. custom_env['PYTHON_BINARY'] = sys.executable
  576. if self.package_info.depends_on_packages:
  577. package_folder_list = []
  578. for package_name, _, subfoldername in self.package_info.depends_on_packages:
  579. package_folder_list.append(str( (self.base_temp_folder / package_name / subfoldername).resolve().absolute()))
  580. custom_env['DOWNLOADED_PACKAGE_FOLDERS'] = ';'.join(package_folder_list)
  581. return custom_env
  582. def build_and_install_custom(self):
  583. """
  584. Build and install from source using custom commands defined by 'custom_build_cmd' and 'custom_install_cmd'
  585. """
  586. # we add TARGET_INSTALL_ROOT, TEMP_FOLDER and DOWNLOADED_PACKAGE_FOLDERS to the environ for both
  587. # build and install, as they are useful to refer to from scripts.
  588. env_to_use = self.create_custom_env()
  589. custom_build_cmds = self.platform_config.get('custom_build_cmd', [])
  590. for custom_build_cmd in custom_build_cmds:
  591. # Support the user specifying {python} in the custom_build_cmd to invoke
  592. # the Python executable that launched this build script
  593. call_result = subprocess.run(custom_build_cmd.format(python=sys.executable),
  594. shell=True,
  595. capture_output=False,
  596. cwd=str(self.base_folder),
  597. env=env_to_use)
  598. if call_result.returncode != 0:
  599. raise BuildError(f"Error executing custom build command {custom_build_cmd}")
  600. custom_install_cmds = self.platform_config.get('custom_install_cmd', [])
  601. for custom_install_cmd in custom_install_cmds:
  602. # Support the user specifying {python} in the custom_install_cmd to invoke
  603. # the Python executable that launched this build script
  604. call_result = subprocess.run(custom_install_cmd.format(python=sys.executable),
  605. shell=True,
  606. capture_output=False,
  607. cwd=str(self.base_folder),
  608. env=env_to_use)
  609. if call_result.returncode != 0:
  610. raise BuildError(f"Error executing custom install command {custom_install_cmd}")
  611. # Allow libraries to define a list of files to include via a json script that stores folder paths and
  612. # individual files in the "Install_Paths" array
  613. custom_install_jsons = self.platform_config.get('custom_install_json', [])
  614. for custom_install_json_file in custom_install_jsons:
  615. custom_json_full_path = os.path.join(self.base_folder, custom_install_json_file)
  616. print(f"Running custom install json file {custom_json_full_path}")
  617. custom_json_full_path_file = open(custom_json_full_path)
  618. custom_install_json = json.loads(custom_json_full_path_file.read())
  619. if not custom_install_json:
  620. raise BuildError(f"Error loading custom install json file {custom_install_json_file}")
  621. source_subfolder = None
  622. if "Source_Subfolder" in custom_install_json:
  623. source_subfolder = custom_install_json["Source_Subfolder"]
  624. for install_path in custom_install_json["Install_Paths"]:
  625. install_src_path = install_path
  626. if source_subfolder is not None:
  627. install_src_path = os.path.join(source_subfolder, install_src_path)
  628. resolved_src_path = os.path.join(env_to_use['TEMP_FOLDER'], install_src_path)
  629. resolved_target_path = os.path.join(env_to_use['TARGET_INSTALL_ROOT'], install_path)
  630. if os.path.isdir(resolved_src_path):
  631. # Newer versions of Python support the parameter dirs_exist_ok=True,
  632. # but that's not available in earlier Python versions.
  633. # It's useful to treat it as an error if the target exists, because that means that something has
  634. # already touched that folder and there might be unexpected behavior copying an entire tree into it.
  635. print(f" Copying directory '{resolved_src_path}' to '{resolved_target_path}'")
  636. shutil.copytree(resolved_src_path, resolved_target_path)
  637. elif os.path.isfile(resolved_src_path):
  638. print(f" Copying file '{resolved_src_path}' to '{resolved_target_path}'")
  639. os.makedirs(os.path.dirname(resolved_target_path), exist_ok=True)
  640. shutil.copy2(resolved_src_path, resolved_target_path)
  641. else:
  642. raise BuildError(f"Error executing custom install json {custom_install_json_file}, found invalid source path {resolved_src_path}")
  643. def check_build_keys(self, keys_to_check):
  644. """
  645. Check a platform configuration for specific build keys
  646. """
  647. config_specific_build_keys = []
  648. for config in self.build_configs:
  649. for build_key in keys_to_check:
  650. config_specific_build_keys.append(f'{build_key}_{config.lower()}')
  651. for platform_config_key in self.platform_config.keys():
  652. if platform_config_key in keys_to_check:
  653. return True
  654. elif platform_config_key in config_specific_build_keys:
  655. return True
  656. return False
  657. def build_for_platform(self):
  658. """
  659. Build for the current platform (host+target)
  660. """
  661. has_cmake_arguments = self.check_build_keys(['cmake_generate_args', 'cmake_build_args'])
  662. has_custom_arguments = self.check_build_keys(['custom_build_cmd', 'custom_install_cmd'])
  663. if has_cmake_arguments and has_custom_arguments:
  664. raise BuildError("Bad build config file. You cannot have both cmake_* and custom_* platform build commands at the same time.")
  665. if has_cmake_arguments:
  666. self.build_and_install_cmake()
  667. elif has_custom_arguments:
  668. self.build_and_install_custom()
  669. else:
  670. raise BuildError("Bad build config file. Missing generate and build commands (cmake or custom)")
  671. def generate_package_info(self):
  672. """
  673. Generate the package file (PackageInfo.json)
  674. """
  675. self.package_info.write_package_info(self.package_install_root)
  676. def generate_cmake(self):
  677. """
  678. Generate the find*.cmake file for the library
  679. """
  680. if self.cmake_find_template is not None:
  681. template_file_content = self.cmake_find_template.read_text("UTF-8", "ignore")
  682. def _build_list_str(indent, key):
  683. list_items = self.platform_config.get(key, [])
  684. indented_list_items = []
  685. for list_item in list_items:
  686. indented_list_items.append(f'{" "*(indent*4)}{list_item}')
  687. return '\n'.join(indented_list_items)
  688. cmake_find_template_def_ident_level = self.package_info.cmake_find_template_custom_indent
  689. template_env = {
  690. "CUSTOM_ADDITIONAL_COMPILE_DEFINITIONS": _build_list_str(cmake_find_template_def_ident_level, 'custom_additional_compile_definitions'),
  691. "CUSTOM_ADDITIONAL_LINK_OPTIONS": _build_list_str(cmake_find_template_def_ident_level, 'custom_additional_link_options'),
  692. "CUSTOM_ADDITIONAL_LIBRARIES": _build_list_str(cmake_find_template_def_ident_level, 'custom_additional_libraries')
  693. }
  694. find_cmake_content = string.Template(template_file_content).substitute(template_env)
  695. elif self.cmake_find_source is not None:
  696. find_cmake_content = self.cmake_find_source.read_text("UTF-8", "ignore")
  697. target_cmake_find_script = self.package_install_root / self.package_info.cmake_find_target
  698. target_cmake_find_script.write_text(find_cmake_content)
  699. def assemble_from_prebuilt_source(self):
  700. assert self.prebuilt_source
  701. assert self.prebuilt_args
  702. # Optionally clean the target package folder first
  703. if self.clean_build and self.package_install_root.is_dir():
  704. delete_folder(self.package_install_root)
  705. # Prepare the target package folder
  706. if not self.build_install_folder.is_dir():
  707. self.build_install_folder.mkdir(parents=True)
  708. prebuilt_source_path = (self.base_folder.resolve() / self.prebuilt_source).resolve()
  709. target_base_package_path = self.build_install_folder.resolve()
  710. # Loop through each of the prebuilt arguments (target/source glob pattern)
  711. for dest_path, glob_pattern in self.prebuilt_args.items():
  712. # Assemble the search pattern as a full path and keep track of the root of the search pattern so that
  713. # only the subpaths after the root of the search pattern will be copied to the target folder
  714. full_search_pattern = f"{str(prebuilt_source_path)}/{glob_pattern}"
  715. wildcard_index = full_search_pattern.find('*')
  716. source_base_folder_path = '' if wildcard_index < 0 else os.path.normpath(full_search_pattern[:wildcard_index])
  717. # Make sure the specified target folder exists
  718. target_base_folder_path = target_base_package_path / dest_path
  719. if not target_base_folder_path.is_dir():
  720. target_base_folder_path.mkdir(parents=True)
  721. total_copied = 0
  722. # For each search pattern, run a glob
  723. glob_results = glob.glob(full_search_pattern, recursive=True)
  724. for glob_result in glob_results:
  725. if os.path.isdir(glob_result):
  726. continue
  727. source_relative = os.path.relpath(glob_result, source_base_folder_path)
  728. target_path = target_base_folder_path / source_relative
  729. target_folder_path = target_path.parent
  730. if not target_folder_path.is_dir():
  731. target_folder_path.mkdir(parents=True)
  732. shutil.copy2(glob_result, str(target_folder_path.resolve()), follow_symlinks=False)
  733. total_copied += 1
  734. print(f"{total_copied} files copied to {target_base_folder_path}")
  735. pass
  736. def test_package(self):
  737. has_test_commands = self.check_build_keys(['custom_test_cmd'])
  738. if not has_test_commands:
  739. return
  740. custom_test_cmds= self.platform_config.get('custom_test_cmd', [])
  741. for custom_test_cmd in custom_test_cmds:
  742. call_result = subprocess.run(custom_test_cmd,
  743. shell=True,
  744. capture_output=False,
  745. cwd=str(self.base_folder),
  746. env=self.create_custom_env())
  747. if call_result.returncode != 0:
  748. raise BuildError(f"Error executing custom test command {custom_test_cmd}")
  749. def execute(self):
  750. """
  751. Perform all the steps to build a folder for the 3rd party library for packaging
  752. """
  753. # Prepare the temp folder structure
  754. if self.prebuilt_source:
  755. self.assemble_from_prebuilt_source()
  756. else:
  757. self.prepare_temp_folders()
  758. # Sync Source
  759. self.sync_source()
  760. # Build the package
  761. self.build_for_platform()
  762. # Generate the Find*.cmake file
  763. self.generate_cmake()
  764. self.test_package()
  765. # Generate the package info file
  766. self.generate_package_info()
  767. def prepare_build(platform_name, base_folder, build_folder, package_root_folder, cmake_command, toolchain_file, build_config_file,
  768. clean, src_folder, skip_git):
  769. """
  770. Prepare a Build manager object based on parameters provided (possibly from command line)
  771. :param platform_name: The name of the target platform that the package is being for
  772. :param base_folder: The base folder where the build_config exists
  773. :param build_folder: The root folder to build into
  774. :param package_root_folder: The root of the package folder where the new package will be assembled
  775. :param cmake_command: The cmake executable command to use for cmake
  776. :param toolchain_file: Option toolchain file to use for specific target platforms
  777. :param build_config_file: The build config file to open from the base_folder
  778. :param clean: Option to clean any existing build folder before proceeding
  779. :param src_folder: Option to manually specify the src folder
  780. :param skip_git: Option to skip all git commands, requires src_folder be supplied
  781. :return: The Build management object
  782. """
  783. base_folder_path = pathlib.Path(base_folder)
  784. build_folder_path = pathlib.Path(build_folder) if build_folder else base_folder_path / "temp"
  785. package_install_root = pathlib.Path(package_root_folder)
  786. src_folder_path = pathlib.Path(src_folder) if src_folder else build_folder_path / "src"
  787. if skip_git and src_folder is None:
  788. raise BuildError("Specified to skip git interactions but didn't supply a source code path")
  789. if src_folder is not None and not src_folder_path.is_dir():
  790. raise BuildError(f"Invalid path for 'git-path': {src_folder}")
  791. build_config_path = base_folder_path / build_config_file
  792. if not build_config_path.is_file():
  793. raise BuildError(f"Invalid build config path ({build_config_path.absolute()}). ")
  794. with build_config_path.open() as build_json_file:
  795. build_config = json.load(build_json_file)
  796. try:
  797. eligible_platforms = build_config["Platforms"][platform.system()]
  798. target_platform_config = eligible_platforms[platform_name]
  799. except KeyError as e:
  800. raise BuildError(f"Invalid build config : {str(e)}")
  801. # Check if this is a prebuilt package to validate any additional required arguments
  802. prebuilt_source = target_platform_config.get('prebuilt_source') or build_config.get('prebuilt_source')
  803. if prebuilt_source:
  804. prebuilt_path = base_folder_path / prebuilt_source
  805. if not prebuilt_path.is_dir():
  806. raise BuildError(f"Invalid path given for 'prebuilt_source': {prebuilt_source}")
  807. prebuilt_args = target_platform_config.get('prebuilt_args')
  808. if not prebuilt_args:
  809. raise BuildError(f"Missing required 'prebuilt_args' argument for platform {platform_name}")
  810. else:
  811. prebuilt_args = None
  812. package_info = PackageInfo(build_config=build_config,
  813. target_platform_name=platform_name,
  814. target_platform_config=target_platform_config)
  815. cmake_find_template_path = None
  816. cmake_find_source_path = None
  817. if package_info.cmake_find_template is not None:
  818. # Validate the cmake find template
  819. if os.path.isabs(package_info.cmake_find_template):
  820. raise BuildError("Invalid 'cmake_find_template' entry in build config. Absolute paths are not allowed, must be relative to the package base folder.")
  821. cmake_find_template_path = base_folder_path / package_info.cmake_find_template
  822. if not cmake_find_template_path.is_file():
  823. raise BuildError("Invalid 'cmake_find_template' entry in build config")
  824. elif package_info.cmake_find_source is not None:
  825. # Validate the cmake find source
  826. if os.path.isabs(package_info.cmake_find_source):
  827. raise BuildError("Invalid 'cmake_find_source' entry in build config. Absolute paths are not allowed, must be relative to the package base folder.")
  828. cmake_find_source_path = base_folder_path / package_info.cmake_find_source
  829. if not cmake_find_source_path.is_file():
  830. raise BuildError("Invalid 'cmake_find_source' entry in build config")
  831. else:
  832. raise BuildError("Bad build config file. 'cmake_find_template' or 'cmake_find_template' must be specified.")
  833. return BuildInfo(package_info=package_info,
  834. platform_config=target_platform_config,
  835. base_folder=base_folder_path,
  836. build_folder=build_folder_path,
  837. package_install_root=package_install_root,
  838. custom_toolchain_file=toolchain_file,
  839. cmake_command=cmake_command,
  840. clean_build=clean,
  841. cmake_find_template=cmake_find_template_path,
  842. cmake_find_source=cmake_find_source_path,
  843. prebuilt_source=prebuilt_source,
  844. prebuilt_args=prebuilt_args,
  845. src_folder=src_folder_path,
  846. skip_git=skip_git)
  847. if __name__ == '__main__':
  848. try:
  849. parser = argparse.ArgumentParser(description="Tool to prepare a 3rd Party Folder for packaging for an open source project pulled from Git.",
  850. formatter_class=argparse.RawDescriptionHelpFormatter,
  851. epilog=SCHEMA_DESCRIPTION)
  852. parser.add_argument('base_path',
  853. help='The base path where the build configuration exists')
  854. parser.add_argument('--platform-name',
  855. help='The platform to build the package for.',
  856. required=True)
  857. parser.add_argument('--package-root',
  858. help="The root path where to install the built packages to.",
  859. required=True)
  860. parser.add_argument('--cmake-path',
  861. help='Path to where cmake is installed. Defaults to the system installed one.',
  862. default='')
  863. parser.add_argument('--custom-toolchain-file',
  864. help=f'Path to a custom toolchain file if needed.',
  865. default=None)
  866. parser.add_argument('--build-config-file',
  867. help=f"Filename of the build config file within the base_path. Defaults to '{DEFAULT_BUILD_CONFIG_FILENAME}'.",
  868. default=DEFAULT_BUILD_CONFIG_FILENAME)
  869. parser.add_argument('--clean',
  870. help=f"Option to clean the build folder for a clean rebuild",
  871. action="store_true")
  872. parser.add_argument('--build-path',
  873. help="Path to build the repository in. Defaults to {base_path}/temp.")
  874. parser.add_argument('--source-path',
  875. help='Path to a folder. Can be used to specify the git sync folder or provide an existing folder with source for the library.',
  876. default=None)
  877. parser.add_argument('--git-skip',
  878. help='skips all git commands, requires source-path to be provided',
  879. default=False)
  880. parsed_args = parser.parse_args(sys.argv[1:])
  881. cmake_path = validate_cmake(f"{parsed_args.cmake_path}/cmake" if parsed_args.cmake_path else "cmake")
  882. if parsed_args.custom_toolchain_file:
  883. if os.path.isabs(parsed_args.custom_toolchain_file):
  884. custom_toolchain_file = parsed_args.custom_toolchain_file
  885. else:
  886. custom_toolchain_file = os.path.abspath(parsed_args.custom_toolchain_file)
  887. else:
  888. custom_toolchain_file = None
  889. # Prepare for the build
  890. build_info = prepare_build(platform_name=parsed_args.platform_name,
  891. base_folder=parsed_args.base_path,
  892. build_folder=parsed_args.build_path,
  893. package_root_folder=parsed_args.package_root,
  894. cmake_command=cmake_path,
  895. toolchain_file=custom_toolchain_file,
  896. build_config_file=parsed_args.build_config_file,
  897. clean=parsed_args.clean,
  898. src_folder=parsed_args.source_path,
  899. skip_git=parsed_args.git_skip)
  900. # Execute the generation of the 3P folder for packaging
  901. build_info.execute()
  902. exit(0)
  903. except BuildError as err:
  904. print(err)
  905. exit(1)