Debian Codegraph @

mesonbuild/mdevenv.py

raw
1 from __future__ import annotations
2
3 import os, subprocess
4 import argparse
5 import tempfile
6 import shutil
7 import sys
8 import itertools
9 import typing as T
10
11 from pathlib import Path
12 from . import build, minstall
13 from .mesonlib import (EnvironmentVariables, MesonException, join_args, is_windows, setup_vsenv,
14 get_wine_shortpath, MachineChoice, relpath, is_osx)
15 from .options import OptionKey
16 from . import mlog
17
18
19 if T.TYPE_CHECKING:
20 from .backend.backends import InstallData
21
22 POWERSHELL_EXES = {'pwsh.exe', 'powershell.exe'}
23
24 # Note: when adding arguments, please also add them to the completion
25 # scripts in $MESONSRC/data/shell-completions/
26 def add_arguments(parser: argparse.ArgumentParser) -> None:
27 parser.add_argument('-C', dest='builddir', type=Path, default='.',
28 help='Path to build directory')
29 parser.add_argument('--workdir', '-w', type=Path, default=None,
30 help='Directory to cd into before running (default: builddir, Since 1.0.0)')
31 parser.add_argument('--dump', nargs='?', const=True,
32 help='Only print required environment (Since 0.62.0) ' +
33 'Takes an optional file path (Since 1.1.0)')
34 parser.add_argument('--dump-format', default='export',
35 choices=['sh', 'export', 'vscode'],
36 help='Format used with --dump (Since 1.1.0)')
37 parser.add_argument('devcmd', nargs=argparse.REMAINDER, metavar='command',
38 help='Command to run in developer environment (default: interactive shell)')
39
40 def get_windows_shell() -> T.Optional[str]:
41 mesonbuild = Path(__file__).parent
42 script = mesonbuild / 'scripts' / 'cmd_or_ps.ps1'
43 for shell in POWERSHELL_EXES:
44 try:
45 command = [shell, '-noprofile', '-executionpolicy', 'bypass', '-file', str(script)]
46 result = subprocess.check_output(command)
47 return result.decode().strip()
48 except (subprocess.CalledProcessError, OSError):
49 pass
50 return None
51
52 def reduce_winepath(env: T.Dict[str, str]) -> None:
53 winepath = env.get('WINEPATH')
54 if not winepath:
55 return
56 winecmd = shutil.which('wine64') or shutil.which('wine')
57 if not winecmd:
58 return
59 env['WINEPATH'] = get_wine_shortpath([winecmd], winepath.split(';'))
60 mlog.log('Meson detected wine and has set WINEPATH accordingly')
61
62 def get_env(b: build.Build, dump_fmt: T.Optional[str]) -> T.Tuple[T.Dict[str, str], T.Set[str]]:
63 extra_env = EnvironmentVariables()
64 extra_env.set('MESON_DEVENV', ['1'])
65 extra_env.set('MESON_PROJECT_NAME', [b.project_name])
66
67 sysroot = b.environment.properties[MachineChoice.HOST].get_sys_root()
68 if sysroot:
69 extra_env.set('QEMU_LD_PREFIX', [sysroot])
70
71 env = {} if dump_fmt else os.environ.copy()
72 if not is_windows():
73 # From XDG spec:
74 # > If $XDG_DATA_DIRS is either not set or empty, a value equal to /usr/local/share/:/usr/share/ should be used.
75 # We need that default value, otherwise adding directories with devenv.prepend()
76 # would override system directories instead of adding to them. Note that
77 # devenv.set() still overrides this default. Distros set their default
78 # XDG_DATA_DIRS, but CI containers often do not.
79 if not env.get('XDG_DATA_DIRS'):
80 env['XDG_DATA_DIRS'] = '/usr/local/share:/usr/share'
81 if not env.get('XDG_CONFIG_DIRS'):
82 env['XDG_CONFIG_DIRS'] = '/etc/xdg'
83
84 default_fmt = '${0}' if dump_fmt in {'sh', 'export'} else None
85 varnames = set()
86 for i in itertools.chain(b.devenv, {extra_env}):
87 env = i.get_env(env, default_fmt)
88 varnames |= i.get_names()
89
90 reduce_winepath(env)
91
92 return env, varnames
93
94 def bash_completion_files(b: build.Build, install_data: 'InstallData') -> T.List[str]:
95 from .dependencies.pkgconfig import PkgConfigDependency
96 result = []
97 dep = PkgConfigDependency('bash-completion', b.environment,
98 {'required': False, 'silent': True, 'version': ['>=2.10'], 'native': MachineChoice.HOST})
99 if dep.found():
100 prefix = b.environment.coredata.optstore.get_value_for(OptionKey('prefix'))
101 assert isinstance(prefix, str), 'for mypy'
102 datadir = b.environment.coredata.optstore.get_value_for(OptionKey('datadir'))
103 assert isinstance(datadir, str), 'for mypy'
104 datadir_abs = os.path.join(prefix, datadir)
105 completionsdir = dep.get_variable(pkgconfig='completionsdir', pkgconfig_define=(('datadir', datadir_abs),))
106 assert isinstance(completionsdir, str), 'for mypy'
107 completionsdir_path = Path(completionsdir)
108 for f in install_data.data:
109 if completionsdir_path in Path(f.install_path).parents:
110 result.append(f.path)
111 return result
112
113 def add_gdb_auto_load(autoload_path: Path, gdb_helper: str, fname: Path) -> None:
114 # Copy or symlink the GDB helper into our private directory tree
115 destdir = autoload_path / fname.parent
116 destdir.mkdir(parents=True, exist_ok=True)
117 try:
118 if is_windows():
119 shutil.copy(gdb_helper, str(destdir / os.path.basename(gdb_helper)))
120 else:
121 os.symlink(gdb_helper, str(destdir / os.path.basename(gdb_helper)))
122 except (FileExistsError, shutil.SameFileError):
123 pass
124
125 def write_gdb_script(privatedir: Path, install_data: 'InstallData', workdir: Path) -> None:
126 if not shutil.which('gdb'):
127 return
128 bdir = privatedir.parent
129 autoload_basedir = privatedir / 'gdb-auto-load'
130 autoload_path = Path(autoload_basedir, *bdir.parts[1:])
131 have_gdb_helpers = False
132 for d in install_data.data:
133 if d.path.endswith('-gdb.py') or d.path.endswith('-gdb.gdb') or d.path.endswith('-gdb.scm'):
134 # This GDB helper is made for a specific shared library, search if
135 # we have it in our builddir.
136 libname = Path(d.path).name.rsplit('-', 1)[0]
137 for t in install_data.targets:
138 path = Path(t.fname)
139 if path.name == libname:
140 add_gdb_auto_load(autoload_path, d.path, path)
141 have_gdb_helpers = True
142 if have_gdb_helpers:
143 gdbinit_line = f'add-auto-load-scripts-directory {autoload_basedir}\n'
144 gdbinit_path = bdir / '.gdbinit'
145 first_time = False
146 try:
147 with gdbinit_path.open('r+', encoding='utf-8') as f:
148 if gdbinit_line not in f.readlines():
149 f.write(gdbinit_line)
150 first_time = True
151 except FileNotFoundError:
152 gdbinit_path.write_text(gdbinit_line, encoding='utf-8')
153 first_time = True
154 if first_time:
155 gdbinit_path = gdbinit_path.resolve()
156 workdir_path = workdir.resolve()
157 rel_path = Path(relpath(gdbinit_path, workdir_path))
158 mlog.log('Meson detected GDB helpers and added config in', mlog.bold(str(rel_path)))
159 mlog.log('To load it automatically you might need to:')
160 mlog.log(' - Add', mlog.bold(f'add-auto-load-safe-path {gdbinit_path.parent}'),
161 'in', mlog.bold('~/.gdbinit'))
162 if gdbinit_path.parent != workdir_path:
163 mlog.log(' - Change current workdir to', mlog.bold(str(rel_path.parent)),
164 'or use', mlog.bold(f'--init-command {rel_path}'))
165
166 def macos_sip_enabled() -> bool:
167 if not is_osx():
168 return False
169 ret = subprocess.run(["csrutil", "status"], text=True, capture_output=True, encoding='utf-8')
170 if not ret.stdout:
171 return True
172 return 'enabled' in ret.stdout
173
174 def dump(devenv: T.Dict[str, str], varnames: T.Set[str], dump_format: T.Optional[str], output: T.Optional[T.TextIO] = None) -> None:
175 for name in varnames:
176 print(f'{name}="{devenv[name]}"', file=output)
177 if dump_format == 'export':
178 print(f'export {name}', file=output)
179
180 def run(options: argparse.Namespace) -> int:
181 privatedir = Path(options.builddir) / 'meson-private'
182 buildfile = privatedir / 'build.dat'
183 if not buildfile.is_file():
184 raise MesonException(f'Directory {options.builddir!r} does not seem to be a Meson build directory.')
185 b = build.load(options.builddir)
186 workdir = options.workdir or options.builddir
187
188 need_vsenv = T.cast('bool', b.environment.coredata.optstore.get_value_for(OptionKey('vsenv')))
189 setup_vsenv(need_vsenv) # Call it before get_env to get vsenv vars as well
190 dump_fmt = options.dump_format if options.dump else None
191 devenv, varnames = get_env(b, dump_fmt)
192 if options.dump:
193 if options.devcmd:
194 raise MesonException('--dump option does not allow running other command.')
195 if options.dump is True:
196 dump(devenv, varnames, dump_fmt)
197 else:
198 with open(options.dump, "w", encoding='utf-8') as output:
199 dump(devenv, varnames, dump_fmt, output)
200 return 0
201
202 if b.environment.need_exe_wrapper():
203 m = 'An executable wrapper could be required'
204 exe_wrapper = b.environment.get_exe_wrapper()
205 if exe_wrapper:
206 cmd = ' '.join(exe_wrapper.get_command())
207 m += f': {cmd}'
208 mlog.log(m)
209
210 install_data = minstall.load_install_data(str(privatedir / 'install.dat'))
211 write_gdb_script(privatedir, install_data, workdir)
212
213 args = options.devcmd
214 if not args:
215 prompt_prefix = f'[{b.project_name}]'
216 if os.environ.get("MESON_DISABLE_PS1_OVERRIDE"):
217 prompt_prefix = None
218 shell_env = os.environ.get("SHELL")
219 # Prefer $SHELL in a MSYS2 bash despite it being Windows
220 if shell_env and os.path.exists(shell_env):
221 args = [shell_env]
222 elif is_windows():
223 shell = get_windows_shell()
224 if not shell:
225 mlog.warning('Failed to determine Windows shell, fallback to cmd.exe')
226 if shell in POWERSHELL_EXES:
227 args = [shell, '-NoLogo', '-NoExit']
228 if prompt_prefix:
229 prompt = f'function global:prompt {{ "{prompt_prefix} PS " + $PWD + "> "}}'
230 args += ['-Command', prompt]
231 else:
232 args = [os.environ.get("COMSPEC", r"C:\WINDOWS\system32\cmd.exe")]
233 args += ['/k', f'prompt {prompt_prefix} $P$G']
234 else:
235 args = [os.environ.get("SHELL", os.path.realpath("/bin/sh"))]
236 if "bash" in args[0]:
237 # Let the GC remove the tmp file
238 tmprc = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8')
239 tmprc.write('[ -e ~/.bashrc ] && . ~/.bashrc\n')
240 if prompt_prefix:
241 tmprc.write(f'export PS1="{prompt_prefix} $PS1"\n')
242 for f in bash_completion_files(b, install_data):
243 tmprc.write(f'. "{f}"\n')
244 tmprc.flush()
245 args.append("--rcfile")
246 args.append(tmprc.name)
247 elif args[0].endswith('zsh'):
248 # Let the GC remove the tmp file
249 tmpdir = tempfile.TemporaryDirectory()
250 with open(os.path.join(tmpdir.name, '.zshrc'), 'w', encoding='utf-8') as zshrc:
251 zshrc.write('[ -e ~/.zshrc ] && . ~/.zshrc\n')
252 if prompt_prefix:
253 zshrc.write(f'export PROMPT="{prompt_prefix} $PROMPT"\n')
254 devenv['ZDOTDIR'] = tmpdir.name
255 if 'DYLD_LIBRARY_PATH' in devenv and macos_sip_enabled():
256 mlog.warning('macOS System Integrity Protection is enabled: DYLD_LIBRARY_PATH cannot be set in the subshell')
257 mlog.warning('To fix that, use `meson devenv --dump dev.env && source dev.env`')
258 del devenv['DYLD_LIBRARY_PATH']
259 else:
260 # Try to resolve executable using devenv's PATH
261 abs_path = shutil.which(args[0], path=devenv.get('PATH', None))
262 args[0] = abs_path or args[0]
263
264 try:
265 if is_windows():
266 # execvpe doesn't return exit code on Windows
267 # see https://github.com/python/cpython/issues/63323
268 result = subprocess.run(args, env=devenv, cwd=workdir)
269 sys.exit(result.returncode)
270 else:
271 os.chdir(workdir)
272 os.execvpe(args[0], args, env=devenv)
273 except FileNotFoundError:
274 raise MesonException(f'Command not found: {args[0]}')
275 except OSError as e:
276 raise MesonException(f'Command `{join_args(args)}` failed to execute: {e}')