pull_and_build_from_git.py 62 KB

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