Debian Codegraph @

mesonbuild/mdist.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2017 The Meson development team
3 # Copyright © 2023-2025 Intel Corporation
4
5 from __future__ import annotations
6
7
8 import abc
9 import argparse
10 import itertools
11 import os
12 import sys
13 import shlex
14 import shutil
15 import subprocess
16 import tarfile
17 import tempfile
18 import hashlib
19 import typing as T
20
21 from dataclasses import dataclass
22 from glob import glob
23 from pathlib import Path
24 from mesonbuild.environment import Environment
25 from mesonbuild.tooldetect import detect_ninja
26 from mesonbuild.mesonlib import (GIT, MesonException, RealPathAction, SimpleABC, get_meson_command, quiet_git,
27 windows_proof_rmtree, setup_vsenv, determine_worker_count, unwrap_err)
28 from .options import OptionKey
29 from mesonbuild.msetup import add_arguments as msetup_argparse
30 from mesonbuild.wrap import wrap
31 from mesonbuild import mlog, build, cmdline
32 from .scripts.meson_exe import run_exe
33
34 if T.TYPE_CHECKING:
35 from ._typing import ImmutableListProtocol
36 from .mesonlib import ExecutableSerialisation, SubProject
37
38 archive_choices = ['bztar', 'gztar', 'xztar', 'zip']
39
40 archive_extension = {'bztar': '.tar.bz2',
41 'gztar': '.tar.gz',
42 'xztar': '.tar.xz',
43 'zip': '.zip'}
44
45 if sys.version_info >= (3, 14):
46 tarfile.TarFile.extraction_filter = staticmethod(tarfile.fully_trusted_filter)
47
48 # Note: when adding arguments, please also add them to the completion
49 # scripts in $MESONSRC/data/shell-completions/
50 def add_arguments(parser: argparse.ArgumentParser) -> None:
51 parser.add_argument('-C', dest='wd', action=RealPathAction,
52 help='directory to cd into before running')
53 parser.add_argument('--allow-dirty', action='store_true',
54 help='Allow even when repository contains uncommitted changes.')
55 parser.add_argument('--formats', default='xztar',
56 help='Comma separated list of archive types to create. Supports xztar (default), bztar, gztar, and zip.')
57 parser.add_argument('--include-subprojects', action='store_true',
58 help='Include source code of subprojects that have been used for the build.')
59 parser.add_argument('--no-tests', action='store_true',
60 help='Do not build and test generated packages.')
61 parser.add_argument('-j', '--num-processes', default=determine_worker_count(), type=int,
62 help='How many parallel processes to use (e.g. for compilation and testing).')
63
64
65 def create_hash(fname: str) -> None:
66 hashname = fname + '.sha256sum'
67 m = hashlib.sha256()
68 m.update(open(fname, 'rb').read())
69 with open(hashname, 'w', encoding='utf-8') as f:
70 # A space and an asterisk because that is the format defined by GNU coreutils
71 # and accepted by busybox and the Perl shasum tool.
72 f.write('{} *{}\n'.format(m.hexdigest(), os.path.basename(fname)))
73
74
75 msg_uncommitted_changes = 'Repository has uncommitted changes that will not be included in the dist tarball'
76
77 def handle_dirty_opt(msg: str, allow_dirty: bool) -> None:
78 if allow_dirty:
79 mlog.warning(msg)
80 else:
81 mlog.error(msg + '\n' + 'Use --allow-dirty to ignore the warning and proceed anyway')
82 sys.exit(1)
83
84 def is_git(src_root: str) -> bool:
85 '''
86 Checks if meson.build file at the root source directory is tracked by git.
87 It could be a subproject part of the parent project git repository.
88 '''
89 if quiet_git(['ls-files', '--error-unmatch', 'meson.build'], src_root)[0]:
90 return True
91
92 if os.path.exists(os.path.join(src_root, '.git')):
93 msg = 'Source tree looks like it may be a git repo, '
94 if not GIT:
95 msg += 'but git is not installed!'
96 if 'GITLAB_CI' in os.environ:
97 msg += ' This is a gitlab bug.'
98 else:
99 msg += 'but git returned a failure. '
100 p, oe = quiet_git(['status'], src_root)
101 if 'dubious ownership' in oe:
102 # For a few years now, git has absolved itself of the responsibility to implement
103 # robust, safe software. Instead of detecting the signs of a problematic scenario,
104 # they have chosen to consider many legitimate and reasonable use cases as "dangerous",
105 # and implemented the number one threat to security worldwide: alert fatigue. Having
106 # done so, they then washed their hands of the matter and permanently tabled the
107 # notion of adding fine-grained detection. This is not just useless, it is *worse*
108 # than useless.
109 #
110 # In our case, the error is triply meaningless since we are already executing build
111 # system commands from the same directory. Either way, reject the notion that git is
112 # well designed or that its error messaging is a valid approach to the problem space.
113 msg += 'This is a bug in git itself, please set `git config --global safe.directory "*"`'
114 else:
115 msg += 'meson.build may not have been committed to git?'
116 mlog.warning(msg)
117 return False
118
119
120 def is_hg(src_root: str) -> bool:
121 return os.path.isdir(os.path.join(src_root, '.hg'))
122
123
124 @dataclass
125 class Dist(metaclass=SimpleABC):
126 dist_name: str
127 src_root: str
128 bld_root: str
129 dist_scripts: T.List[ExecutableSerialisation]
130 subprojects: T.Dict[SubProject, str]
131 options: argparse.Namespace
132
133 def __post_init__(self) -> None:
134 self.dist_sub = os.path.join(self.bld_root, 'meson-dist')
135 self.distdir = os.path.join(self.dist_sub, self.dist_name)
136
137 @abc.abstractmethod
138 def create_dist(self, archives: T.List[str]) -> T.List[str]:
139 pass
140
141 def run_dist_scripts(self) -> None:
142 assert os.path.isabs(self.distdir)
143 mesonrewrite = Environment.get_build_command() + ['rewrite']
144 env = {'MESON_DIST_ROOT': self.distdir,
145 'MESON_SOURCE_ROOT': self.src_root,
146 'MESON_BUILD_ROOT': self.bld_root,
147 'MESONREWRITE': ' '.join(shlex.quote(x) for x in mesonrewrite),
148 }
149 for d in self.dist_scripts:
150 if d.subproject and d.subproject not in self.subprojects:
151 continue
152 subdir = self.subprojects.get(d.subproject, '')
153 env['MESON_PROJECT_DIST_ROOT'] = os.path.join(self.distdir, subdir)
154 env['MESON_PROJECT_SOURCE_ROOT'] = os.path.join(self.src_root, subdir)
155 env['MESON_PROJECT_BUILD_ROOT'] = os.path.join(self.bld_root, subdir)
156 name = ' '.join(d.cmd_args)
157 print(f'Running custom dist script {name!r}')
158 try:
159 rc = run_exe(d, env)
160 if rc != 0:
161 sys.exit('Dist script errored out')
162 except OSError:
163 print(f'Failed to run dist script {name!r}')
164 sys.exit(1)
165
166
167 class GitDist(Dist):
168 def git_root(self, dir_: str) -> Path:
169 # Cannot use --show-toplevel here because git in our CI prints cygwin paths
170 # that python cannot resolve. Workaround this by taking parent of src_root.
171 prefix = quiet_git(['rev-parse', '--show-prefix'], dir_, check=True)[1].strip()
172 if not prefix:
173 return Path(dir_)
174 prefix_level = len(Path(prefix).parents)
175 return Path(dir_).parents[prefix_level - 1]
176
177 def have_dirty_index(self) -> bool:
178 '''Check whether there are uncommitted changes in git'''
179 # Optimistically call update-index, and disregard its return value. It could be read-only,
180 # and only the output of diff-index matters.
181 subprocess.call(['git', '-C', self.src_root, 'update-index', '-q', '--refresh'])
182 ret = subprocess.call(['git', '-C', self.src_root, 'diff-index', '--quiet', 'HEAD'])
183 return ret == 1
184
185 def copy_git(self, src: T.Union[str, os.PathLike], distdir: str, revision: str = 'HEAD',
186 prefix: T.Optional[str] = None, subdir: T.Optional[str] = None) -> None:
187 cmd = ['git', 'archive', '--format', 'tar', revision]
188 if prefix is not None:
189 cmd.insert(2, f'--prefix={prefix}/')
190 if subdir is not None:
191 cmd.extend(['--', subdir])
192 with tempfile.TemporaryFile() as f:
193 subprocess.check_call(cmd, cwd=src, stdout=f)
194 f.seek(0)
195 t = tarfile.open(fileobj=f) # [ignore encoding]
196 t.extractall(path=distdir)
197
198 def process_git_project(self, src_root: str, distdir: str) -> None:
199 if self.have_dirty_index():
200 handle_dirty_opt(msg_uncommitted_changes, self.options.allow_dirty)
201 if os.path.exists(distdir):
202 windows_proof_rmtree(distdir)
203 repo_root = self.git_root(src_root)
204 if repo_root.samefile(src_root):
205 os.makedirs(distdir)
206 self.copy_git(src_root, distdir)
207 else:
208 subdir = Path(src_root).relative_to(repo_root)
209 tmp_distdir = distdir + '-tmp'
210 if os.path.exists(tmp_distdir):
211 windows_proof_rmtree(tmp_distdir)
212 os.makedirs(tmp_distdir)
213 self.copy_git(repo_root, tmp_distdir, subdir=str(subdir))
214 Path(tmp_distdir, subdir).rename(distdir)
215 windows_proof_rmtree(tmp_distdir)
216 self.process_submodules(src_root, distdir)
217
218 def process_submodules(self, src: str, distdir: str) -> None:
219 module_file = os.path.join(src, '.gitmodules')
220 if not os.path.exists(module_file):
221 return
222 cmd = ['git', 'submodule', 'status', '--cached', '--recursive']
223 modlist = subprocess.check_output(cmd, cwd=src, universal_newlines=True).splitlines()
224 for submodule in modlist:
225 status = submodule[:1]
226 sha1, rest = submodule[1:].split(' ', 1)
227 subpath = rest.rsplit(' ', 1)[0]
228
229 if status == '-':
230 mlog.warning(f'Submodule {subpath!r} is not checked out and cannot be added to the dist')
231 continue
232 elif status in {'+', 'U'}:
233 handle_dirty_opt(f'Submodule {subpath!r} has uncommitted changes that will not be included in the dist tarball', self.options.allow_dirty)
234
235 self.copy_git(os.path.join(src, subpath), distdir, revision=sha1, prefix=subpath)
236
237 def create_dist(self, archives: T.List[str]) -> T.List[str]:
238 self.process_git_project(self.src_root, self.distdir)
239 for path in self.subprojects.values():
240 sub_src_root = os.path.join(self.src_root, path)
241 sub_distdir = os.path.join(self.distdir, path)
242 if os.path.exists(sub_distdir):
243 continue
244 if is_git(sub_src_root):
245 self.process_git_project(sub_src_root, sub_distdir)
246 else:
247 shutil.copytree(sub_src_root, sub_distdir)
248 self.run_dist_scripts()
249 output_names = []
250 for a in archives:
251 compressed_name = self.distdir + archive_extension[a]
252 shutil.make_archive(self.distdir, a, root_dir=self.dist_sub, base_dir=self.dist_name)
253 output_names.append(compressed_name)
254 windows_proof_rmtree(self.distdir)
255 return output_names
256
257
258 class HgDist(Dist):
259 def have_dirty_index(self) -> bool:
260 '''Check whether there are uncommitted changes in hg'''
261 env = os.environ.copy()
262 env['LC_ALL'] = 'C'
263 # cpython's gettext has a bug and uses LANGUAGE to override LC_ALL,
264 # contrary to the gettext spec
265 env.pop('LANGUAGE', None)
266 out = subprocess.check_output(['hg', '-R', self.src_root, 'summary'], env=env)
267 return b'commit: (clean)' not in out
268
269 def create_dist(self, archives: T.List[str]) -> T.List[str]:
270 if self.have_dirty_index():
271 handle_dirty_opt(msg_uncommitted_changes, self.options.allow_dirty)
272 if self.dist_scripts:
273 mlog.warning('dist scripts are not supported in Mercurial projects')
274
275 os.makedirs(self.dist_sub, exist_ok=True)
276 tarname = os.path.join(self.dist_sub, self.dist_name + '.tar')
277 xzname = tarname + '.xz'
278 bz2name = tarname + '.bz2'
279 gzname = tarname + '.gz'
280 zipname = os.path.join(self.dist_sub, self.dist_name + '.zip')
281 # Note that -X interprets relative paths using the current working
282 # directory, not the repository root, so this must be an absolute path:
283 # https://bz.mercurial-scm.org/show_bug.cgi?id=6267
284 #
285 # .hg[a-z]* is used instead of .hg* to keep .hg_archival.txt, which may
286 # be useful to link the tarball to the Mercurial revision for either
287 # manual inspection or in case any code interprets it for a --version or
288 # similar.
289 subprocess.check_call(['hg', 'archive', '-R', self.src_root, '-S', '-t', 'tar',
290 '-X', self.src_root + '/.hg[a-z]*', tarname])
291 output_names = []
292 if 'xztar' in archives:
293 import lzma
294 with lzma.open(xzname, 'wb') as xf, open(tarname, 'rb') as tf:
295 shutil.copyfileobj(tf, xf)
296 output_names.append(xzname)
297 if 'bztar' in archives:
298 import bz2
299 with bz2.open(bz2name, 'wb') as bf, open(tarname, 'rb') as tf:
300 shutil.copyfileobj(tf, bf)
301 output_names.append(bz2name)
302 if 'gztar' in archives:
303 import gzip
304 with gzip.open(gzname, 'wb') as zf, open(tarname, 'rb') as tf:
305 shutil.copyfileobj(tf, zf)
306 output_names.append(gzname)
307 os.unlink(tarname)
308 if 'zip' in archives:
309 subprocess.check_call(['hg', 'archive', '-R', self.src_root, '-S', '-t', 'zip', zipname])
310 output_names.append(zipname)
311 return output_names
312
313
314 def run_dist_steps(meson_command: T.List[str], unpacked_src_dir: str, builddir: str, installdir: str, ninja_args: T.List[str]) -> int:
315 if subprocess.call(meson_command + ['--backend=ninja', unpacked_src_dir, builddir]) != 0:
316 print('Running Meson on distribution package failed')
317 return 1
318 if subprocess.call(ninja_args, cwd=builddir) != 0:
319 print('Compiling the distribution package failed')
320 return 1
321 if subprocess.call(ninja_args + ['test'], cwd=builddir) != 0:
322 print('Running unit tests on the distribution package failed')
323 return 1
324 myenv = os.environ.copy()
325 myenv['DESTDIR'] = installdir
326 if subprocess.call(ninja_args + ['install'], cwd=builddir, env=myenv) != 0:
327 print('Installing the distribution package failed')
328 return 1
329 return 0
330
331 def check_dist(packagename: str, _meson_command: ImmutableListProtocol[str], extra_meson_args: T.List[str], bld_root: str, privdir: str, num_processes: int = 1) -> int:
332 print(f'Testing distribution package {packagename}')
333 unpackdir = os.path.join(privdir, 'dist-unpack')
334 builddir = os.path.join(privdir, 'dist-build')
335 installdir = os.path.join(privdir, 'dist-install')
336 for p in (unpackdir, builddir, installdir):
337 if os.path.exists(p):
338 windows_proof_rmtree(p)
339 os.mkdir(p)
340 ninja = unwrap_err(detect_ninja(), 'Ninja is required but could not be found')
341 ninja_args = ninja + [f'-j{num_processes}']
342 shutil.unpack_archive(packagename, unpackdir)
343 unpacked_files = glob(os.path.join(unpackdir, '*'))
344 assert len(unpacked_files) == 1
345 unpacked_src_dir = unpacked_files[0]
346 meson_command = _meson_command.copy()
347 meson_command += ['setup']
348 meson_command += create_cmdline_args(bld_root)
349 meson_command += extra_meson_args
350
351 ret = run_dist_steps(meson_command, unpacked_src_dir, builddir, installdir, ninja_args)
352 if ret > 0:
353 print(f'Dist check build directory was {builddir}')
354 else:
355 windows_proof_rmtree(unpackdir)
356 windows_proof_rmtree(builddir)
357 windows_proof_rmtree(installdir)
358 print(f'Distribution package {packagename} tested')
359 return ret
360
361 def create_cmdline_args(bld_root: str) -> T.List[str]:
362 parser = argparse.ArgumentParser()
363 msetup_argparse(parser)
364 args = T.cast('cmdline.SharedCMDOptions', parser.parse_args([]))
365 cmdline.parse_cmd_line_options(args)
366 cmdline.read_cmd_line_file(bld_root, args)
367 args.cmd_line_options.pop(OptionKey('backend'), '')
368 return shlex.split(cmdline.format_cmd_line_options(args))
369
370 def determine_archives_to_generate(options: argparse.Namespace) -> T.List[str]:
371 result = []
372 for i in options.formats.split(','):
373 if i not in archive_choices:
374 sys.exit(f'Value "{i}" not one of permitted values {archive_choices}.')
375 result.append(i)
376 if len(i) == 0:
377 sys.exit('No archive types specified.')
378 return result
379
380 def run(options: argparse.Namespace) -> int:
381 buildfile = Path(options.wd) / 'meson-private' / 'build.dat'
382 if not buildfile.is_file():
383 raise MesonException(f'Directory {options.wd!r} does not seem to be a Meson build directory.')
384 b = build.load(options.wd)
385 need_vsenv = T.cast('bool', b.environment.coredata.optstore.get_value_for(OptionKey('vsenv')))
386 setup_vsenv(need_vsenv)
387 src_root = b.environment.source_dir
388 bld_root = b.environment.build_dir
389 priv_dir = os.path.join(bld_root, 'meson-private')
390
391 dist_name = b.project_name
392 if b.project_version is not None:
393 dist_name = f'{dist_name}-{b.project_version}'
394
395 archives = determine_archives_to_generate(options)
396
397 subprojects: T.Dict[SubProject, str] = {}
398 extra_meson_args = []
399 if options.include_subprojects:
400 subproject_dir = os.path.join(src_root, b.subproject_dir)
401 for sub in set(itertools.chain(b.projects.host, b.projects.build)):
402 if sub:
403 directory = wrap.get_directory(subproject_dir, sub)
404 subprojects[sub] = os.path.join(b.subproject_dir, directory)
405 extra_meson_args.append('-Dwrap_mode=nodownload')
406
407 cls: T.Type[Dist]
408 if is_git(src_root):
409 cls = GitDist
410 elif is_hg(src_root):
411 if subprojects:
412 print('--include-subprojects option currently not supported with Mercurial')
413 return 1
414 cls = HgDist
415 else:
416 print('Dist currently only works with Git or Mercurial repos')
417 return 1
418
419 project = cls(dist_name, src_root, bld_root, b.dist_scripts, subprojects, options)
420 names = project.create_dist(archives)
421
422 if names is None:
423 return 1
424 rc = 0
425 if not options.no_tests:
426 # Check only one.
427 rc = check_dist(names[0], get_meson_command(), extra_meson_args, bld_root, priv_dir, options.num_processes)
428 if rc == 0:
429 for name in names:
430 create_hash(name)
431 print('Created', name)
432 return rc