build-release.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. #!/usr/bin/env python
  2. import argparse
  3. import collections
  4. import contextlib
  5. import datetime
  6. import glob
  7. import io
  8. import json
  9. import logging
  10. import os
  11. from pathlib import Path
  12. import platform
  13. import re
  14. import shutil
  15. import subprocess
  16. import sys
  17. import tarfile
  18. import tempfile
  19. import textwrap
  20. import typing
  21. import zipfile
  22. logger = logging.getLogger(__name__)
  23. VcArchDevel = collections.namedtuple("VcArchDevel", ("dll", "imp", "test"))
  24. GIT_HASH_FILENAME = ".git-hash"
  25. ANDROID_AVAILABLE_ABIS = [
  26. "armeabi-v7a",
  27. "arm64-v8a",
  28. "x86",
  29. "x86_64",
  30. ]
  31. ANDROID_MINIMUM_API = 19
  32. ANDROID_TARGET_API = 29
  33. ANDROID_MINIMUM_NDK = 21
  34. ANDROID_LIBRARIES = [
  35. "dl",
  36. "GLESv1_CM",
  37. "GLESv2",
  38. "log",
  39. "android",
  40. "OpenSLES",
  41. ]
  42. def itertools_batched(iterator: typing.Iterable, count: int):
  43. iterator = iter(iterator)
  44. while True:
  45. items = []
  46. for _ in range(count):
  47. obj = next(iterator, None)
  48. if obj is None:
  49. yield tuple(items)
  50. return
  51. items.append(obj)
  52. yield tuple(items)
  53. class Executer:
  54. def __init__(self, root: Path, dry: bool=False):
  55. self.root = root
  56. self.dry = dry
  57. def run(self, cmd, stdout=False, dry_out=None, force=False):
  58. sys.stdout.flush()
  59. logger.info("Executing args=%r", cmd)
  60. if self.dry and not force:
  61. if stdout:
  62. return subprocess.run(["echo", "-E", dry_out or ""], stdout=subprocess.PIPE if stdout else None, text=True, check=True, cwd=self.root)
  63. else:
  64. return subprocess.run(cmd, stdout=subprocess.PIPE if stdout else None, text=True, check=True, cwd=self.root)
  65. class SectionPrinter:
  66. @contextlib.contextmanager
  67. def group(self, title: str):
  68. print(f"{title}:")
  69. yield
  70. class GitHubSectionPrinter(SectionPrinter):
  71. def __init__(self):
  72. super().__init__()
  73. self.in_group = False
  74. @contextlib.contextmanager
  75. def group(self, title: str):
  76. print(f"::group::{title}")
  77. assert not self.in_group, "Can enter a group only once"
  78. self.in_group = True
  79. yield
  80. self.in_group = False
  81. print("::endgroup::")
  82. class VisualStudio:
  83. def __init__(self, executer: Executer, year: typing.Optional[str]=None):
  84. self.executer = executer
  85. self.vsdevcmd = self.find_vsdevcmd(year)
  86. self.msbuild = self.find_msbuild()
  87. @property
  88. def dry(self):
  89. return self.executer.dry
  90. VS_YEAR_TO_VERSION = {
  91. "2022": 17,
  92. "2019": 16,
  93. "2017": 15,
  94. "2015": 14,
  95. "2013": 12,
  96. }
  97. def find_vsdevcmd(self, year: typing.Optional[str]=None) -> typing.Optional[Path]:
  98. vswhere_spec = ["-latest"]
  99. if year is not None:
  100. try:
  101. version = cls.VS_YEAR_TO_VERSION[year]
  102. except KeyError:
  103. logger.error("Invalid Visual Studio year")
  104. return None
  105. vswhere_spec.extend(["-version", f"[{version},{version+1})"])
  106. vswhere_cmd = ["vswhere"] + vswhere_spec + ["-property", "installationPath"]
  107. vs_install_path = Path(self.executer.run(vswhere_cmd, stdout=True, dry_out="/tmp").stdout.strip())
  108. logger.info("VS install_path = %s", vs_install_path)
  109. assert vs_install_path.is_dir(), "VS installation path does not exist"
  110. vsdevcmd_path = vs_install_path / "Common7/Tools/vsdevcmd.bat"
  111. logger.info("vsdevcmd path = %s", vsdevcmd_path)
  112. if self.dry:
  113. vsdevcmd_path.parent.mkdir(parents=True, exist_ok=True)
  114. vsdevcmd_path.touch(exist_ok=True)
  115. assert vsdevcmd_path.is_file(), "vsdevcmd.bat batch file does not exist"
  116. return vsdevcmd_path
  117. def find_msbuild(self) -> typing.Optional[Path]:
  118. vswhere_cmd = ["vswhere", "-latest", "-requires", "Microsoft.Component.MSBuild", "-find", "MSBuild\**\Bin\MSBuild.exe"]
  119. msbuild_path = Path(self.executer.run(vswhere_cmd, stdout=True, dry_out="/tmp/MSBuild.exe").stdout.strip())
  120. logger.info("MSBuild path = %s", msbuild_path)
  121. if self.dry:
  122. msbuild_path.parent.mkdir(parents=True, exist_ok=True)
  123. msbuild_path.touch(exist_ok=True)
  124. assert msbuild_path.is_file(), "MSBuild.exe does not exist"
  125. return msbuild_path
  126. def build(self, arch: str, platform: str, configuration: str, projects: list[Path]):
  127. assert projects, "Need at least one project to build"
  128. vsdev_cmd_str = f"\"{self.vsdevcmd}\" -arch={arch}"
  129. msbuild_cmd_str = " && ".join([f"\"{self.msbuild}\" \"{project}\" /m /p:BuildInParallel=true /p:Platform={platform} /p:Configuration={configuration}" for project in projects])
  130. bat_contents = f"{vsdev_cmd_str} && {msbuild_cmd_str}\n"
  131. bat_path = Path(tempfile.gettempdir()) / "cmd.bat"
  132. with bat_path.open("w") as f:
  133. f.write(bat_contents)
  134. logger.info("Running cmd.exe script (%s): %s", bat_path, bat_contents)
  135. cmd = ["cmd.exe", "/D", "/E:ON", "/V:OFF", "/S", "/C", f"CALL {str(bat_path)}"]
  136. self.executer.run(cmd)
  137. class Releaser:
  138. def __init__(self, project: str, commit: str, root: Path, dist_path: Path, section_printer: SectionPrinter, executer: Executer, cmake_generator: str):
  139. self.project = project
  140. self.version = self.extract_sdl_version(root=root, project=project)
  141. self.root = root
  142. self.commit = commit
  143. self.dist_path = dist_path
  144. self.section_printer = section_printer
  145. self.executer = executer
  146. self.cmake_generator = cmake_generator
  147. self.artifacts = {}
  148. @property
  149. def dry(self):
  150. return self.executer.dry
  151. def prepare(self):
  152. logger.debug("Creating dist folder")
  153. self.dist_path.mkdir(parents=True, exist_ok=True)
  154. GitLsTreeResult = collections.namedtuple("GitLsTreeResult", ("path", "mode", "object_type", "object_name"))
  155. def _git_ls_tree(self, commit) -> dict[str, GitLsTreeResult]:
  156. logger.debug("Getting source listing from git")
  157. dry_out = textwrap.dedent("""\
  158. "CMakeLists.txt": {"object_name": "9e5e4bcf094bfbde94f19c3f314808031ec8f141", "mode": "100644", "type": "blob"},
  159. """)
  160. last_key = "zzzzzz"
  161. dict_tree_items = "{" + self.executer.run(["git", "ls-tree", "-r", """--format="%(path)": {"object_name": "%(objectname)", "mode": "%(objectmode)", "type": "%(objecttype)"},""", commit], stdout=True, dry_out=dry_out).stdout + f'"{last_key}": null' + "}"
  162. with open("/tmp/a.txt", "w") as f:
  163. f.write(dict_tree_items)
  164. f.write("\n")
  165. dict_tree_items = json.loads(dict_tree_items)
  166. del dict_tree_items[last_key]
  167. tree_items = {path: self.GitLsTreeResult(path=path, mode=int(v["mode"], 8), object_type=v["type"], object_name=v["object_name"]) for path, v in dict_tree_items.items()}
  168. assert all(item.object_type == "blob" for item in tree_items.values())
  169. return tree_items
  170. def _git_cat_file(self, tree_items: dict[str, GitLsTreeResult]) -> dict[str, bytes]:
  171. logger.debug("Getting source binary data from git")
  172. if self.dry:
  173. return {
  174. "CMakeLists.txt": b"cmake_minimum_required(VERSION 3.20)\nproject(SDL)\n",
  175. }
  176. git_cat = subprocess.Popen(["git", "cat-file", "--batch"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=False, bufsize=50 * 1024 * 1024)
  177. data_tree = {}
  178. batch_size = 60
  179. for batch in itertools_batched(tree_items.items(), batch_size):
  180. for object_path, tree_item in batch:
  181. logger.debug("Requesting data of file '%s' (object=%s)...", object_path, tree_item.object_name)
  182. git_cat.stdin.write(f"{tree_item.object_name}\n".encode())
  183. git_cat.stdin.flush()
  184. for object_path, tree_item in batch:
  185. header = git_cat.stdout.readline().decode()
  186. object_name, object_type, obj_size = header.strip().split(maxsplit=3)
  187. assert tree_item.object_name == object_name
  188. assert tree_item.object_type == object_type
  189. obj_size = int(obj_size)
  190. data_tree[object_path] = git_cat.stdout.read(obj_size)
  191. logger.debug("File data received '%s'", object_path)
  192. assert git_cat.stdout.readline() == b"\n"
  193. assert len(data_tree) == len(tree_items)
  194. logger.debug("No more file!")
  195. git_cat.stdin.close()
  196. git_cat.wait()
  197. assert git_cat.returncode == 0
  198. logger.debug("All data received!")
  199. return data_tree
  200. def _get_file_times(self, tree_items: dict[str, GitLsTreeResult]) -> dict[str, datetime.datetime]:
  201. dry_out = textwrap.dedent("""\
  202. time=2024-03-14T15:40:25-07:00
  203. M\tCMakeLists.txt
  204. """)
  205. git_log_out = self.executer.run(["git", "log", "--name-status", '--pretty=time=%cI'], stdout=True, dry_out=dry_out).stdout.splitlines(keepends=False)
  206. current_time = None
  207. tree_paths = {item.path for item in tree_items.values()}
  208. path_times = {}
  209. for line in git_log_out:
  210. if not line:
  211. continue
  212. if line.startswith("time="):
  213. current_time = datetime.datetime.fromisoformat(line.removeprefix("time="))
  214. continue
  215. mod_type, paths = line.split(maxsplit=1)
  216. assert current_time is not None
  217. for path in paths.split():
  218. if path in tree_paths and path not in path_times:
  219. path_times[path] = current_time
  220. assert set(path_times.keys()) == tree_paths
  221. return path_times
  222. @staticmethod
  223. def _path_filter(path: str):
  224. if path.startswith(".git"):
  225. return False
  226. return True
  227. TreeItem = collections.namedtuple("TreeItem", ("path", "mode", "data", "time"))
  228. def _get_git_contents(self) -> dict[str, (TreeItem, bytes, datetime.datetime)]:
  229. commit_file_tree = self._git_ls_tree(self.commit)
  230. git_datas = self._git_cat_file(commit_file_tree)
  231. git_times = self._get_file_times(commit_file_tree)
  232. git_contents = {path: self.TreeItem(path=path, data=git_datas[path], mode=item.mode, time=git_times[path]) for path, item in commit_file_tree.items() if self._path_filter(path)}
  233. return git_contents
  234. def create_source_archives(self):
  235. archive_base = f"{self.project}-{self.version}"
  236. git_contents = self._get_git_contents()
  237. git_files = list(git_contents.values())
  238. assert len(git_contents) == len(git_files)
  239. latest_mod_time = max(item.time for item in git_files)
  240. git_files.append(self.TreeItem(path="VERSION.txt", data=f"{self.version}\n".encode(), mode=0o100644, time=latest_mod_time))
  241. git_files.append(self.TreeItem(path=GIT_HASH_FILENAME, data=f"{self.commit}\n".encode(), mode=0o100644, time=latest_mod_time))
  242. git_files.sort(key=lambda v: v.time)
  243. zip_path = self.dist_path / f"{archive_base}.zip"
  244. logger.info("Creating .zip source archive (%s)...", zip_path)
  245. if self.dry:
  246. zip_path.touch()
  247. else:
  248. with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zip_object:
  249. for git_file in git_files:
  250. file_data_time = (git_file.time.year, git_file.time.month, git_file.time.day, git_file.time.hour, git_file.time.minute, git_file.time.second)
  251. zip_info = zipfile.ZipInfo(filename=f"{archive_base}/{git_file.path}", date_time=file_data_time)
  252. zip_info.external_attr = git_file.mode << 16
  253. zip_info.compress_type = zipfile.ZIP_DEFLATED
  254. zip_object.writestr(zip_info, data=git_file.data)
  255. self.artifacts["src-zip"] = zip_path
  256. tar_types = (
  257. (".tar.gz", "gz"),
  258. (".tar.xz", "xz"),
  259. )
  260. for ext, comp in tar_types:
  261. tar_path = self.dist_path / f"{archive_base}{ext}"
  262. logger.info("Creating %s source archive (%s)...", ext, tar_path)
  263. if self.dry:
  264. tar_path.touch()
  265. else:
  266. with tarfile.open(tar_path, f"w:{comp}") as tar_object:
  267. for git_file in git_files:
  268. tar_info = tarfile.TarInfo(f"{archive_base}/{git_file.path}")
  269. tar_info.mode = git_file.mode
  270. tar_info.size = len(git_file.data)
  271. tar_info.mtime = git_file.time.timestamp()
  272. tar_object.addfile(tar_info, fileobj=io.BytesIO(git_file.data))
  273. if tar_path.suffix == ".gz":
  274. # Zero the embedded timestamp in the gzip'ed tarball
  275. with open(tar_path, "r+b") as f:
  276. f.seek(4, 0)
  277. f.write(b"\x00\x00\x00\x00")
  278. self.artifacts[f"src-tar-{comp}"] = tar_path
  279. def create_xcframework(self, configuration: str="Release"):
  280. dmg_in = self.root / f"Xcode/SDL/build/SDL3.dmg"
  281. dmg_in.unlink(missing_ok=True)
  282. self.executer.run(["xcodebuild", "-project", str(self.root / "Xcode/SDL/SDL.xcodeproj"), "-target", "SDL3.dmg", "-configuration", configuration])
  283. if self.dry:
  284. dmg_in.parent.mkdir(parents=True, exist_ok=True)
  285. dmg_in.touch()
  286. assert dmg_in.is_file(), "SDL3.dmg was not created by xcodebuild"
  287. dmg_out = self.dist_path / f"{self.project}-{self.version}.dmg"
  288. shutil.copy(dmg_in, dmg_out)
  289. self.artifacts["dmg"] = dmg_out
  290. @property
  291. def git_hash_data(self):
  292. return f"{self.commit}\n".encode()
  293. def _tar_add_git_hash(self, tar_object: tarfile.TarFile, root: typing.Optional[str]=None, time: typing.Optional[datetime.datetime]=None):
  294. if not time:
  295. time = datetime.datetime(year=2024, month=4, day=1)
  296. path = GIT_HASH_FILENAME
  297. if root:
  298. path = f"{root}/{path}"
  299. tar_info = tarfile.TarInfo(path)
  300. tar_info.mode = 0o100644
  301. tar_info.size = len(self.git_hash_data)
  302. tar_info.mtime = time.timestamp()
  303. tar_object.addfile(tar_info, fileobj=io.BytesIO(self.git_hash_data))
  304. def _zip_add_git_hash(self, zip_file: zipfile.ZipFile, root: typing.Optional[str]=None, time: typing.Optional[datetime.datetime]=None):
  305. if not time:
  306. time = datetime.datetime(year=2024, month=4, day=1)
  307. path = GIT_HASH_FILENAME
  308. if root:
  309. path = f"{root}/{path}"
  310. file_data_time = (time.year, time.month, time.day, time.hour, time.minute, time.second)
  311. zip_info = zipfile.ZipInfo(filename=path, date_time=file_data_time)
  312. zip_info.external_attr = 0o100644 << 16
  313. zip_info.compress_type = zipfile.ZIP_DEFLATED
  314. zip_file.writestr(zip_info, data=self.git_hash_data)
  315. def create_mingw_archives(self):
  316. build_type = "Release"
  317. mingw_archs = ("i686", "x86_64")
  318. build_parent_dir = self.root / "build-mingw"
  319. zip_path = self.dist_path / f"{self.project}-devel-{self.version}-mingw.zip"
  320. tar_exts = ("gz", "xz")
  321. tar_paths = { ext: self.dist_path / f"{self.project}-devel-{self.version}-mingw.tar.{ext}" for ext in tar_exts}
  322. arch_install_paths = {}
  323. arch_files = {}
  324. for arch in mingw_archs:
  325. build_path = build_parent_dir / f"build-{arch}"
  326. install_path = build_parent_dir / f"install-{arch}"
  327. arch_install_paths[arch] = install_path
  328. shutil.rmtree(install_path, ignore_errors=True)
  329. build_path.mkdir(parents=True, exist_ok=True)
  330. with self.section_printer.group(f"Configuring MinGW {arch}"):
  331. self.executer.run([
  332. "cmake", "-S", str(self.root), "-B", str(build_path),
  333. "--fresh",
  334. f'''-DCMAKE_C_FLAGS="-ffile-prefix-map={self.root}=/src/{self.project}"''',
  335. f'''-DCMAKE_CXX_FLAGS="-ffile-prefix-map={self.root}=/src/{self.project}"''',
  336. "-DSDL_SHARED=ON",
  337. "-DSDL_STATIC=ON",
  338. "-DSDL_DISABLE_INSTALL_DOCS=ON",
  339. "-DSDL_TEST_LIBRARY=ON",
  340. "-DSDL_TESTS=OFF",
  341. "-DCMAKE_INSTALL_BINDIR=bin",
  342. "-DCMAKE_INSTALL_DATAROOTDIR=share",
  343. "-DCMAKE_INSTALL_INCLUDEDIR=include",
  344. "-DCMAKE_INSTALL_LIBDIR=lib",
  345. f"-DCMAKE_BUILD_TYPE={build_type}",
  346. f"-DCMAKE_TOOLCHAIN_FILE={self.root}/build-scripts/cmake-toolchain-mingw64-{arch}.cmake",
  347. f"-G{self.cmake_generator}",
  348. f"-DCMAKE_INSTALL_PREFIX={install_path}",
  349. ])
  350. with self.section_printer.group(f"Build MinGW {arch}"):
  351. self.executer.run(["cmake", "--build", str(build_path), "--verbose", "--config", build_type])
  352. with self.section_printer.group(f"Install MinGW {arch}"):
  353. self.executer.run(["cmake", "--install", str(build_path), "--strip", "--config", build_type])
  354. arch_files[arch] = list(Path(r) / f for r, _, files in os.walk(install_path) for f in files)
  355. extra_files = [
  356. ("mingw/pkg-support/INSTALL.txt", ""),
  357. ("mingw/pkg-support/Makefile", ""),
  358. ("mingw/pkg-support/cmake/sdl3-config.cmake", "cmake/"),
  359. ("mingw/pkg-support/cmake/sdl3-config-version.cmake", "cmake/"),
  360. ("BUGS.txt", ""),
  361. ("CREDITS.md", ""),
  362. ("README-SDL.txt", ""),
  363. ("WhatsNew.txt", ""),
  364. ("LICENSE.txt", ""),
  365. ("README.md", ""),
  366. ]
  367. test_files = list(Path(r) / f for r, _, files in os.walk(self.root / "test") for f in files)
  368. # FIXME: split SDL3.dll debug information into debug library
  369. # objcopy --only-keep-debug SDL3.dll SDL3.debug.dll
  370. # objcopy --add-gnu-debuglink=SDL3.debug.dll SDL3.dll
  371. # objcopy --strip-debug SDL3.dll
  372. for comp in tar_exts:
  373. logger.info("Creating %s...", tar_paths[comp])
  374. with tarfile.open(tar_paths[comp], f"w:{comp}") as tar_object:
  375. arc_root = f"{self.project}-{self.version}"
  376. for file_path, arcdirname in extra_files:
  377. assert not arcdirname or arcdirname[-1] == "/"
  378. arcname = f"{arc_root}/{arcdirname}{Path(file_path).name}"
  379. tar_object.add(self.root / file_path, arcname=arcname)
  380. for arch in mingw_archs:
  381. install_path = arch_install_paths[arch]
  382. arcname_parent = f"{arc_root}/{arch}-w64-mingw32"
  383. for file in arch_files[arch]:
  384. arcname = os.path.join(arcname_parent, file.relative_to(install_path))
  385. tar_object.add(file, arcname=arcname)
  386. for test_file in test_files:
  387. arcname = f"{arc_root}/test/{test_file.relative_to(self.root/'test')}"
  388. tar_object.add(test_file, arcname=arcname)
  389. self._tar_add_git_hash(tar_object=tar_object, root=arc_root)
  390. self.artifacts[f"mingw-devel-tar-{comp}"] = tar_paths[comp]
  391. def build_vs(self, arch: str, platform: str, vs: VisualStudio, configuration: str="Release"):
  392. dll_path = self.root / f"VisualC/SDL/{platform}/{configuration}/{self.project}.dll"
  393. imp_path = self.root / f"VisualC/SDL/{platform}/{configuration}/{self.project}.lib"
  394. test_path = self.root / f"VisualC/SDL_test/{platform}/{configuration}/{self.project}_test.lib"
  395. dll_path.unlink(missing_ok=True)
  396. imp_path.unlink(missing_ok=True)
  397. test_path.unlink(missing_ok=True)
  398. projects = [
  399. self.root / "VisualC/SDL/SDL.vcxproj",
  400. self.root / "VisualC/SDL_test/SDL_test.vcxproj",
  401. ]
  402. vs.build(arch=arch, platform=platform, configuration=configuration, projects=projects)
  403. if self.dry:
  404. dll_path.parent.mkdir(parents=True, exist_ok=True)
  405. dll_path.touch()
  406. imp_path.touch()
  407. test_path.parent.mkdir(parents=True, exist_ok=True)
  408. test_path.touch()
  409. assert dll_path.is_file(), "SDL3.dll has not been created"
  410. assert imp_path.is_file(), "SDL3.lib has not been created"
  411. assert test_path.is_file(), "SDL3_test.lib has not been created"
  412. zip_path = self.dist_path / f"{self.project}-{self.version}-win32-{arch}.zip"
  413. zip_path.unlink(missing_ok=True)
  414. logger.info("Creating %s", zip_path)
  415. with zipfile.ZipFile(zip_path, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
  416. logger.debug("Adding %s", dll_path.name)
  417. zf.write(dll_path, arcname=dll_path.name)
  418. logger.debug("Adding %s", "README-SDL.txt")
  419. zf.write(self.root / "README-SDL.txt", arcname="README-SDL.txt")
  420. self._zip_add_git_hash(zip_file=zf)
  421. self.artifacts[f"VC-{arch}"] = zip_path
  422. return VcArchDevel(dll=dll_path, imp=imp_path, test=test_path)
  423. def build_vs_devel(self, arch_vc: dict[str, VcArchDevel]):
  424. zip_path = self.dist_path / f"{self.project}-devel-{self.version}-VC.zip"
  425. archive_prefix = f"{self.project}-{self.version}"
  426. def zip_file(zf: zipfile.ZipFile, path: Path, arcrelpath: str):
  427. arcname = f"{archive_prefix}/{arcrelpath}"
  428. logger.debug("Adding %s to %s", path, arcname)
  429. zf.write(path, arcname=arcname)
  430. def zip_directory(zf: zipfile.ZipFile, directory: Path, arcrelpath: str):
  431. for f in directory.iterdir():
  432. if f.is_file():
  433. arcname = f"{archive_prefix}/{arcrelpath}/{f.name}"
  434. logger.debug("Adding %s to %s", f, arcname)
  435. zf.write(f, arcname=arcname)
  436. with zipfile.ZipFile(zip_path, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
  437. for arch, binaries in arch_vc.items():
  438. zip_file(zf, path=binaries.dll, arcrelpath=f"lib/{arch}/{binaries.dll.name}")
  439. zip_file(zf, path=binaries.imp, arcrelpath=f"lib/{arch}/{binaries.imp.name}")
  440. zip_file(zf, path=binaries.test, arcrelpath=f"lib/{arch}/{binaries.test.name}")
  441. zip_directory(zf, directory=self.root / "include/SDL3", arcrelpath="include/SDL3")
  442. zip_directory(zf, directory=self.root / "docs", arcrelpath="docs")
  443. zip_directory(zf, directory=self.root / "VisualC/pkg-support/cmake", arcrelpath="cmake")
  444. for txt in ("BUGS.txt", "README-SDL.txt", "WhatsNew.txt"):
  445. zip_file(zf, path=self.root / txt, arcrelpath=txt)
  446. zip_file(zf, path=self.root / "LICENSE.txt", arcrelpath="COPYING.txt")
  447. zip_file(zf, path=self.root / "README.md", arcrelpath="README.txt")
  448. self._zip_add_git_hash(zip_file=zf, root=archive_prefix)
  449. self.artifacts["VC-devel"] = zip_path
  450. def detect_android_api(self, android_home: str) -> typing.Optional[int]:
  451. platform_dirs = list(Path(p) for p in glob.glob(f"{android_home}/platforms/android-*"))
  452. re_platform = re.compile("android-([0-9]+)")
  453. platform_versions = []
  454. for platform_dir in platform_dirs:
  455. logger.debug("Found Android Platform SDK: %s", platform_dir)
  456. if m:= re_platform.match(platform_dir.name):
  457. platform_versions.append(int(m.group(1)))
  458. platform_versions.sort()
  459. logger.info("Available platform versions: %s", platform_versions)
  460. platform_versions = list(filter(lambda v: v >= ANDROID_MINIMUM_API, platform_versions))
  461. logger.info("Valid platform versions (>=%d): %s", ANDROID_MINIMUM_API, platform_versions)
  462. if not platform_versions:
  463. return None
  464. android_api = platform_versions[0]
  465. logger.info("Selected API version %d", android_api)
  466. return android_api
  467. def get_prefab_json_text(self):
  468. return textwrap.dedent(f"""\
  469. {{
  470. "schema_version": 2,
  471. "name": "{self.project}",
  472. "version": "{self.version}",
  473. "dependencies": []
  474. }}
  475. """)
  476. def get_prefab_module_json_text(self, library_name: str, extra_libs: list[str]):
  477. export_libraries_str = ", ".join(f"\"-l{lib}\"" for lib in extra_libs)
  478. return textwrap.dedent(f"""\
  479. {{
  480. "export_libraries": [{export_libraries_str}],
  481. "library_name": "lib{library_name}"
  482. }}
  483. """)
  484. def get_prefab_abi_json_text(self, abi: str, cpp: bool, shared: bool):
  485. return textwrap.dedent(f"""\
  486. {{
  487. "abi": "{abi}",
  488. "api": {ANDROID_MINIMUM_API},
  489. "ndk": {ANDROID_MINIMUM_NDK},
  490. "stl": "{'c++_shared' if cpp else 'none'}",
  491. "static": {'true' if not shared else 'false'}
  492. }}
  493. """)
  494. def get_android_manifest_text(self):
  495. return textwrap.dedent(f"""\
  496. <manifest
  497. xmlns:android="http://schemas.android.com/apk/res/android"
  498. package="org.libsdl.android.{self.project}" android:versionCode="1"
  499. android:versionName="1.0">
  500. <uses-sdk android:minSdkVersion="{ANDROID_MINIMUM_API}"
  501. android:targetSdkVersion="{ANDROID_TARGET_API}" />
  502. </manifest>
  503. """)
  504. def create_android_archives(self, android_api: int, android_home: Path, android_ndk_home: Path, android_abis: list[str]):
  505. cmake_toolchain_file = Path(android_ndk_home) / "build/cmake/android.toolchain.cmake"
  506. if not cmake_toolchain_file.exists():
  507. logger.error("CMake toolchain file does not exist (%s)", cmake_toolchain_file)
  508. raise SystemExit(1)
  509. aar_path = self.dist_path / f"{self.project}-{self.version}.aar"
  510. added_global_files = False
  511. with zipfile.ZipFile(aar_path, "w", compression=zipfile.ZIP_DEFLATED) as zip_object:
  512. zip_object.writestr("AndroidManifest.xml", self.get_android_manifest_text())
  513. zip_object.write(self.root / "android-project/app/proguard-rules.pro", arcname="proguard.txt")
  514. zip_object.write(self.root / "LICENSE.txt", arcname="META-INF/LICENSE.txt")
  515. zip_object.writestr("prefab/prefab.json", self.get_prefab_json_text())
  516. self._zip_add_git_hash(zip_file=zip_object)
  517. for android_abi in android_abis:
  518. with self.section_printer.group(f"Building for Android {android_api} {android_abi}"):
  519. build_dir = self.root / "build-android" / f"{android_abi}-build"
  520. install_dir = self.root / "install-android" / f"{android_abi}-install"
  521. shutil.rmtree(install_dir, ignore_errors=True)
  522. assert not install_dir.is_dir(), f"{install_dir} should not exist prior to build"
  523. cmake_args = [
  524. "cmake",
  525. "-S", str(self.root),
  526. "-B", str(build_dir),
  527. "--fresh",
  528. f'''-DCMAKE_C_FLAGS="-ffile-prefix-map={self.root}=/src/{self.project}"''',
  529. f'''-DCMAKE_CXX_FLAGS="-ffile-prefix-map={self.root}=/src/{self.project}"''',
  530. "-DCMAKE_BUILD_TYPE=RelWithDebInfo",
  531. f"-DCMAKE_TOOLCHAIN_FILE={cmake_toolchain_file}",
  532. f"-DANDROID_PLATFORM={android_api}",
  533. f"-DANDROID_ABI={android_abi}",
  534. f"-DCMAKE_POSITION_INDEPENDENT_CODE=ON",
  535. "-DSDL_SHARED=ON",
  536. "-DSDL_STATIC=ON",
  537. "-DSDL_STATIC_PIC=ON",
  538. "-DSDL_TEST_LIBRARY=ON",
  539. "-DSDL_DISABLE_ANDROID_JAR=OFF",
  540. "-DSDL_TESTS=OFF",
  541. f"-DCMAKE_INSTALL_PREFIX={install_dir}",
  542. "-DSDL_DISABLE_INSTALL=OFF",
  543. "-DSDL_DISABLE_INSTALL_DOCS=OFF",
  544. "-DCMAKE_INSTALL_INCLUDEDIR=include ",
  545. "-DCMAKE_INSTALL_LIBDIR=lib",
  546. "-DCMAKE_INSTALL_DATAROOTDIR=share",
  547. "-DCMAKE_BUILD_TYPE=Release",
  548. f"-G{self.cmake_generator}",
  549. ]
  550. build_args = [
  551. "cmake",
  552. "--build", str(build_dir),
  553. "--config", "RelWithDebInfo",
  554. ]
  555. install_args = [
  556. "cmake",
  557. "--install", str(build_dir),
  558. "--config", "RelWithDebInfo",
  559. ]
  560. self.executer.run(cmake_args)
  561. self.executer.run(build_args)
  562. self.executer.run(install_args)
  563. main_so_library = install_dir / "lib" / f"lib{self.project}.so"
  564. logger.debug("Expecting library %s", main_so_library)
  565. assert main_so_library.is_file(), "CMake should have built a shared library (e.g. libSDL3.so)"
  566. main_static_library = install_dir / "lib" / f"lib{self.project}.a"
  567. logger.debug("Expecting library %s", main_static_library)
  568. assert main_static_library.is_file(), "CMake should have built a static library (e.g. libSDL3.a)"
  569. test_library = install_dir / "lib" / f"lib{self.project}_test.a"
  570. logger.debug("Expecting library %s", test_library)
  571. assert test_library.is_file(), "CMake should have built a static test library (e.g. libSDL3_test.a)"
  572. java_jar = install_dir / f"share/java/{self.project}/{self.project}-{self.version}.jar"
  573. logger.debug("Expecting java archive: %s", java_jar)
  574. assert java_jar.is_file(), "CMake should have compiled the java sources and archived them into a JAR"
  575. javasources_jar = install_dir / f"share/java/{self.project}/{self.project}-{self.version}-sources.jar"
  576. logger.debug("Expecting java sources archive %s", javasources_jar)
  577. assert javasources_jar.is_file(), "CMake should have archived the java sources into a JAR"
  578. javadoc_dir = install_dir / "share/javadoc" / self.project
  579. logger.debug("Expecting javadoc archive %s", javadoc_dir)
  580. assert javadoc_dir.is_dir(), "CMake should have built javadoc documentation for the java sources"
  581. if not added_global_files:
  582. zip_object.write(java_jar, arcname="classes.jar")
  583. zip_object.write(javasources_jar, arcname="classes-sources.jar", )
  584. doc_jar_path = install_dir / "classes-doc.jar"
  585. javadoc_jar_args = ["jar", "--create", "--file", str(doc_jar_path)]
  586. for fn in javadoc_dir.iterdir():
  587. javadoc_jar_args.extend(["-C", str(javadoc_dir), fn.name])
  588. self.executer.run(javadoc_jar_args)
  589. zip_object.write(doc_jar_path, arcname="classes-doc.jar")
  590. for header in (install_dir / "include" / self.project).iterdir():
  591. zip_object.write(header, arcname=f"prefab/modules/{self.project}-shared/include/{self.project}/{header.name}")
  592. zip_object.write(header, arcname=f"prefab/modules/{self.project}-static/include/{self.project}/{header.name}")
  593. zip_object.writestr(f"prefab/modules/{self.project}-shared/module.json", self.get_prefab_module_json_text(library_name=self.project, extra_libs=[]))
  594. zip_object.writestr(f"prefab/modules/{self.project}-static/module.json", self.get_prefab_module_json_text(library_name=self.project, extra_libs=list(ANDROID_LIBRARIES)))
  595. zip_object.writestr(f"prefab/modules/{self.project}_test/module.json", self.get_prefab_module_json_text(library_name=f"{self.project}_test", extra_libs=list()))
  596. added_global_files = True
  597. zip_object.write(main_so_library, arcname=f"prefab/modules/{self.project}-shared/libs/android.{android_abi}/lib{self.project}.so")
  598. zip_object.writestr(f"prefab/modules/{self.project}-shared/libs/android.{android_abi}/abi.json", self.get_prefab_abi_json_text(abi=android_abi, cpp=False, shared=True))
  599. zip_object.write(main_static_library, arcname=f"prefab/modules/{self.project}-static/libs/android.{android_abi}/lib{self.project}.a")
  600. zip_object.writestr(f"prefab/modules/{self.project}-static/libs/android.{android_abi}/abi.json", self.get_prefab_abi_json_text(abi=android_abi, cpp=False, shared=False))
  601. zip_object.write(test_library, arcname=f"prefab/modules/{self.project}_test/libs/android.{android_abi}/lib{self.project}_test.a")
  602. zip_object.writestr(f"prefab/modules/{self.project}_test/libs/android.{android_abi}/abi.json", self.get_prefab_abi_json_text(abi=android_abi, cpp=False, shared=False))
  603. self.artifacts[f"android-prefab-aar"] = aar_path
  604. @classmethod
  605. def extract_sdl_version(cls, root: Path, project: str):
  606. with open(root / f"include/{project}/SDL_version.h", "r") as f:
  607. text = f.read()
  608. major = next(re.finditer(r"^#define SDL_MAJOR_VERSION\s+([0-9]+)$", text, flags=re.M)).group(1)
  609. minor = next(re.finditer(r"^#define SDL_MINOR_VERSION\s+([0-9]+)$", text, flags=re.M)).group(1)
  610. micro = next(re.finditer(r"^#define SDL_MICRO_VERSION\s+([0-9]+)$", text, flags=re.M)).group(1)
  611. return f"{major}.{minor}.{micro}"
  612. def main(argv=None):
  613. parser = argparse.ArgumentParser(allow_abbrev=False, description="Create SDL release artifacts")
  614. parser.add_argument("--root", metavar="DIR", type=Path, default=Path(__file__).absolute().parents[1], help="Root of SDL")
  615. parser.add_argument("--out", "-o", metavar="DIR", dest="dist_path", type=Path, default="dist", help="Output directory")
  616. parser.add_argument("--github", action="store_true", help="Script is running on a GitHub runner")
  617. parser.add_argument("--commit", default="HEAD", help="Git commit/tag of which a release should be created")
  618. parser.add_argument("--project", required=True, help="Name of the project (e.g. SDL3")
  619. parser.add_argument("--create", choices=["source", "mingw", "win32", "xcframework", "android"], required=True, action="append", dest="actions", help="What to do")
  620. parser.set_defaults(loglevel=logging.INFO)
  621. parser.add_argument('--vs-year', dest="vs_year", help="Visual Studio year")
  622. parser.add_argument('--android-api', type=int, dest="android_api", help="Android API version")
  623. parser.add_argument('--android-home', dest="android_home", default=os.environ.get("ANDROID_HOME"), help="Android Home folder")
  624. parser.add_argument('--android-ndk-home', dest="android_ndk_home", default=os.environ.get("ANDROID_NDK_HOME"), help="Android NDK Home folder")
  625. parser.add_argument('--android-abis', dest="android_abis", nargs="*", choices=ANDROID_AVAILABLE_ABIS, default=list(ANDROID_AVAILABLE_ABIS), help="Android NDK Home folder")
  626. parser.add_argument('--cmake-generator', dest="cmake_generator", default="Ninja", help="CMake Generator")
  627. parser.add_argument('--debug', action='store_const', const=logging.DEBUG, dest="loglevel", help="Print script debug information")
  628. parser.add_argument('--dry-run', action='store_true', dest="dry", help="Don't execute anything")
  629. parser.add_argument('--force', action='store_true', dest="force", help="Ignore a non-clean git tree")
  630. args = parser.parse_args(argv)
  631. logging.basicConfig(level=args.loglevel, format='[%(levelname)s] %(message)s')
  632. args.actions = set(args.actions)
  633. args.dist_path = args.dist_path.absolute()
  634. args.root = args.root.absolute()
  635. args.dist_path = args.dist_path.absolute()
  636. if args.dry:
  637. args.dist_path = args.dist_path / "dry"
  638. if args.github:
  639. section_printer = GitHubSectionPrinter()
  640. else:
  641. section_printer = SectionPrinter()
  642. executer = Executer(root=args.root, dry=args.dry)
  643. root_git_hash_path = args.root / GIT_HASH_FILENAME
  644. root_is_maybe_archive = root_git_hash_path.is_file()
  645. if root_is_maybe_archive:
  646. logger.warning("%s detected: Building from archive", GIT_HASH_FILENAME)
  647. archive_commit = root_git_hash_path.read_text().strip()
  648. if args.commit != archive_commit:
  649. logger.warn("Commit argument is %s, but archive commit is %s. Using %s.", args.commit, archive_commit, archive_commit)
  650. args.commit = archive_commit
  651. else:
  652. args.commit = executer.run(["git", "rev-parse", args.commit], stdout=True, dry_out="e5812a9fd2cda317b503325a702ba3c1c37861d9").stdout.strip()
  653. logger.info("Using commit %s", args.commit)
  654. releaser = Releaser(
  655. project=args.project,
  656. commit=args.commit,
  657. root=args.root,
  658. dist_path=args.dist_path,
  659. executer=executer,
  660. section_printer=section_printer,
  661. cmake_generator=args.cmake_generator,
  662. )
  663. if root_is_maybe_archive:
  664. logger.warn("Building from archive. Skipping clean git tree check.")
  665. else:
  666. porcelain_status = executer.run(["git", "status", "--ignored", "--porcelain"], stdout=True, dry_out="\n").stdout.strip()
  667. if porcelain_status:
  668. print(porcelain_status)
  669. logger.warning("The tree is dirty! Do not publish any generated artifacts!")
  670. if not args.force:
  671. raise Exception("The git repo contains modified and/or non-committed files. Run with --force to ignore.")
  672. with section_printer.group("Arguments"):
  673. print(f"project = {args.project}")
  674. print(f"version = {releaser.version}")
  675. print(f"commit = {args.commit}")
  676. print(f"out = {args.dist_path}")
  677. print(f"actions = {args.actions}")
  678. print(f"dry = {args.dry}")
  679. print(f"force = {args.force}")
  680. print(f"cmake_generator = {args.cmake_generator}")
  681. releaser.prepare()
  682. if "source" in args.actions:
  683. if root_is_maybe_archive:
  684. raise Exception("Cannot build source archive from source archive")
  685. with section_printer.group("Create source archives"):
  686. releaser.create_source_archives()
  687. if "xcframework" in args.actions:
  688. if platform.system() != "Darwin" and not args.dry:
  689. parser.error("xcframework artifact(s) can only be built on Darwin")
  690. releaser.create_xcframework()
  691. if "win32" in args.actions:
  692. if platform.system() != "Windows" and not args.dry:
  693. parser.error("win32 artifact(s) can only be built on Windows")
  694. with section_printer.group("Find Visual Studio"):
  695. vs = VisualStudio(executer=executer)
  696. with section_printer.group("Build x86 VS binary"):
  697. x86 = releaser.build_vs(arch="x86", platform="Win32", vs=vs)
  698. with section_printer.group("Build x64 VS binary"):
  699. x64 = releaser.build_vs(arch="x64", platform="x64", vs=vs)
  700. with section_printer.group("Create SDL VC development zip"):
  701. arch_vc = {
  702. "x86": x86,
  703. "x64": x64,
  704. }
  705. releaser.build_vs_devel(arch_vc)
  706. if "mingw" in args.actions:
  707. releaser.create_mingw_archives()
  708. if "android" in args.actions:
  709. if args.android_home is None or not Path(args.android_home).is_dir():
  710. parser.error("Invalid $ANDROID_HOME or --android-home: must be a directory containing the Android SDK")
  711. if args.android_ndk_home is None or not Path(args.android_ndk_home).is_dir():
  712. parser.error("Invalid $ANDROID_NDK_HOME or --android_ndk_home: must be a directory containing the Android NDK")
  713. if args.android_api is None:
  714. with section_printer.group("Detect Android APIS"):
  715. args.android_api = releaser.detect_android_api(android_home=args.android_home)
  716. if args.android_api is None or not (Path(args.android_home) / f"platforms/android-{args.android_api}").is_dir():
  717. parser.error("Invalid --android-api, and/or could not be detected")
  718. if not args.android_abis:
  719. parser.error("Need at least one Android ABI")
  720. with section_printer.group("Android arguments"):
  721. print(f"android_home = {args.android_home}")
  722. print(f"android_ndk_home = {args.android_ndk_home}")
  723. print(f"android_api = {args.android_api}")
  724. print(f"android_abis = {args.android_abis}")
  725. releaser.create_android_archives(
  726. android_api=args.android_api,
  727. android_home=args.android_home,
  728. android_ndk_home=args.android_ndk_home,
  729. android_abis=args.android_abis,
  730. )
  731. with section_printer.group("Summary"):
  732. print(f"artifacts = {releaser.artifacts}")
  733. if args.github:
  734. if args.dry:
  735. os.environ["GITHUB_OUTPUT"] = "/tmp/github_output.txt"
  736. with open(os.environ["GITHUB_OUTPUT"], "a") as f:
  737. f.write(f"project={releaser.project}\n")
  738. f.write(f"version={releaser.version}\n")
  739. for k, v in releaser.artifacts.items():
  740. f.write(f"{k}={v.name}\n")
  741. return 0
  742. if __name__ == "__main__":
  743. raise SystemExit(main())