pull/9348/head
Eli Schwartz 3 years ago
parent 47ae0b82f0
commit d06cc042eb
No known key found for this signature in database
GPG Key ID: CEB167EFB5722BD6
  1. 2
      mesonbuild/interpreter/compiler.py
  2. 4
      mesonbuild/mesonlib/universal.py
  3. 10
      mesonbuild/minit.py
  4. 26
      mesonbuild/minstall.py
  5. 2
      mesonbuild/modules/cmake.py
  6. 40
      mesonbuild/modules/gnome.py
  7. 3
      mesonbuild/modules/hotdoc.py
  8. 2
      mesonbuild/modules/i18n.py
  9. 3
      mesonbuild/modules/pkgconfig.py
  10. 6
      mesonbuild/modules/python.py
  11. 3
      mesonbuild/modules/unstable_cuda.py
  12. 8
      mesonbuild/programs.py
  13. 34
      mesonbuild/wrap/wrap.py

@ -719,7 +719,7 @@ class CompilerHolder(ObjectHolder['Compiler']):
result, cached = self.compiler.has_func_attribute(attr, self.environment) result, cached = self.compiler.has_func_attribute(attr, self.environment)
cached_msg = mlog.blue('(cached)') if cached else '' cached_msg = mlog.blue('(cached)') if cached else ''
h = mlog.green('YES') if result else mlog.red('NO') h = mlog.green('YES') if result else mlog.red('NO')
mlog.log('Compiler for {} supports function attribute {}:'.format(self.compiler.get_display_language(), attr), h, cached_msg) mlog.log(f'Compiler for {self.compiler.get_display_language()} supports function attribute {attr}:', h, cached_msg)
return result return result
@FeatureNew('compiler.has_function_attribute', '0.48.0') @FeatureNew('compiler.has_function_attribute', '0.48.0')

@ -1467,8 +1467,8 @@ def _substitute_values_check_errors(command: T.List[str], values: T.Dict[str, T.
# Error out if any output-derived templates are present in the command # Error out if any output-derived templates are present in the command
match = iter_regexin_iter(outregex, command) match = iter_regexin_iter(outregex, command)
if match: if match:
m = 'Command cannot have {!r} since there are no outputs' m = f'Command cannot have {match!r} since there are no outputs'
raise MesonException(m.format(match)) raise MesonException(m)
else: else:
# Error out if an invalid @OUTPUTnn@ template was specified # Error out if an invalid @OUTPUTnn@ template was specified
for each in command: for each in command:

@ -75,14 +75,12 @@ def autodetect_options(options: 'argparse.Namespace', sample: bool = False) -> N
if not options.name: if not options.name:
options.name = Path().resolve().stem options.name = Path().resolve().stem
if not re.match('[a-zA-Z_][a-zA-Z0-9]*', options.name) and sample: if not re.match('[a-zA-Z_][a-zA-Z0-9]*', options.name) and sample:
raise SystemExit('Name of current directory "{}" is not usable as a sample project name.\n' raise SystemExit(f'Name of current directory "{options.name}" is not usable as a sample project name.\n'
'Specify a project name with --name.'.format(options.name)) 'Specify a project name with --name.')
print('Using "{}" (name of current directory) as project name.' print(f'Using "{options.name}" (name of current directory) as project name.')
.format(options.name))
if not options.executable: if not options.executable:
options.executable = options.name options.executable = options.name
print('Using "{}" (project name) as name of executable to build.' print(f'Using "{options.executable}" (project name) as name of executable to build.')
.format(options.executable))
if sample: if sample:
# The rest of the autodetection is not applicable to generating sample projects. # The rest of the autodetection is not applicable to generating sample projects.
return return

@ -181,8 +181,8 @@ def sanitize_permissions(path: str, umask: T.Union[str, int]) -> None:
try: try:
set_chmod(path, new_perms, follow_symlinks=False) set_chmod(path, new_perms, follow_symlinks=False)
except PermissionError as e: except PermissionError as e:
msg = '{!r}: Unable to set permissions {!r}: {}, ignoring...' msg = f'{path!r}: Unable to set permissions {new_perms!r}: {e.strerror}, ignoring...'
print(msg.format(path, new_perms, e.strerror)) print(msg)
def set_mode(path: str, mode: T.Optional['FileMode'], default_umask: T.Union[str, int]) -> None: def set_mode(path: str, mode: T.Optional['FileMode'], default_umask: T.Union[str, int]) -> None:
@ -195,15 +195,15 @@ def set_mode(path: str, mode: T.Optional['FileMode'], default_umask: T.Union[str
try: try:
set_chown(path, mode.owner, mode.group, follow_symlinks=False) set_chown(path, mode.owner, mode.group, follow_symlinks=False)
except PermissionError as e: except PermissionError as e:
msg = '{!r}: Unable to set owner {!r} and group {!r}: {}, ignoring...' msg = f'{path!r}: Unable to set owner {mode.owner!r} and group {mode.group!r}: {e.strerror}, ignoring...'
print(msg.format(path, mode.owner, mode.group, e.strerror)) print(msg)
except LookupError: except LookupError:
msg = '{!r}: Non-existent owner {!r} or group {!r}: ignoring...' msg = f'{path!r}: Non-existent owner {mode.owner!r} or group {mode.group!r}: ignoring...'
print(msg.format(path, mode.owner, mode.group)) print(msg)
except OSError as e: except OSError as e:
if e.errno == errno.EINVAL: if e.errno == errno.EINVAL:
msg = '{!r}: Non-existent numeric owner {!r} or group {!r}: ignoring...' msg = f'{path!r}: Non-existent numeric owner {mode.owner!r} or group {mode.group!r}: ignoring...'
print(msg.format(path, mode.owner, mode.group)) print(msg)
else: else:
raise raise
# Must set permissions *after* setting owner/group otherwise the # Must set permissions *after* setting owner/group otherwise the
@ -213,8 +213,8 @@ def set_mode(path: str, mode: T.Optional['FileMode'], default_umask: T.Union[str
try: try:
set_chmod(path, mode.perms, follow_symlinks=False) set_chmod(path, mode.perms, follow_symlinks=False)
except PermissionError as e: except PermissionError as e:
msg = '{!r}: Unable to set permissions {!r}: {}, ignoring...' msg = '{path!r}: Unable to set permissions {mode.perms_s!r}: {e.strerror}, ignoring...'
print(msg.format(path, mode.perms_s, e.strerror)) print(msg)
else: else:
sanitize_permissions(path, default_umask) sanitize_permissions(path, default_umask)
@ -400,15 +400,13 @@ class Installer:
makedirs: T.Optional[T.Tuple[T.Any, str]] = None) -> bool: makedirs: T.Optional[T.Tuple[T.Any, str]] = None) -> bool:
outdir = os.path.split(to_file)[0] outdir = os.path.split(to_file)[0]
if not os.path.isfile(from_file) and not os.path.islink(from_file): if not os.path.isfile(from_file) and not os.path.islink(from_file):
raise RuntimeError('Tried to install something that isn\'t a file:' raise RuntimeError(f'Tried to install something that isn\'t a file: {from_file!r}')
'{!r}'.format(from_file))
# copyfile fails if the target file already exists, so remove it to # copyfile fails if the target file already exists, so remove it to
# allow overwriting a previous install. If the target is not a file, we # allow overwriting a previous install. If the target is not a file, we
# want to give a readable error. # want to give a readable error.
if os.path.exists(to_file): if os.path.exists(to_file):
if not os.path.isfile(to_file): if not os.path.isfile(to_file):
raise RuntimeError('Destination {!r} already exists and is not ' raise RuntimeError(f'Destination {to_file!r} already exists and is not a file')
'a file'.format(to_file))
if self.should_preserve_existing_file(from_file, to_file): if self.should_preserve_existing_file(from_file, to_file):
append_to_log(self.lf, f'# Preserving old file {to_file}\n') append_to_log(self.lf, f'# Preserving old file {to_file}\n')
self.preserved_file_count += 1 self.preserved_file_count += 1

@ -307,7 +307,7 @@ class CmakeModule(ExtensionModule):
with open(infile, encoding='utf-8') as fin: with open(infile, encoding='utf-8') as fin:
data = fin.readlines() data = fin.readlines()
except Exception as e: except Exception as e:
raise mesonlib.MesonException('Could not read input file {}: {}'.format(infile, str(e))) raise mesonlib.MesonException(f'Could not read input file {infile}: {e!s}')
result = [] result = []
regex = re.compile(r'(?:\\\\)+(?=\\?@)|\\@|@([-a-zA-Z0-9_]+)@') regex = re.compile(r'(?:\\\\)+(?=\\?@)|\\@|@([-a-zA-Z0-9_]+)@')

@ -205,10 +205,10 @@ class GnomeModule(ExtensionModule):
'<https://bugzilla.gnome.org/show_bug.cgi?id=774368>' '<https://bugzilla.gnome.org/show_bug.cgi?id=774368>'
raise MesonException(m) raise MesonException(m)
else: else:
m = 'Unexpected dependency type {!r} for gnome.compile_resources() ' \ m = f'Unexpected dependency type {dep!r} for gnome.compile_resources() ' \
'"dependencies" argument.\nPlease pass the return value of ' \ '"dependencies" argument.\nPlease pass the return value of ' \
'custom_target() or configure_file()' 'custom_target() or configure_file()'
raise MesonException(m.format(dep)) raise MesonException(m)
if not mesonlib.version_compare(glib_version, gresource_dep_needed_version): if not mesonlib.version_compare(glib_version, gresource_dep_needed_version):
ifile = args[1] ifile = args[1]
@ -327,8 +327,8 @@ class GnomeModule(ExtensionModule):
except (FileNotFoundError, PermissionError): except (FileNotFoundError, PermissionError):
raise MesonException('Could not execute glib-compile-resources.') raise MesonException('Could not execute glib-compile-resources.')
if pc.returncode != 0: if pc.returncode != 0:
m = 'glib-compile-resources failed to get dependencies for {}:\n{}' m = f'glib-compile-resources failed to get dependencies for {cmd[1]}:\n{stderr}'
mlog.warning(m.format(cmd[1], stderr)) mlog.warning(m)
raise subprocess.CalledProcessError(pc.returncode, cmd) raise subprocess.CalledProcessError(pc.returncode, cmd)
dep_files = stdout.split('\n')[:-1] dep_files = stdout.split('\n')[:-1]
@ -1224,8 +1224,8 @@ class GnomeModule(ExtensionModule):
if not mesonlib.version_compare(glib_version, '>= 2.49.1'): if not mesonlib.version_compare(glib_version, '>= 2.49.1'):
# Warn if requested, silently disable if not # Warn if requested, silently disable if not
if 'autocleanup' in kwargs: if 'autocleanup' in kwargs:
mlog.warning('Glib version ({}) is too old to support the \'autocleanup\' ' mlog.warning(f'Glib version ({glib_version}) is too old to support the \'autocleanup\' '
'kwarg, need 2.49.1 or newer'.format(glib_version)) 'kwarg, need 2.49.1 or newer')
return [] return []
autocleanup = kwargs.pop('autocleanup', 'all') autocleanup = kwargs.pop('autocleanup', 'all')
values = ('none', 'objects', 'all') values = ('none', 'objects', 'all')
@ -1518,7 +1518,7 @@ class GnomeModule(ExtensionModule):
fhead += '%s\n' % body_prefix fhead += '%s\n' % body_prefix
fhead += '#include "%s"\n' % hdr_filename fhead += '#include "%s"\n' % hdr_filename
for hdr in sources: for hdr in sources:
fhead += '#include "%s"\n' % os.path.basename(str(hdr)) fhead += '#include "{}"\n'.format(os.path.basename(str(hdr)))
fhead += ''' fhead += '''
#define C_ENUM(v) ((gint) v) #define C_ENUM(v) ((gint) v)
#define C_FLAGS(v) ((guint) v) #define C_FLAGS(v) ((guint) v)
@ -1529,12 +1529,12 @@ class GnomeModule(ExtensionModule):
/* enumerations from "@basename@" */ /* enumerations from "@basename@" */
''' '''
c_file_kwargs['vhead'] = ''' c_file_kwargs['vhead'] = f'''
GType GType
%s@enum_name@_get_type (void) {func_prefix}@enum_name@_get_type (void)
{ {{
static gsize gtype_id = 0; static gsize gtype_id = 0;
static const G@Type@Value values[] = {''' % func_prefix static const G@Type@Value values[] = {{'''
c_file_kwargs['vprod'] = ' { C_@TYPE@(@VALUENAME@), "@VALUENAME@", "@valuenick@" },' c_file_kwargs['vprod'] = ' { C_@TYPE@(@VALUENAME@), "@VALUENAME@", "@valuenick@" },'
@ -1553,22 +1553,22 @@ GType
# .h file generation # .h file generation
h_file_kwargs = copy.deepcopy(mkenums_kwargs) h_file_kwargs = copy.deepcopy(mkenums_kwargs)
h_file_kwargs['fhead'] = '''#pragma once h_file_kwargs['fhead'] = f'''#pragma once
#include <glib-object.h> #include <glib-object.h>
{} {header_prefix}
G_BEGIN_DECLS G_BEGIN_DECLS
'''.format(header_prefix) '''
h_file_kwargs['fprod'] = ''' h_file_kwargs['fprod'] = '''
/* enumerations from "@basename@" */ /* enumerations from "@basename@" */
''' '''
h_file_kwargs['vhead'] = ''' h_file_kwargs['vhead'] = f'''
{} {decl_decorator}
GType {}@enum_name@_get_type (void); GType {func_prefix}@enum_name@_get_type (void);
#define @ENUMPREFIX@_TYPE_@ENUMSHORT@ ({}@enum_name@_get_type())'''.format(decl_decorator, func_prefix, func_prefix) #define @ENUMPREFIX@_TYPE_@ENUMSHORT@ ({func_prefix}@enum_name@_get_type())'''
h_file_kwargs['ftail'] = ''' h_file_kwargs['ftail'] = '''
G_END_DECLS''' G_END_DECLS'''
@ -1630,9 +1630,7 @@ G_END_DECLS'''
elif arg in known_kwargs and value: elif arg in known_kwargs and value:
cmd += ['--' + arg.replace('_', '-')] cmd += ['--' + arg.replace('_', '-')]
elif arg not in known_custom_target_kwargs: elif arg not in known_custom_target_kwargs:
raise MesonException( raise MesonException(f'Genmarshal does not take a {arg} keyword argument.')
'Genmarshal does not take a {} keyword argument.'.format(
arg))
install_header = kwargs.pop('install_header', False) install_header = kwargs.pop('install_header', False)
install_dir = kwargs.pop('install_dir', None) install_dir = kwargs.pop('install_dir', None)

@ -406,8 +406,7 @@ class HotDocModule(ExtensionModule):
from hotdoc.run_hotdoc import run # noqa: F401 from hotdoc.run_hotdoc import run # noqa: F401
self.hotdoc.run_hotdoc = run self.hotdoc.run_hotdoc = run
except Exception as e: except Exception as e:
raise MesonException('hotdoc {} required but not found. ({})'.format( raise MesonException(f'hotdoc {MIN_HOTDOC_VERSION} required but not found. ({e})')
MIN_HOTDOC_VERSION, e))
self.methods.update({ self.methods.update({
'has_extensions': self.has_extensions, 'has_extensions': self.has_extensions,
'generate_doc': self.generate_doc, 'generate_doc': self.generate_doc,

@ -230,7 +230,7 @@ class I18nModule(ExtensionModule):
lang_arg = '--langs=' + '@@'.join(languages) if languages else None lang_arg = '--langs=' + '@@'.join(languages) if languages else None
_datadirs = ':'.join(self._get_data_dirs(state, kwargs['data_dirs'])) _datadirs = ':'.join(self._get_data_dirs(state, kwargs['data_dirs']))
datadirs = '--datadirs={}'.format(_datadirs) if _datadirs else None datadirs = f'--datadirs={_datadirs}' if _datadirs else None
extra_args = kwargs['args'] extra_args = kwargs['args']
targets: T.List['Target'] = [] targets: T.List['Target'] = []

@ -100,8 +100,7 @@ class DependenciesHelper:
else: else:
raise mesonlib.MesonException('requires argument not a string, ' raise mesonlib.MesonException('requires argument not a string, '
'library with pkgconfig-generated file ' 'library with pkgconfig-generated file '
'or pkgconfig-dependency object, ' 'or pkgconfig-dependency object, got {obj!r}')
'got {!r}'.format(obj))
return processed_reqs return processed_reqs
def add_cflags(self, cflags): def add_cflags(self, cflags):

@ -141,8 +141,7 @@ class PythonSystemDependency(SystemDependency, _PythonDependencyBase):
elif pycc.startswith(('i686', 'i386')): elif pycc.startswith(('i686', 'i386')):
return '32' return '32'
else: else:
mlog.log('MinGW Python built with unknown CC {!r}, please file' mlog.log(f'MinGW Python built with unknown CC {pycc!r}, please file a bug')
'a bug'.format(pycc))
return None return None
elif self.platform == 'win32': elif self.platform == 'win32':
return '32' return '32'
@ -199,8 +198,7 @@ class PythonSystemDependency(SystemDependency, _PythonDependencyBase):
return return
# Pyarch ends in '32' or '64' # Pyarch ends in '32' or '64'
if arch != pyarch: if arch != pyarch:
mlog.log('Need', mlog.bold(self.name), 'for {}-bit, but ' mlog.log('Need', mlog.bold(self.name), f'for {arch}-bit, but found {pyarch}-bit')
'found {}-bit'.format(arch, pyarch))
self.is_found = False self.is_found = False
return return
# This can fail if the library is not found # This can fail if the library is not found

@ -294,8 +294,7 @@ class CudaModule(NewExtensionModule):
}.get(arch_name, (None, None)) }.get(arch_name, (None, None))
if arch_bin is None: if arch_bin is None:
raise InvalidArguments('Unknown CUDA Architecture Name {}!' raise InvalidArguments(f'Unknown CUDA Architecture Name {arch_name}!')
.format(arch_name))
cuda_arch_bin += arch_bin cuda_arch_bin += arch_bin

@ -106,15 +106,15 @@ class ExternalProgram(mesonlib.HoldableObject):
cmd: T.List[T.Union[str, ExternalProgram]] = [self, '--version'] cmd: T.List[T.Union[str, ExternalProgram]] = [self, '--version']
res = interpreter.run_command_impl(interpreter.current_node, cmd, {}, True) res = interpreter.run_command_impl(interpreter.current_node, cmd, {}, True)
if res.returncode != 0: if res.returncode != 0:
m = 'Running {!r} failed' m = f'Running {raw_cmd!r} failed'
raise mesonlib.MesonException(m.format(raw_cmd)) raise mesonlib.MesonException(m)
output = res.stdout.strip() output = res.stdout.strip()
if not output: if not output:
output = res.stderr.strip() output = res.stderr.strip()
match = re.search(r'([0-9][0-9\.]+)', output) match = re.search(r'([0-9][0-9\.]+)', output)
if not match: if not match:
m = 'Could not find a version number in output of {!r}' m = f'Could not find a version number in output of {raw_cmd!r}'
raise mesonlib.MesonException(m.format(raw_cmd)) raise mesonlib.MesonException(m)
self.cached_version = match.group(1) self.cached_version = match.group(1)
return self.cached_version return self.cached_version

@ -118,7 +118,7 @@ class PackageDefinition:
config = configparser.ConfigParser(interpolation=None) config = configparser.ConfigParser(interpolation=None)
config.read(self.filename) config.read(self.filename)
except configparser.Error as e: except configparser.Error as e:
raise WrapException('Failed to parse {}: {}'.format(self.basename, str(e))) raise WrapException(f'Failed to parse {self.basename}: {e!s}')
self.parse_wrap_section(config) self.parse_wrap_section(config)
if self.type == 'redirect': if self.type == 'redirect':
# [wrap-redirect] have a `filename` value pointing to the real wrap # [wrap-redirect] have a `filename` value pointing to the real wrap
@ -149,8 +149,8 @@ class PackageDefinition:
raise WrapException(f'Missing sections in {self.basename}') raise WrapException(f'Missing sections in {self.basename}')
self.wrap_section = config.sections()[0] self.wrap_section = config.sections()[0]
if not self.wrap_section.startswith('wrap-'): if not self.wrap_section.startswith('wrap-'):
m = '{!r} is not a valid first section in {}' m = f'{self.wrap_section!r} is not a valid first section in {self.basename}'
raise WrapException(m.format(self.wrap_section, self.basename)) raise WrapException(m)
self.type = self.wrap_section[5:] self.type = self.wrap_section[5:]
self.values = dict(config[self.wrap_section]) self.values = dict(config[self.wrap_section])
@ -169,18 +169,18 @@ class PackageDefinition:
self.provided_programs += names_list self.provided_programs += names_list
continue continue
if not v: if not v:
m = ('Empty dependency variable name for {!r} in {}. ' m = (f'Empty dependency variable name for {k!r} in {self.basename}. '
'If the subproject uses meson.override_dependency() ' 'If the subproject uses meson.override_dependency() '
'it can be added in the "dependency_names" special key.') 'it can be added in the "dependency_names" special key.')
raise WrapException(m.format(k, self.basename)) raise WrapException(m)
self.provided_deps[k] = v self.provided_deps[k] = v
def get(self, key: str) -> str: def get(self, key: str) -> str:
try: try:
return self.values[key] return self.values[key]
except KeyError: except KeyError:
m = 'Missing key {!r} in {}' m = f'Missing key {key!r} in {self.basename}'
raise WrapException(m.format(key, self.basename)) raise WrapException(m)
def get_directory(subdir_root: str, packagename: str) -> str: def get_directory(subdir_root: str, packagename: str) -> str:
fname = os.path.join(subdir_root, packagename + '.wrap') fname = os.path.join(subdir_root, packagename + '.wrap')
@ -234,14 +234,14 @@ class Resolver:
for k in wrap.provided_deps.keys(): for k in wrap.provided_deps.keys():
if k in self.provided_deps: if k in self.provided_deps:
prev_wrap = self.provided_deps[k] prev_wrap = self.provided_deps[k]
m = 'Multiple wrap files provide {!r} dependency: {} and {}' m = f'Multiple wrap files provide {k!r} dependency: {wrap.basename} and {prev_wrap.basename}'
raise WrapException(m.format(k, wrap.basename, prev_wrap.basename)) raise WrapException(m)
self.provided_deps[k] = wrap self.provided_deps[k] = wrap
for k in wrap.provided_programs: for k in wrap.provided_programs:
if k in self.provided_programs: if k in self.provided_programs:
prev_wrap = self.provided_programs[k] prev_wrap = self.provided_programs[k]
m = 'Multiple wrap files provide {!r} program: {} and {}' m = f'Multiple wrap files provide {k!r} program: {wrap.basename} and {prev_wrap.basename}'
raise WrapException(m.format(k, wrap.basename, prev_wrap.basename)) raise WrapException(m)
self.provided_programs[k] = wrap self.provided_programs[k] = wrap
def merge_wraps(self, other_resolver: 'Resolver') -> None: def merge_wraps(self, other_resolver: 'Resolver') -> None:
@ -279,8 +279,8 @@ class Resolver:
self.directory = packagename self.directory = packagename
self.wrap = self.wraps.get(packagename) self.wrap = self.wraps.get(packagename)
if not self.wrap: if not self.wrap:
m = 'Neither a subproject directory nor a {}.wrap file was found.' m = f'Neither a subproject directory nor a {self.packagename}.wrap file was found.'
raise WrapNotFoundException(m.format(self.packagename)) raise WrapNotFoundException(m)
self.directory = self.wrap.directory self.directory = self.wrap.directory
if self.wrap.has_wrap: if self.wrap.has_wrap:
@ -387,8 +387,8 @@ class Resolver:
elif out == '': elif out == '':
# It is not a submodule, just a folder that exists in the main repository. # It is not a submodule, just a folder that exists in the main repository.
return False return False
m = 'Unknown git submodule output: {!r}' m = f'Unknown git submodule output: {out!r}'
raise WrapException(m.format(out)) raise WrapException(m)
def get_file(self) -> None: def get_file(self) -> None:
path = self.get_file_internal('source') path = self.get_file_internal('source')
@ -568,8 +568,8 @@ class Resolver:
def apply_patch(self) -> None: def apply_patch(self) -> None:
if 'patch_filename' in self.wrap.values and 'patch_directory' in self.wrap.values: if 'patch_filename' in self.wrap.values and 'patch_directory' in self.wrap.values:
m = 'Wrap file {!r} must not have both "patch_filename" and "patch_directory"' m = f'Wrap file {self.wrap.basename!r} must not have both "patch_filename" and "patch_directory"'
raise WrapException(m.format(self.wrap.basename)) raise WrapException(m)
if 'patch_filename' in self.wrap.values: if 'patch_filename' in self.wrap.values:
path = self.get_file_internal('patch') path = self.get_file_internal('patch')
try: try:

Loading…
Cancel
Save