pull_and_build_from_git.py 66 KB

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