pull_and_build_from_git.py 66 KB

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