pull_and_build_from_git.py 59 KB

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