Debian Codegraph @

ci/deploy.py

raw
1 #!/usr/bin/env python3
2
3 """
4 steps for deploying a new release (see ../.gitlab-ci.yml)
5
6 This is based on Gitlab’s generic package example,
7 https://gitlab.com/gitlab-org/release-cli/-/tree/master/docs/examples/release-assets-as-generic-package
8 """
9
10 import hashlib
11 import json
12 import logging
13 import os
14 import re
15 import shutil
16 import stat
17 import subprocess
18 import sys
19 from pathlib import Path
20
21 # logging output stream, setup in main()
22 log = None
23
24
25 def upload(dry_run: bool, version: str, path: Path) -> str:
26 """
27 upload a file to the Graphviz generic package with the given version
28 """
29
30 name = path.name
31
32 # Gitlab upload file_name field only allows letters, numbers, dot, dash, and
33 # underscore
34 safe = re.sub(r"[^a-zA-Z0-9.\-]", "_", name)
35 log.info(f"escaped name {name} to {safe}")
36
37 target = (
38 f'{os.environ["CI_API_V4_URL"]}/projects/'
39 f'{os.environ["CI_PROJECT_ID"]}/packages/generic/graphviz-releases/'
40 f"{version}/{safe}"
41 )
42
43 if dry_run:
44 log.info("skipping upload due to 'dry_run' flag")
45 return target
46
47 log.info(f"uploading {path} to {target}")
48 # calling Curl is not the cleanest way to achieve this, but Curl takes care of
49 # encodings, headers and part splitting for us
50 proc = subprocess.run(
51 [
52 "curl",
53 "--silent", # no progress bar
54 "--include", # include HTTP response headers in output
55 "--verbose", # more connection details
56 "--retry",
57 "3", # retry on transient errors
58 "--header",
59 f'JOB-TOKEN: {os.environ["CI_JOB_TOKEN"]}',
60 "--upload-file",
61 path,
62 target,
63 ],
64 stdout=subprocess.PIPE,
65 stderr=subprocess.STDOUT,
66 check=False,
67 text=True,
68 )
69 log.info("Curl response:")
70 for i, line in enumerate(proc.stdout.split("\n"), 1):
71 log.info(f" {i:3}: {line}")
72 proc.check_returncode()
73
74 resp = proc.stdout.split("\n")[-1]
75 if json.loads(resp)["message"] != "201 Created":
76 raise RuntimeError(f"upload failed: {resp}")
77
78 return target
79
80
81 def checksum(path: Path) -> Path:
82 """generate checksum for the given file"""
83
84 assert path.exists()
85
86 log.info(f"SHA256 summing {path}")
87 check = Path(f"{path}.sha256")
88 data = path.read_bytes()
89 check.write_text(f"{hashlib.sha256(data).hexdigest()} {path}\n", encoding="utf-8")
90 return check
91
92
93 def is_macos_artifact(name: str) -> bool:
94 """is this a deployment artifact for macOS?"""
95 return re.search(r"\bDarwin\b", name) is not None
96
97
98 def is_windows_artifact(name: str) -> bool:
99 """is this a deployment artifact for Windows?"""
100 return re.search(r"\bwindows\b", name) is not None
101
102
103 def get_format(path: Path) -> str:
104 """a human readable description of the format of this file"""
105 if path.suffix[1:].lower() == "exe":
106 return "EXE installer"
107 if path.suffix[1:].lower() == "zip":
108 return "ZIP archive"
109 if ".tar." in str(path):
110 return "".join(path.suffixes[-2:])[1:].lower()
111 return path.suffix[1:].lower()
112
113
114 def main() -> int:
115 """entry point"""
116
117 # setup logging to print to stderr
118 global log
119 ch = logging.StreamHandler()
120 log = logging.getLogger("deploy.py")
121 log.addHandler(ch)
122 log.setLevel(logging.INFO)
123
124 if os.environ.get("CI") is None:
125 log.error("CI environment variable unset; refusing to run")
126 return -1
127
128 # echo some useful things for debugging
129 log.info(f"os.uname(): {os.uname()}")
130 if Path("/etc/os-release").exists():
131 with open("/etc/os-release", "rt", encoding="utf-8") as f:
132 log.info("/etc/os-release:")
133 for i, line in enumerate(f, 1):
134 log.info(f" {i}: {line[:-1]}")
135
136 # bail out early if we do not have release-cli to avoid uploading assets that
137 # become orphaned when we fail to create the release
138 if not shutil.which("release-cli"):
139 log.error("release-cli not found")
140 return -1
141
142 # retrieve version name left by prior CI tasks
143 log.info("deriving Graphviz version")
144 root = Path(__file__).resolve().parents[1]
145 version = subprocess.check_output(
146 [sys.executable, "gen_version.py"], cwd=root, text=True
147 ).strip()
148 log.info(f"Graphviz version == {version}")
149
150 # the generic package version has to be \d+.\d+.\d+ but it does not need to
151 # correspond to the release version (which may not conform to this pattern if
152 # this is a dev release)
153 if re.match(r"\d+\.\d+\.\d+$", version) is None:
154 # generate a compliant version
155 package_version = f'0.0.{int(os.environ["CI_COMMIT_SHA"], 16)}'
156 else:
157 # we can use a version corresponding to the release version
158 package_version = version
159 log.info(f"using generic package version {package_version}")
160
161 # we only create Gitlab releases for stable version numbers
162 skip_release = re.match(r"\d+\.\d+\.\d+$", version) is None
163
164 # list of assets we have uploaded
165 assets: list[str] = []
166
167 # 0-pad major version to 2 digits, to sort versions properly
168 vparts = version.split(".")
169 assert len(vparts) > 0, "Malformed version string"
170 vparts[0] = f"{int(vparts[0]):02d}"
171
172 # data for the website’s download page
173 webdata = {
174 "name": f"graphviz-{version}",
175 "version": ".".join(vparts),
176 "sources": [],
177 "windows": [],
178 }
179
180 for tarball in (
181 Path(f"graphviz-{version}.tar.gz"),
182 Path(f"graphviz-{version}.tar.xz"),
183 ):
184 if not tarball.exists():
185 log.error(f"source {tarball} not found")
186 return -1
187
188 # accrue the source tarball and accompanying checksum
189 url = upload(skip_release, package_version, tarball)
190 assets.append(url)
191 webentry = {"format": get_format(tarball), "url": url}
192 check = checksum(tarball)
193 url = upload(skip_release, package_version, check)
194 assets.append(url)
195 webentry[check.suffix[1:]] = url
196
197 webdata["sources"].append(webentry)
198
199 # exported artifacts to be included in the release
200 ARTIFACTS = {
201 # CI job → [artifacts…]
202 "fedora41-build": [f"fedora_41_graphviz-{version}-rpms.tar.xz"],
203 "fedora42-build": [f"fedora_42_graphviz-{version}-rpms.tar.xz"],
204 "fedora43-build": [f"fedora_43_graphviz-{version}-rpms.tar.xz"],
205 "rocky8-build": [f"rocky_8.9_graphviz-{version}-rpms.tar.xz"],
206 "rocky9-build": [f"rocky_9.3_graphviz-{version}-rpms.tar.xz"],
207 "fedora41-cmake-build": [f"fedora_41_graphviz-{version}-cmake.rpm"],
208 "fedora42-cmake-build": [f"fedora_42_graphviz-{version}-cmake.rpm"],
209 "fedora43-cmake-build": [f"fedora_43_graphviz-{version}-cmake.rpm"],
210 "rocky8-cmake-build": [f"rocky_8.9_graphviz-{version}-cmake.rpm"],
211 "rocky9-cmake-build": [f"rocky_9.3_graphviz-{version}-cmake.rpm"],
212 "ubuntu-22.04-build": [f"ubuntu_22.04_graphviz-{version}-debs.tar.xz"],
213 "ubuntu-24.04-build": [f"ubuntu_24.04_graphviz-{version}-debs.tar.xz"],
214 "ubuntu-25.04-build": [f"ubuntu_25.04_graphviz-{version}-debs.tar.xz"],
215 "ubuntu-25.10-build": [f"ubuntu_25.10_graphviz-{version}-debs.tar.xz"],
216 "ubuntu-22.04-cmake-build": [f"ubuntu_22.04_graphviz-{version}-cmake.deb"],
217 "ubuntu-24.04-cmake-build": [f"ubuntu_24.04_graphviz-{version}-cmake.deb"],
218 "ubuntu-25.04-cmake-build": [f"ubuntu_25.04_graphviz-{version}-cmake.deb"],
219 "ubuntu-25.10-cmake-build": [f"ubuntu_25.10_graphviz-{version}-cmake.deb"],
220 "macos-autotools-build": [f"Darwin_23.6.0_graphviz-{version}-arm64.pkg"],
221 "macos-cmake-build": [f"Darwin_23.6.0_Graphviz-{version}-Darwin.zip"],
222 "windows-cmake-Win32-release-build": [
223 f"windows_10_cmake_Release_graphviz-install-{version}-win32.exe",
224 f"windows_10_cmake_Release_Graphviz-{version}-win32.zip",
225 ],
226 "windows-cmake-Win32-debug-build": [
227 f"windows_10_cmake_Debug_graphviz-install-{version}-win32.exe",
228 f"windows_10_cmake_Debug_Graphviz-{version}-win32.zip",
229 ],
230 "windows-cmake-x64-release-build": [
231 f"windows_10_cmake_Release_graphviz-install-{version}-win64.exe",
232 f"windows_10_cmake_Release_Graphviz-{version}-win64.zip",
233 ],
234 "windows-cmake-x64-debug-build": [
235 f"windows_10_cmake_Debug_graphviz-install-{version}-win64.exe",
236 f"windows_10_cmake_Debug_Graphviz-{version}-win64.zip",
237 ],
238 "windows-mingw64-cmake-build": [
239 f"msys2_*_Graphviz-{version}-win64.exe",
240 f"msys2_*_Graphviz-{version}-win64.zip",
241 ],
242 "windows-cygwin-build": [f"CYGWIN_*_graphviz-{version}-x86_64.tar.xz"],
243 "windows-cygwin-cmake-build": [f"CYGWIN_*_Graphviz-{version}-CYGWIN-1.tar.bz2"],
244 }
245
246 for job, artifacts in ARTIFACTS.items():
247 for artifact in artifacts:
248 paths = list((Path("Packages") / job).glob(artifact))
249 assert len(paths) != 0, f"missing artifact: {artifact}"
250 assert len(paths) == 1, f"multiple matches for {artifact}: {paths}"
251 path = paths[0]
252
253 # get existing permissions
254 mode = path.stat().st_mode
255
256 # fixup permissions, o-rwx g-wx
257 path.chmod(mode & ~stat.S_IRWXO & ~stat.S_IWGRP & ~stat.S_IXGRP)
258
259 url = upload(skip_release, package_version, path)
260 assets.append(url)
261
262 webentry = {
263 "format": get_format(path),
264 "url": url,
265 }
266 if "win32" in artifact:
267 webentry["bits"] = 32
268 elif "win64" in artifact:
269 webentry["bits"] = 64
270
271 # if this is a standalone Windows or macOS package, also provide checksum(s)
272 if is_macos_artifact(artifact) or is_windows_artifact(artifact):
273 c = checksum(path)
274 url = upload(skip_release, package_version, c)
275 assets.append(url)
276 webentry[c.suffix[1:]] = url
277
278 # only expose a subset of the Windows artifacts
279 if "windows_10_cmake_Release_" in artifact:
280 webdata["windows"].append(webentry)
281
282 # various release pages truncate the viewable artifacts to 100 or even 50
283 if len(assets) > 50:
284 log.error(
285 f"upload has {len(assets)} assets, which will result in some of "
286 f"them being unviewable in web page lists: {assets}"
287 )
288 return -1
289
290 assert len(webdata["windows"]) > 0, "no Windows artifacts found"
291
292 if skip_release:
293 log.warning(
294 f"skipping release creation because {version} is not "
295 "of the form \\d+.\\d+.\\d+"
296 )
297 return 0
298
299 # construct a command to create the release itself
300 cmd = [
301 "release-cli",
302 "create",
303 "--name",
304 version,
305 "--tag-name",
306 version,
307 "--description",
308 "See the [CHANGELOG](https://gitlab.com/"
309 "graphviz/graphviz/-/blob/main/CHANGELOG.md).",
310 ]
311 for a in assets:
312 name = os.path.basename(a)
313 url = a
314 cmd += ["--assets-link", json.dumps({"name": name, "url": url})]
315
316 # create the release
317 subprocess.check_call(cmd)
318
319 # output JSON data for the website
320 log.info(f"dumping {webdata} to graphviz-{version}.json")
321 with open(f"graphviz-{version}.json", "wt", encoding="utf-8") as f:
322 json.dump(webdata, f, indent=2)
323
324 return 0
325
326
327 if __name__ == "__main__":
328 sys.exit(main())