Debian Codegraph @

setup/unix-ci.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
3
4
5 import glob
6 import io
7 import lzma
8 import os
9 import shlex
10 import subprocess
11 import sys
12 import tarfile
13 import time
14 from tempfile import NamedTemporaryFile
15 from urllib.request import Request, urlopen
16
17 _plat = sys.platform.lower()
18 ismacos = 'darwin' in _plat
19 iswindows = 'win32' in _plat or 'win64' in _plat
20
21
22 def setenv(key, val):
23 os.environ[key] = os.path.expandvars(val)
24
25
26 def download_with_retry(url: str | Request, count: int = 5) -> bytes:
27 for i in range(count):
28 try:
29 print('Downloading', getattr(url, 'full_url', url), flush=True)
30 with urlopen(url) as f:
31 ans: bytes = f.read()
32 return ans
33 except Exception as err:
34 if getattr(err, 'code', -1) == 403:
35 raise
36 if i >= count - 1:
37 raise
38 print(f'Download failed with error {err} retrying...', file=sys.stderr)
39 time.sleep(1)
40 return b''
41
42
43 if ismacos:
44 SWBASE = '/Users/Shared/calibre-build/sw'
45 SW = SWBASE + '/sw'
46
47 def install_env():
48 setenv('SWBASE', SWBASE)
49 setenv('SW', SW)
50 setenv('PATH', '$SW/bin:$SW/qt/bin:$SW/python/Python.framework/Versions/2.7/bin:$PWD/node_modules/.bin:$PATH')
51 setenv('CFLAGS', '-I$SW/include')
52 setenv('LDFLAGS', '-L$SW/lib')
53 setenv('QMAKE', '$SW/qt/bin/qmake')
54 setenv('QTWEBENGINE_DISABLE_SANDBOX', '1')
55 setenv('QT_PLUGIN_PATH', '$SW/qt/plugins')
56 old = os.environ.get('DYLD_FALLBACK_LIBRARY_PATH', '')
57 if old:
58 old += ':'
59 setenv('DYLD_FALLBACK_LIBRARY_PATH', old + '$SW/lib')
60 setenv('CALIBRE_ESPEAK_DATA_DIR', '$SW/share/espeak-ng-data')
61
62 else:
63 SWBASE = '/sw'
64 SW = SWBASE + '/sw'
65
66 def install_env():
67 setenv('SW', SW)
68 setenv('PATH', '$SW/bin:$PATH')
69 setenv('CFLAGS', '-I$SW/include')
70 setenv('LDFLAGS', '-L$SW/lib')
71 setenv('LD_LIBRARY_PATH', '$SW/qt/lib:$SW/ffmpeg/lib:$SW/lib')
72 setenv('PKG_CONFIG_PATH', '$SW/lib/pkgconfig')
73 setenv('QMAKE', '$SW/qt/bin/qmake')
74 setenv('CALIBRE_QT_PREFIX', '$SW/qt')
75 setenv('CALIBRE_ESPEAK_DATA_DIR', '$SW/share/espeak-ng-data')
76
77
78 def do_print_crash_reports() -> None:
79 print('Printing available crash reports...', flush=True)
80 if ismacos:
81 end_time = time.monotonic() + 90
82 while time.monotonic() < end_time:
83 time.sleep(1)
84 items = glob.glob(os.path.join(os.path.expanduser('~/Library/Logs/DiagnosticReports'), 'Python-*.ips'))
85 if items:
86 break
87 if items:
88 time.sleep(1)
89 print(os.path.basename(items[0]), flush=True)
90 sdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
91 subprocess.check_call([sys.executable, os.path.join(sdir, '.github', 'workflows', 'macos_crash_report.py'), items[0]])
92 else:
93 run('sh -c "echo bt | coredumpctl debug"')
94 print(flush=True)
95
96
97 def run(*args, timeout=1200, print_crash_reports: bool = False):
98 if len(args) == 1:
99 args = shlex.split(args[0])
100 print(' '.join(args), flush=True)
101 p = subprocess.Popen(args)
102 try:
103 ret = p.wait(timeout=timeout)
104 except subprocess.TimeoutExpired as err:
105 ret = 1
106 print(err, file=sys.stderr, flush=True)
107 print('Timed out running:', ' '.join(args), flush=True, file=sys.stderr)
108 p.kill()
109
110 if ret != 0:
111 if print_crash_reports:
112 do_print_crash_reports()
113 raise SystemExit(ret)
114
115
116 def decompress(path, dest, compression):
117 run('tar', 'x' + compression + 'f', path, '-C', dest)
118
119
120 def download_and_decompress(url, dest, compression=None):
121 if compression is None:
122 compression = 'j' if url.endswith('.bz2') else 'J'
123 for i in range(5):
124 print('Downloading', url, '...')
125 with NamedTemporaryFile() as f:
126 ret = subprocess.Popen(['curl', '-fSL', url], stdout=f).wait()
127 if ret == 0:
128 decompress(f.name, dest, compression)
129 sys.stdout.flush(), sys.stderr.flush()
130 return
131 time.sleep(1)
132 raise SystemExit('Failed to download ' + url)
133
134
135 def install_qt_source_code():
136 dest = os.path.expanduser('~/qt-base')
137 os.mkdir(dest)
138 download_and_decompress('https://download.calibre-ebook.com/qtbase-everywhere-src-6.4.2.tar.xz', dest, 'J')
139 qdir = glob.glob(dest + '/*')[0]
140 os.environ['QT_SRC'] = qdir
141
142
143 def run_python(*args):
144 python = os.path.expandvars('$SW/bin/python')
145 if len(args) == 1:
146 args = shlex.split(args[0])
147 args = [python] + list(args)
148 run(*args, print_crash_reports=True)
149
150
151 def install_linux_deps():
152 run('sudo', 'apt-get', 'update', '-y')
153 # run('sudo', 'apt-get', 'upgrade', '-y')
154 run(
155 'sudo',
156 'apt-get',
157 'install',
158 '-y',
159 'gettext',
160 'libgl1-mesa-dev',
161 'libxkbcommon-dev',
162 'libxkbcommon-x11-dev',
163 'libfreetype-dev',
164 'pulseaudio',
165 'libasound2t64',
166 'libflite1',
167 'libspeechd2',
168 )
169
170
171 def get_tx():
172 url = 'https://github.com/transifex/cli/releases/latest/download/tx-linux-amd64.tar.gz'
173 print('Downloading:', url)
174 raw = download_with_retry(url)
175 with tarfile.open(fileobj=io.BytesIO(raw), mode='r') as tf:
176 tf.extract('tx', filter='fully_trusted')
177
178
179 def install_grype(exe: str = '/tmp/grype') -> str:
180 raw = download_with_retry('https://download.calibre-ebook.com/ci/grype.xz')
181 raw = lzma.decompress(raw)
182 with open(exe, 'wb') as f:
183 f.write(raw)
184 os.fchmod(f.fileno(), 0o755)
185 subprocess.check_call([exe, 'db', 'update'])
186 return exe
187
188
189 IGNORED_DEPENDENCY_CVES = [
190 # python stdlib all these are erroneously marked as fixed in python 3.15
191 # when it hasnt even been released. Sigh.
192 'CVE-2026-1299',
193 'CVE-2026-0865',
194 'CVE-2026-0672',
195 'CVE-2025-15282',
196 'CVE-2025-15366',
197 'CVE-2025-15367',
198 'CVE-2025-12781',
199 'CVE-2025-11468',
200 'CVE-2026-2297',
201 'CVE-2026-3644',
202 'CVE-2026-1502',
203 'CVE-2026-4224', # expat parser unused
204 'CVE-2026-4519', # webbrowser() unused
205 'CVE-2026-7210', # DoS in unused XML parser
206 'CVE-2026-3276', # DoS in unicodedata.normalize()
207 'CVE-2026-7774', # tarfile.data_filter path traversal bypass
208 'CVE-2026-12003', # bug in release builds irrelevant to us
209 'CVE-2026-15308', # bug in stdlib html parser unused by us
210 'CVE-2026-11940', # tarfile, unused
211 'CVE-2026-11972', # tarfile, unused
212 'CVE-2026-0864', # configparser unused
213 # libtiff
214 'CVE-2025-8851', # this is erroneously marked as fixed in the database but no release of libtiff has been made with the fix
215 # hyphen
216 'CVE-2017-1000376', # false match in the database
217 # espeak
218 'CVE-2023-4990', # false match because we currently build with a specific commit pending release of espeak 1.53
219 'CVE-2026-2673', # openssl fix not released
220 'CVE-2026-14456', # openssl fix not released
221 ]
222 IGNORED_DEPENDENCY_PACKAGES = [
223 'nodejs', # only used at build time
224 'ffmpeg', # cannot be updated till we update Qt
225 ]
226
227
228 LINUX_BUNDLE = 'linux-64'
229 MACOS_BUNDLE = 'macos-64'
230 WINDOWS_BUNDLE = 'windows-64'
231
232
233 def install_bundle(dest=SW, which=''):
234 run('sudo', 'mkdir', '-p', dest)
235 run('sudo', 'chown', '-R', os.environ['USER'], SWBASE)
236 tball = which or (MACOS_BUNDLE if ismacos else LINUX_BUNDLE)
237 download_and_decompress(f'https://download.calibre-ebook.com/ci/calibre7/{tball}.tar.xz', dest)
238
239
240 def check_dependencies() -> None:
241 dest = os.path.join(SW, LINUX_BUNDLE)
242 install_bundle(dest, os.path.basename(dest))
243 dest = os.path.join(SW, MACOS_BUNDLE)
244 install_bundle(dest, os.path.basename(dest))
245 dest = os.path.join(SW, WINDOWS_BUNDLE)
246 install_bundle(dest, os.path.basename(dest))
247 grype = install_grype()
248 with open((gc := os.path.expanduser('~/.grype.yml')), 'w') as f:
249 print('ignore:', file=f)
250 for x in IGNORED_DEPENDENCY_CVES:
251 print(' - vulnerability:', x, file=f)
252 for x in IGNORED_DEPENDENCY_PACKAGES:
253 print(' - package:', file=f)
254 print(f' name: {x}', file=f)
255 cmdline = [grype, '--by-cve', '--config', gc, '--fail-on', 'medium', '--only-fixed', '--add-cpes-if-none']
256 # disable testing against dir as it raises false positives on sqlite
257 # embedded in dependencies we dont use at runtime
258 # print('Testing against the bundle directories', flush=True)
259 # if (cp := subprocess.run(cmdline + ['dir:' + SW])).returncode != 0:
260 # raise SystemExit(cp.returncode)
261 # Test against the SBOM
262 print('Testing against the SBOM', flush=True)
263 import runpy
264
265 orig = sys.argv, sys.stdout
266 sys.argv = ['bypy', 'sbom', 'kovidgoyal/calibre', '1.0.0']
267 buf = io.StringIO()
268 sys.stdout = buf
269 runpy.run_path('bypy-src')
270 sys.argv, sys.stdout = orig
271 print(buf.getvalue())
272 if (cp := subprocess.run(cmdline, input=buf.getvalue().encode())).returncode != 0:
273 raise SystemExit(cp.returncode)
274
275
276 def main():
277 action = sys.argv[1]
278
279 if action == 'install':
280 # WebEngine is flaky in macOS CI so install rapydscript so bootstrap wont fail
281 import sysconfig
282
283 run(sys.executable, '-m', 'pip', 'install', 'rapydscript-ng')
284 with open(os.environ['GITHUB_PATH'], 'a') as f:
285 print(sysconfig.get_path('scripts'), file=f)
286
287 if iswindows:
288 import runpy
289
290 m = runpy.run_path('setup/win-ci.py')
291 return m['main']()
292
293 if action == 'install':
294 install_bundle()
295 if not ismacos:
296 install_linux_deps()
297
298 elif action == 'bootstrap':
299 run('rapydscript', '--version')
300 install_env()
301 run_python('setup.py bootstrap --ephemeral')
302
303 elif action == 'check-dependencies':
304 check_dependencies()
305
306 elif action == 'pot':
307 transifexrc = '''\
308 [https://www.transifex.com]
309 api_hostname = https://api.transifex.com
310 rest_hostname = https://rest.api.transifex.com
311 hostname = https://www.transifex.com
312 password = PASSWORD
313 token = PASSWORD
314 username = api
315 '''.replace('PASSWORD', os.environ['tx'])
316 with open(os.path.expanduser('~/.transifexrc'), 'w') as f:
317 f.write(transifexrc)
318 install_qt_source_code()
319 install_env()
320 get_tx()
321 os.environ['TX'] = os.path.abspath('tx')
322 run(sys.executable, 'setup.py', 'pot', timeout=30 * 60)
323 elif action == 'test':
324 os.environ['CI'] = 'true'
325 os.environ['OPENSSL_MODULES'] = os.path.join(SW, 'lib', 'ossl-modules')
326 os.environ['PIPER_TTS_DIR'] = os.path.join(SW, 'piper')
327 if ismacos:
328 os.environ['SSL_CERT_DIR'] = os.path.abspath('resources/mozilla-ca-certs')
329 # needed to ensure correct libxml2 is loaded
330 os.environ['DYLD_INSERT_LIBRARIES'] = ':'.join(os.path.join(SW, 'lib', x) for x in 'libxml2.dylib libxslt.dylib libexslt.dylib'.split())
331 os.environ['OPENSSL_ENGINES'] = os.path.join(SW, 'lib', 'engines-3')
332
333 install_env()
334 run_python('setup.py test')
335 if not ismacos: # webengine is flaky on macOS
336 run_python('setup.py test_rs')
337 else:
338 raise SystemExit(f'Unknown action: {action}')
339
340
341 if __name__ == '__main__':
342 main()