Merge pull request #5311 from mensinda/flake8Plugins

Added flake8 plugins and some code fixes
pull/5339/head
Jussi Pakkanen 6 years ago committed by GitHub
commit 1f4023fa47
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 8
      mesonbuild/ast/introspection.py
  2. 2
      mesonbuild/ast/visitor.py
  3. 4
      mesonbuild/backend/backends.py
  4. 16
      mesonbuild/backend/ninjabackend.py
  5. 6
      mesonbuild/backend/vs2010backend.py
  6. 4
      mesonbuild/backend/xcodebackend.py
  7. 2
      mesonbuild/compilers/c.py
  8. 4
      mesonbuild/compilers/cs.py
  9. 8
      mesonbuild/dependencies/base.py
  10. 8
      mesonbuild/dependencies/ui.py
  11. 4
      mesonbuild/interpreter.py
  12. 2
      mesonbuild/interpreterbase.py
  13. 16
      mesonbuild/mesonlib.py
  14. 30
      mesonbuild/mesonmain.py
  15. 4
      mesonbuild/minstall.py
  16. 6
      mesonbuild/mintro.py
  17. 51
      mesonbuild/mlog.py
  18. 6
      mesonbuild/modules/python.py
  19. 4
      mesonbuild/modules/windows.py
  20. 2
      mesonbuild/mparser.py
  21. 10
      mesonbuild/munstable_coredata.py
  22. 4
      mesonbuild/scripts/depfixer.py
  23. 4
      mesonbuild/wrap/wrap.py
  24. 2
      mesonbuild/wrap/wraptool.py
  25. 4
      run_project_tests.py
  26. 2
      run_tests.py
  27. 12
      run_unittests.py
  28. 2
      setup.cfg
  29. 4
      sideci.yml
  30. 2
      tools/boost_names.py

@ -122,7 +122,7 @@ class IntrospectionInterpreter(AstInterpreter):
subi.analyze()
subi.project_data['name'] = dirname
self.project_data['subprojects'] += [subi.project_data]
except:
except (mesonlib.MesonException, RuntimeError):
return
def func_add_languages(self, node, args, kwargs):
@ -173,9 +173,9 @@ class IntrospectionInterpreter(AstInterpreter):
arg_node = curr.args
elif isinstance(curr, IdNode):
# Try to resolve the ID and append the node to the queue
id = curr.value
if id in self.assignments and self.assignments[id]:
tmp_node = self.assignments[id][0]
var_name = curr.value
if var_name in self.assignments and self.assignments[var_name]:
tmp_node = self.assignments[var_name][0]
if isinstance(tmp_node, (ArrayNode, IdNode, FunctionNode)):
srcqueue += [tmp_node]
elif isinstance(curr, ArithmeticNode):

@ -134,7 +134,5 @@ class AstVisitor:
self.visit_default_func(node)
for i in node.arguments:
i.accept(self)
for i in node.commas:
pass
for val in node.kwargs.values():
val.accept(self)

@ -322,12 +322,14 @@ class Backend:
raise MesonException('Unknown data type in object list.')
return obj_list
def serialize_executable(self, tname, exe, cmd_args, workdir, env={},
def serialize_executable(self, tname, exe, cmd_args, workdir, env=None,
extra_paths=None, capture=None):
'''
Serialize an executable for running with a generator or a custom target
'''
import hashlib
if env is None:
env = {}
if extra_paths is None:
# The callee didn't check if we needed extra paths, so check it here
if mesonlib.is_windows() or mesonlib.is_cygwin():

@ -406,9 +406,9 @@ int dummy;
}
}
'''
id = target.get_id()
tid = target.get_id()
lang = comp.get_language()
tgt = self.introspection_data[id]
tgt = self.introspection_data[tid]
# Find an existing entry or create a new one
id_hash = (lang, tuple(parameters))
src_block = tgt.get(id_hash, None)
@ -520,7 +520,7 @@ int dummy;
# This will be set as dependencies of all the target's sources. At the
# same time, also deal with generated sources that need to be compiled.
generated_source_files = []
for rel_src, gensrc in generated_sources.items():
for rel_src in generated_sources.keys():
dirpart, fnamepart = os.path.split(rel_src)
raw_src = File(True, dirpart, fnamepart)
if self.environment.is_source(rel_src) and not self.environment.is_header(rel_src):
@ -585,7 +585,7 @@ int dummy;
obj_list.append(self.generate_single_compile(target, src, 'vala', [], header_deps))
# Generate compile targets for all the pre-existing sources for this target
for f, src in target_sources.items():
for src in target_sources.values():
if not self.environment.is_header(src):
if self.environment.is_llvm_ir(src):
obj_list.append(self.generate_llvm_ir_compile(target, src))
@ -912,7 +912,7 @@ int dummy;
# Add possible java generated files to src list
generated_sources = self.get_target_generated_sources(target)
gen_src_list = []
for rel_src, gensrc in generated_sources.items():
for rel_src in generated_sources.keys():
dirpart, fnamepart = os.path.split(rel_src)
raw_src = File(True, dirpart, fnamepart)
if rel_src.endswith('.java'):
@ -1041,7 +1041,7 @@ int dummy;
def generate_single_java_compile(self, src, target, compiler, args):
deps = [os.path.join(self.get_target_dir(l), l.get_filename()) for l in target.link_targets]
generated_sources = self.get_target_generated_sources(target)
for rel_src, gensrc in generated_sources.items():
for rel_src in generated_sources.keys():
if rel_src.endswith('.java'):
deps.append(rel_src)
rel_src = src.rel_to_builddir(self.build_to_src)
@ -1227,7 +1227,7 @@ int dummy;
if len(target.install_dir) > 3 and target.install_dir[3] is True:
target.install_dir[3] = os.path.join(self.environment.get_datadir(), 'gir-1.0')
# Detect gresources and add --gresources arguments for each
for (gres, gensrc) in other_src[1].items():
for gensrc in other_src[1].values():
if isinstance(gensrc, modules.GResourceTarget):
gres_xml, = self.get_custom_target_sources(gensrc)
args += ['--gresources=' + gres_xml]
@ -2751,7 +2751,7 @@ https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47485'''))
return super().get_introspection_data(target_id, target)
result = []
for _, i in self.introspection_data[target_id].items():
for i in self.introspection_data[target_id].values():
result += [i]
return result

@ -312,7 +312,7 @@ class Vs2010Backend(backends.Backend):
target = self.build.targets[prj[0]]
lang = 'default'
if hasattr(target, 'compilers') and target.compilers:
for (lang_out, _) in target.compilers.items():
for lang_out in target.compilers.keys():
lang = lang_out
break
prj_line = prj_templ % (
@ -386,7 +386,7 @@ class Vs2010Backend(backends.Backend):
for p in projlist:
if p[1].parent != PurePath('.'):
ofile.write("\t\t{%s} = {%s}\n" % (p[2], self.subdirs[p[1].parent][0]))
for (_, subdir) in self.subdirs.items():
for subdir in self.subdirs.values():
if subdir[1]:
ofile.write("\t\t{%s} = {%s}\n" % (subdir[0], subdir[1]))
ofile.write('\tEndGlobalSection\n')
@ -463,7 +463,7 @@ class Vs2010Backend(backends.Backend):
def add_target_deps(self, root, target):
target_dict = {target.get_id(): target}
for name, dep in self.get_target_deps(target_dict).items():
for dep in self.get_target_deps(target_dict).values():
if dep.get_id() in self.handled_target_deps[target.get_id()]:
# This dependency was already handled manually.
continue

@ -345,7 +345,7 @@ class XCodeBackend(backends.Backend):
self.ofile.write('/* End PBXFileReference section */\n')
def generate_pbx_frameworks_buildphase(self):
for tname, t in self.build.targets.items():
for t in self.build.targets.values():
self.ofile.write('\n/* Begin PBXFrameworksBuildPhase section */\n')
self.write_line('%s /* %s */ = {\n' % (t.buildphasemap['Frameworks'], 'Frameworks'))
self.indent_level += 1
@ -587,7 +587,7 @@ class XCodeBackend(backends.Backend):
def generate_pbx_sources_build_phase(self):
self.ofile.write('\n/* Begin PBXSourcesBuildPhase section */\n')
for name, phase_id in self.source_phase.items():
for name in self.source_phase.keys():
t = self.build.targets[name]
self.write_line('%s /* Sources */ = {' % (t.buildphasemap[name]))
self.indent_level += 1

@ -1036,7 +1036,7 @@ class CCompiler(Compiler):
elf_class = 2
else:
elf_class = 1
except:
except (MesonException, KeyError): # TODO evaluate if catching KeyError is wanted here
elf_class = 0
# Search in the specified dirs, and then in the system libraries
for d in itertools.chain(extra_dirs, self.get_library_dirs(env, elf_class)):

@ -28,10 +28,10 @@ cs_optimization_args = {'0': [],
}
class CsCompiler(Compiler):
def __init__(self, exelist, version, id, runner=None):
def __init__(self, exelist, version, comp_id, runner=None):
self.language = 'cs'
super().__init__(exelist, version)
self.id = id
self.id = comp_id
self.is_cross = False
self.runner = runner

@ -923,9 +923,11 @@ class CMakeTraceLine:
return s.format(self.file, self.line, self.func, self.args)
class CMakeTarget:
def __init__(self, name, type, properies = {}):
def __init__(self, name, target_type, properies=None):
if properies is None:
properies = {}
self.name = name
self.type = type
self.type = target_type
self.properies = properies
def __repr__(self):
@ -1106,7 +1108,7 @@ class CMakeDependency(ExternalDependency):
for l in lexer1:
if l.func == 'set':
self._cmake_set(l)
except:
except MesonException:
return None
# Extract the variables and sanity check them

@ -298,8 +298,8 @@ class QtBaseDependency(ExternalDependency):
# the Qt + m_name there is not a symlink, it's a file
mod_private_dir = qt_inc_dir
mod_private_inc = _qt_get_private_includes(mod_private_dir, m_name, m.version)
for dir in mod_private_inc:
self.compile_args.append('-I' + dir)
for directory in mod_private_inc:
self.compile_args.append('-I' + directory)
self.link_args += m.get_link_args()
if 'Core' in modules:
@ -402,8 +402,8 @@ class QtBaseDependency(ExternalDependency):
if self.private_headers:
priv_inc = self.get_private_includes(mincdir, module)
for dir in priv_inc:
self.compile_args.append('-I' + dir)
for directory in priv_inc:
self.compile_args.append('-I' + directory)
libfile = self.clib_compiler.find_library(self.qtpkgname + module + modules_lib_suffix,
self.env,
libdir)

@ -2193,7 +2193,7 @@ class Interpreter(InterpreterBase):
def check_cross_stdlibs(self):
if self.build.environment.is_cross_build():
props = self.build.environment.properties.host
for l, c in self.build.cross_compilers.items():
for l in self.build.cross_compilers.keys():
try:
di = mesonlib.stringlistify(props.get_stdlib(l))
if len(di) != 2:
@ -2454,7 +2454,7 @@ external dependencies (including libraries) must go to "dependencies".''')
with mlog.nested():
# Suppress the 'ERROR:' prefix because this exception is not
# fatal and VS CI treat any logs with "ERROR:" as fatal.
mlog.exception(e, prefix=None)
mlog.exception(e, prefix=mlog.yellow('Exception:'))
mlog.log('\nSubproject', mlog.bold(dirname), 'is buildable:', mlog.red('NO'), '(disabling)')
return self.disabled_subproject(dirname)
raise e

@ -144,7 +144,7 @@ def stringArgs(f):
return wrapped
def noArgsFlattening(f):
setattr(f, 'no-args-flattening', True)
setattr(f, 'no-args-flattening', True) # noqa: B010
return f
def disablerIfNotFound(f):

@ -720,11 +720,11 @@ def has_path_sep(name, sep='/\\'):
return True
return False
def do_replacement(regex, line, format, confdata):
def do_replacement(regex, line, variable_format, confdata):
missing_variables = set()
start_tag = '@'
backslash_tag = '\\@'
if format == 'cmake':
if variable_format == 'cmake':
start_tag = '${'
backslash_tag = '\\${'
@ -777,7 +777,7 @@ def do_mesondefine(line, confdata):
raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
def do_conf_file(src, dst, confdata, format, encoding='utf-8'):
def do_conf_file(src, dst, confdata, variable_format, encoding='utf-8'):
try:
with open(src, encoding=encoding, newline='') as f:
data = f.readlines()
@ -785,15 +785,15 @@ def do_conf_file(src, dst, confdata, format, encoding='utf-8'):
raise MesonException('Could not read input file %s: %s' % (src, str(e)))
# Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
# Also allow escaping '@' with '\@'
if format in ['meson', 'cmake@']:
if variable_format in ['meson', 'cmake@']:
regex = re.compile(r'(?:\\\\)+(?=\\?@)|\\@|@([-a-zA-Z0-9_]+)@')
elif format == 'cmake':
elif variable_format == 'cmake':
regex = re.compile(r'(?:\\\\)+(?=\\?\$)|\\\${|\${([-a-zA-Z0-9_]+)}')
else:
raise MesonException('Format "{}" not handled'.format(format))
raise MesonException('Format "{}" not handled'.format(variable_format))
search_token = '#mesondefine'
if format != 'meson':
if variable_format != 'meson':
search_token = '#cmakedefine'
result = []
@ -806,7 +806,7 @@ def do_conf_file(src, dst, confdata, format, encoding='utf-8'):
confdata_useless = False
line = do_mesondefine(line, confdata)
else:
line, missing = do_replacement(regex, line, format, confdata)
line, missing = do_replacement(regex, line, variable_format, confdata)
missing_variables.update(missing)
if missing:
confdata_useless = False

@ -41,41 +41,41 @@ class CommandLineParser:
self.subparsers = self.parser.add_subparsers(title='Commands',
description='If no command is specified it defaults to setup command.')
self.add_command('setup', msetup.add_arguments, msetup.run,
help='Configure the project')
help_msg='Configure the project')
self.add_command('configure', mconf.add_arguments, mconf.run,
help='Change project options',)
help_msg='Change project options',)
self.add_command('install', minstall.add_arguments, minstall.run,
help='Install the project')
help_msg='Install the project')
self.add_command('introspect', mintro.add_arguments, mintro.run,
help='Introspect project')
help_msg='Introspect project')
self.add_command('init', minit.add_arguments, minit.run,
help='Create a new project')
help_msg='Create a new project')
self.add_command('test', mtest.add_arguments, mtest.run,
help='Run tests')
help_msg='Run tests')
self.add_command('wrap', wraptool.add_arguments, wraptool.run,
help='Wrap tools')
help_msg='Wrap tools')
self.add_command('subprojects', msubprojects.add_arguments, msubprojects.run,
help='Manage subprojects')
help_msg='Manage subprojects')
self.add_command('help', self.add_help_arguments, self.run_help_command,
help='Print help of a subcommand')
help_msg='Print help of a subcommand')
self.add_command('rewrite', lambda parser: rewriter.add_arguments(parser, self.formater), rewriter.run,
help='Modify the project definition')
help_msg='Modify the project definition')
# Hidden commands
self.add_command('runpython', self.add_runpython_arguments, self.run_runpython_command,
help=argparse.SUPPRESS)
help_msg=argparse.SUPPRESS)
self.add_command('unstable-coredata', munstable_coredata.add_arguments, munstable_coredata.run,
help=argparse.SUPPRESS)
help_msg=argparse.SUPPRESS)
def add_command(self, name, add_arguments_func, run_func, help, aliases=None):
def add_command(self, name, add_arguments_func, run_func, help_msg, aliases=None):
aliases = aliases or []
# FIXME: Cannot have hidden subparser:
# https://bugs.python.org/issue22848
if help == argparse.SUPPRESS:
if help_msg == argparse.SUPPRESS:
p = argparse.ArgumentParser(prog='meson ' + name, formatter_class=self.formater)
self.hidden_commands.append(name)
else:
p = self.subparsers.add_parser(name, help=help, aliases=aliases, formatter_class=self.formater)
p = self.subparsers.add_parser(name, help=help_msg, aliases=aliases, formatter_class=self.formater)
add_arguments_func(p)
p.set_defaults(run_func=run_func)
for i in [name] + aliases:

@ -65,7 +65,7 @@ class DirMaker:
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
def __exit__(self, exception_type, value, traceback):
self.dirs.reverse()
for d in self.dirs:
append_to_log(self.lf, d)
@ -93,7 +93,7 @@ def set_chown(path, user=None, group=None, dir_fd=None, follow_symlinks=True):
dir_fd=dir_fd,
follow_symlinks=follow_symlinks)
shutil.chown(path, user, group)
except:
except Exception:
raise
finally:
os.chown = real_os_chown

@ -117,11 +117,11 @@ def list_installed(installdata):
for t in installdata.targets:
res[os.path.join(installdata.build_dir, t.fname)] = \
os.path.join(installdata.prefix, t.outdir, os.path.basename(t.fname))
for path, installpath, unused_prefix in installdata.data:
for path, installpath, _ in installdata.data:
res[path] = os.path.join(installdata.prefix, installpath)
for path, installdir, unused_custom_install_mode in installdata.headers:
for path, installdir, _ in installdata.headers:
res[path] = os.path.join(installdata.prefix, installdir, os.path.basename(path))
for path, installpath, unused_custom_install_mode in installdata.man:
for path, installpath, _ in installdata.man:
res[path] = os.path.join(installdata.prefix, installpath)
return res

@ -19,6 +19,7 @@ import time
import platform
from contextlib import contextmanager
import typing
from typing import Any, Generator, List, Optional, Sequence, TextIO, Union
"""This is (mostly) a standalone module used to write logging
information about Meson runs. Some output goes to screen,
@ -43,11 +44,11 @@ if platform.system().lower() == 'windows':
colorize_console = os.isatty(sys.stdout.fileno()) and _windows_ansi() # type: bool
else:
colorize_console = os.isatty(sys.stdout.fileno()) and os.environ.get('TERM') != 'dumb'
log_dir = None # type: typing.Optional[str]
log_file = None # type: typing.Optional[typing.TextIO]
log_dir = None # type: Optional[str]
log_file = None # type: Optional[TextIO]
log_fname = 'meson-log.txt' # type: str
log_depth = 0 # type: int
log_timestamp_start = None # type: typing.Optional[float]
log_timestamp_start = None # type: Optional[float]
log_fatal_warnings = False # type: bool
log_disable_stdout = False # type: bool
log_errors_only = False # type: bool
@ -78,7 +79,7 @@ def set_timestamp_start(start: float) -> None:
global log_timestamp_start
log_timestamp_start = start
def shutdown() -> typing.Optional[str]:
def shutdown() -> Optional[str]:
global log_file
if log_file is not None:
path = log_file.name
@ -124,8 +125,8 @@ def cyan(text: str) -> AnsiDecorator:
# This really should be AnsiDecorator or anything that implements
# __str__(), but that requires protocols from typing_extensions
def process_markup(args: typing.Sequence[typing.Union[AnsiDecorator, str]], keep: bool) -> typing.List[str]:
arr = [] # type: typing.List[str]
def process_markup(args: Sequence[Union[AnsiDecorator, str]], keep: bool) -> List[str]:
arr = [] # type: List[str]
if log_timestamp_start is not None:
arr = ['[{:.3f}]'.format(time.monotonic() - log_timestamp_start)]
for arg in args:
@ -139,7 +140,7 @@ def process_markup(args: typing.Sequence[typing.Union[AnsiDecorator, str]], keep
arr.append(str(arg))
return arr
def force_print(*args: str, **kwargs: typing.Any) -> None:
def force_print(*args: str, **kwargs: Any) -> None:
global log_disable_stdout
if log_disable_stdout:
return
@ -160,14 +161,14 @@ def force_print(*args: str, **kwargs: typing.Any) -> None:
print(cleaned, end='')
# We really want a heterogenous dict for this, but that's in typing_extensions
def debug(*args: typing.Union[str, AnsiDecorator], **kwargs: typing.Any) -> None:
def debug(*args: Union[str, AnsiDecorator], **kwargs: Any) -> None:
arr = process_markup(args, False)
if log_file is not None:
print(*arr, file=log_file, **kwargs)
log_file.flush()
def log(*args: typing.Union[str, AnsiDecorator], is_error: bool = False,
**kwargs: typing.Any) -> None:
def log(*args: Union[str, AnsiDecorator], is_error: bool = False,
**kwargs: Any) -> None:
global log_errors_only
arr = process_markup(args, False)
if log_file is not None:
@ -178,7 +179,7 @@ def log(*args: typing.Union[str, AnsiDecorator], is_error: bool = False,
if not log_errors_only or is_error:
force_print(*arr, **kwargs)
def _log_error(severity: str, *rargs: typing.Union[str, AnsiDecorator], **kwargs: typing.Any) -> None:
def _log_error(severity: str, *rargs: Union[str, AnsiDecorator], **kwargs: Any) -> None:
from .mesonlib import get_error_location_string
from .environment import build_filename
from .mesonlib import MesonException
@ -186,7 +187,7 @@ def _log_error(severity: str, *rargs: typing.Union[str, AnsiDecorator], **kwargs
# The tping requirements here are non-obvious. Lists are invariant,
# therefore List[A] and List[Union[A, B]] are not able to be joined
if severity == 'warning':
label = [yellow('WARNING:')] # type: typing.List[typing.Union[str, AnsiDecorator]]
label = [yellow('WARNING:')] # type: List[Union[str, AnsiDecorator]]
elif severity == 'error':
label = [red('ERROR:')]
elif severity == 'deprecation':
@ -202,7 +203,7 @@ def _log_error(severity: str, *rargs: typing.Union[str, AnsiDecorator], **kwargs
location_str = get_error_location_string(location_file, location.lineno)
# Unions are frankly awful, and we have to cast here to get mypy
# to understand that the list concatenation is safe
location_list = typing.cast(typing.List[typing.Union[str, AnsiDecorator]], [location_str])
location_list = typing.cast(List[Union[str, AnsiDecorator]], [location_str])
args = location_list + args
log(*args, **kwargs)
@ -211,18 +212,20 @@ def _log_error(severity: str, *rargs: typing.Union[str, AnsiDecorator], **kwargs
if log_fatal_warnings:
raise MesonException("Fatal warnings enabled, aborting")
def error(*args: typing.Union[str, AnsiDecorator], **kwargs: typing.Any) -> None:
def error(*args: Union[str, AnsiDecorator], **kwargs: Any) -> None:
return _log_error('error', *args, **kwargs, is_error=True)
def warning(*args: typing.Union[str, AnsiDecorator], **kwargs: typing.Any) -> None:
def warning(*args: Union[str, AnsiDecorator], **kwargs: Any) -> None:
return _log_error('warning', *args, **kwargs, is_error=True)
def deprecation(*args: typing.Union[str, AnsiDecorator], **kwargs: typing.Any) -> None:
def deprecation(*args: Union[str, AnsiDecorator], **kwargs: Any) -> None:
return _log_error('deprecation', *args, **kwargs, is_error=True)
def exception(e: Exception, prefix: AnsiDecorator = red('ERROR:')) -> None:
def exception(e: Exception, prefix: Optional[AnsiDecorator] = None) -> None:
if prefix is None:
prefix = red('ERROR:')
log()
args = [] # type: typing.List[typing.Union[AnsiDecorator, str]]
args = [] # type: List[Union[AnsiDecorator, str]]
if hasattr(e, 'file') and hasattr(e, 'lineno') and hasattr(e, 'colno'):
# Mypy can't figure this out, and it's pretty easy to vidual inspect
# that this is correct, so we'll just ignore it.
@ -234,19 +237,19 @@ def exception(e: Exception, prefix: AnsiDecorator = red('ERROR:')) -> None:
# Format a list for logging purposes as a string. It separates
# all but the last item with commas, and the last with 'and'.
def format_list(list_: typing.List[str]) -> str:
l = len(list_)
def format_list(input_list: List[str]) -> str:
l = len(input_list)
if l > 2:
return ' and '.join([', '.join(list_[:-1]), list_[-1]])
return ' and '.join([', '.join(input_list[:-1]), input_list[-1]])
elif l == 2:
return ' and '.join(list_)
return ' and '.join(input_list)
elif l == 1:
return list_[0]
return input_list[0]
else:
return ''
@contextmanager
def nested() -> typing.Generator[None, None, None]:
def nested() -> Generator[None, None, None]:
global log_depth
log_depth += 1
try:

@ -477,9 +477,9 @@ class PythonModule(ExtensionModule):
ver = {'python2': '-2', 'python3': '-3'}[name_or_path]
cmd = ['py', ver, '-c', "import sysconfig; print(sysconfig.get_config_var('BINDIR'))"]
_, stdout, _ = mesonlib.Popen_safe(cmd)
dir = stdout.strip()
if os.path.exists(dir):
return os.path.join(dir, 'python')
directory = stdout.strip()
if os.path.exists(directory):
return os.path.join(directory, 'python')
else:
return None

@ -59,7 +59,7 @@ class WindowsModule(ExtensionModule):
if not rescomp.found():
raise MesonException('Could not find Windows resource compiler')
for (arg, match, type) in [
for (arg, match, rc_type) in [
('/?', '^.*Microsoft.*Resource Compiler.*$', ResourceCompilerType.rc),
('--version', '^.*GNU windres.*$', ResourceCompilerType.windres),
]:
@ -67,7 +67,7 @@ class WindowsModule(ExtensionModule):
m = re.search(match, o, re.MULTILINE)
if m:
mlog.log('Windows resource compiler: %s' % m.group())
self._rescomp = (rescomp, type)
self._rescomp = (rescomp, rc_type)
break
else:
raise MesonException('Could not determine type of Windows resource compiler')

@ -217,7 +217,7 @@ class BaseNode:
fname = 'visit_{}'.format(type(self).__name__)
if hasattr(visitor, fname):
func = getattr(visitor, fname)
if hasattr(func, '__call__'):
if callable(func):
func(self)
class ElementaryNode(BaseNode):

@ -51,7 +51,7 @@ def run(options):
'change the working directory to it.')
return 1
all = options.all
all_backends = options.all
print('This is a dump of the internal unstable cache of meson. This is for debugging only.')
print('Do NOT parse, this will change from version to version in incompatible ways')
@ -64,18 +64,18 @@ def run(options):
# use `meson configure` to view these
pass
elif k in ['install_guid', 'test_guid', 'regen_guid']:
if all or backend.startswith('vs'):
if all_backends or backend.startswith('vs'):
print(k + ': ' + v)
elif k == 'target_guids':
if all or backend.startswith('vs'):
if all_backends or backend.startswith('vs'):
print(k + ':')
dump_guids(v)
elif k in ['lang_guids']:
if all or backend.startswith('vs') or backend == 'xcode':
if all_backends or backend.startswith('vs') or backend == 'xcode':
print(k + ':')
dump_guids(v)
elif k == 'meson_command':
if all or backend.startswith('vs'):
if all_backends or backend.startswith('vs'):
print('Meson command used in build file regeneration: ' + ' '.join(v))
elif k == 'pkgconf_envvar':
print('Last seen PKGCONFIG enviroment variable value: ' + v)

@ -123,7 +123,7 @@ class Elf(DataSizes):
self.parse_header()
self.parse_sections()
self.parse_dynamic()
except:
except (struct.error, RuntimeError):
self.bf.close()
raise
@ -180,7 +180,7 @@ class Elf(DataSizes):
def parse_sections(self):
self.bf.seek(self.e_shoff)
self.sections = []
for i in range(self.e_shnum):
for _ in range(self.e_shnum):
self.sections.append(SectionHeader(self.bf, self.ptrsize, self.is_le))
def read_str(self):

@ -84,7 +84,7 @@ class PackageDefinition:
try:
self.config = configparser.ConfigParser(interpolation=None)
self.config.read(fname)
except:
except configparser.Error:
raise WrapException('Failed to parse {}'.format(self.basename))
if len(self.config.sections()) < 1:
raise WrapException('Missing sections in {}'.format(self.basename))
@ -338,7 +338,7 @@ class Resolver:
"""
Copy directory tree. Overwrites also read only files.
"""
for src_dir, dirs, files in os.walk(root_src_dir):
for src_dir, _, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)

@ -177,7 +177,7 @@ def promote(options):
# check if the argument is a full path to a subproject directory or wrap file
system_native_path_argument = argument.replace('/', os.sep)
for _, matches in sprojs.items():
for matches in sprojs.values():
if system_native_path_argument in matches:
do_promotion(system_native_path_argument, spdir_name)
return

@ -778,7 +778,7 @@ def detect_system_compiler():
try:
comp = env.compiler_from_language(lang, env.is_cross_build())
details = '%s %s' % (' '.join(comp.get_exelist()), comp.get_version_string())
except:
except mesonlib.MesonException:
comp = None
details = 'not found'
print('%-7s: %s' % (lang, details))
@ -823,7 +823,7 @@ if __name__ == '__main__':
print(l, '\n')
except UnicodeError:
print(l.encode('ascii', errors='replace').decode(), '\n')
for name, dirs, skip in all_tests:
for name, dirs, _ in all_tests:
dirs = (x.name for x in dirs)
for k, g in itertools.groupby(dirs, key=lambda x: x.split()[0]):
tests = list(g)

@ -136,7 +136,7 @@ def find_vcxproj_with_target(builddir, target):
p = r'<TargetName>{}</TargetName>\s*<TargetExt>\{}</TargetExt>'.format(t, ext)
else:
p = r'<TargetName>{}</TargetName>'.format(t)
for root, dirs, files in os.walk(builddir):
for _, _, files in os.walk(builddir):
for f in fnmatch.filter(files, '*.vcxproj'):
f = os.path.join(builddir, f)
with open(f, 'r', encoding='utf-8') as o:

@ -1244,7 +1244,7 @@ class BasePlatformTests(unittest.TestCase):
print('Stderr:\n')
print(err)
raise RuntimeError('Configure failed')
except:
except Exception:
self._print_meson_log()
raise
finally:
@ -1257,7 +1257,7 @@ class BasePlatformTests(unittest.TestCase):
out = self._run(self.setup_command + args + extra_args)
except unittest.SkipTest:
raise unittest.SkipTest('Project requested skipping: ' + srcdir)
except:
except Exception:
self._print_meson_log()
raise
return out
@ -2681,9 +2681,9 @@ int main(int argc, char **argv) {
if ninja is None:
raise unittest.SkipTest('This test currently requires ninja. Fix this once "meson build" works.')
for lang in ('c', 'cpp'):
for type in ('executable', 'library'):
for target_type in ('executable', 'library'):
with tempfile.TemporaryDirectory() as tmpdir:
self._run(self.meson_command + ['init', '--language', lang, '--type', type],
self._run(self.meson_command + ['init', '--language', lang, '--type', target_type],
workdir=tmpdir)
self._run(self.setup_command + ['--backend=ninja', 'builddir'],
workdir=tmpdir)
@ -4443,7 +4443,7 @@ class LinuxlikeTests(BasePlatformTests):
self.assertIn(cmd_std, cmd)
try:
self.build()
except:
except Exception:
print('{} was {!r}'.format(lang_std, v))
raise
self.wipe()
@ -5527,7 +5527,7 @@ class RewriterTests(BasePlatformTests):
out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json'))
expected = {'name': 'myExe', 'sources': ['main.cpp']}
self.assertEqual(len(out['target']), 2)
for _, val in out['target'].items():
for val in out['target'].values():
self.assertDictEqual(expected, val)
def test_kwargs_info(self):

@ -28,4 +28,6 @@ ignore =
E722
# W504: line break after binary operator
W504
# A003: builtin class attribute
A003
max-line-length = 120

@ -1,3 +1,7 @@
linter:
flake8:
version: 3
plugins:
- flake8-blind-except
- flake8-builtins
- flake8-bugbear

@ -132,7 +132,7 @@ def get_modules_2():
# The python module uses an older build system format and is not easily parseable.
# We add the python module libraries manually.
modules.append(Module('python', 'Python', ['boost_python', 'boost_python3', 'boost_numpy', 'boost_numpy3']))
for (root, dirs, files) in os.walk(LIBS):
for (root, _, files) in os.walk(LIBS):
for f in files:
if f == "libraries.json":
projectdir = os.path.dirname(root)

Loading…
Cancel
Save