build-release.py 38 KB

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