pull_and_build_from_git.py 52 KB

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