Merge pull request #1810 from QuLogic/pycharm-warnings

Fix various warnings found in PyCharm
pull/1822/head
Jussi Pakkanen 8 years ago committed by GitHub
commit 5ec6151e56
  1. 4
      mesonbuild/backend/backends.py
  2. 9
      mesonbuild/backend/ninjabackend.py
  3. 1
      mesonbuild/backend/vs2015backend.py
  4. 10
      mesonbuild/build.py
  5. 25
      mesonbuild/compilers.py
  6. 3
      mesonbuild/dependencies/base.py
  7. 1
      mesonbuild/dependencies/misc.py
  8. 12
      mesonbuild/environment.py
  9. 7
      mesonbuild/interpreter.py
  10. 53
      mesonbuild/interpreterbase.py
  11. 5
      mesonbuild/mconf.py
  12. 12
      mesonbuild/mintro.py
  13. 2
      mesonbuild/modules/gnome.py
  14. 6
      mesonbuild/scripts/delwithsuffix.py
  15. 8
      mesonbuild/scripts/dist.py
  16. 2
      mesonbuild/scripts/meson_install.py
  17. 6
      mesonbuild/wrap/wrap.py
  18. 22
      mesontest.py
  19. 4
      run_project_tests.py
  20. 9
      run_unittests.py
  21. 95
      test cases/common/19 comparison/meson.build
  22. 6
      test cases/failing/51 executable comparison/meson.build
  23. 1
      test cases/failing/51 executable comparison/prog.c
  24. 7
      test cases/failing/52 inconsistent comparison/meson.build

@ -529,9 +529,7 @@ class Backend:
return return
ifilename = os.path.join(self.environment.get_build_dir(), 'depmf.json') ifilename = os.path.join(self.environment.get_build_dir(), 'depmf.json')
ofilename = os.path.join(self.environment.get_prefix(), self.build.dep_manifest_name) ofilename = os.path.join(self.environment.get_prefix(), self.build.dep_manifest_name)
mfobj = {'type': 'dependency manifest', mfobj = {'type': 'dependency manifest', 'version': '1.0', 'projects': self.build.dep_manifest}
'version': '1.0'}
mfobj['projects'] = self.build.dep_manifest
with open(ifilename, 'w') as f: with open(ifilename, 'w') as f:
f.write(json.dumps(mfobj)) f.write(json.dumps(mfobj))
# Copy file from, to, and with mode unchanged # Copy file from, to, and with mode unchanged

@ -21,7 +21,7 @@ from .. import dependencies
from .. import compilers from .. import compilers
from ..compilers import CompilerArgs from ..compilers import CompilerArgs
from ..mesonlib import File, MesonException, OrderedSet from ..mesonlib import File, MesonException, OrderedSet
from ..mesonlib import get_meson_script, get_compiler_for_source, Popen_safe from ..mesonlib import get_meson_script, get_compiler_for_source
from .backends import CleanTrees, InstallData from .backends import CleanTrees, InstallData
from ..build import InvalidArguments from ..build import InvalidArguments
import os, sys, pickle, re import os, sys, pickle, re
@ -315,14 +315,14 @@ int dummy;
# Now we handle the following languages: # Now we handle the following languages:
# ObjC++, ObjC, C++, C, D, Fortran, Vala # ObjC++, ObjC, C++, C, D, Fortran, Vala
# target_sources:
# Pre-existing target C/C++ sources to be built; dict of full path to # Pre-existing target C/C++ sources to be built; dict of full path to
# source relative to build root and the original File object. # source relative to build root and the original File object.
target_sources = OrderedDict() # generated_sources:
# GeneratedList and CustomTarget sources to be built; dict of the full # GeneratedList and CustomTarget sources to be built; dict of the full
# path to source relative to build root and the generating target/list # path to source relative to build root and the generating target/list
generated_sources = OrderedDict() # vala_generated_sources:
# Array of sources generated by valac that have to be compiled # Array of sources generated by valac that have to be compiled
vala_generated_sources = []
if 'vala' in target.compilers: if 'vala' in target.compilers:
# Sources consumed by valac are filtered out. These only contain # Sources consumed by valac are filtered out. These only contain
# C/C++ sources, objects, generated libs, and unknown sources now. # C/C++ sources, objects, generated libs, and unknown sources now.
@ -331,6 +331,7 @@ int dummy;
else: else:
target_sources = self.get_target_sources(target) target_sources = self.get_target_sources(target)
generated_sources = self.get_target_generated_sources(target) generated_sources = self.get_target_generated_sources(target)
vala_generated_sources = []
self.scan_fortran_module_outputs(target) self.scan_fortran_module_outputs(target)
# Generate rules for GeneratedLists # Generate rules for GeneratedLists
self.generate_generator_list_rules(target, outfile) self.generate_generator_list_rules(target, outfile)

@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from xml.etree import ElementTree as ET
from .vs2010backend import Vs2010Backend from .vs2010backend import Vs2010Backend

@ -227,8 +227,6 @@ class ExtractedObjects:
'You can only extract all the object files at once.' 'You can only extract all the object files at once.'
raise MesonException(msg) raise MesonException(msg)
def get_want_all_objects(self):
return self.want_all_objects
class EnvironmentVariables: class EnvironmentVariables:
def __init__(self): def __init__(self):
@ -238,7 +236,7 @@ class EnvironmentVariables:
repr_str = "<{0}: {1}>" repr_str = "<{0}: {1}>"
return repr_str.format(self.__class__.__name__, self.envvars) return repr_str.format(self.__class__.__name__, self.envvars)
def get_value(self, name, values, kwargs): def get_value(self, values, kwargs):
separator = kwargs.get('separator', os.pathsep) separator = kwargs.get('separator', os.pathsep)
value = '' value = ''
@ -247,16 +245,16 @@ class EnvironmentVariables:
return separator, value.strip(separator) return separator, value.strip(separator)
def set(self, env, name, values, kwargs): def set(self, env, name, values, kwargs):
return self.get_value(name, values, kwargs)[1] return self.get_value(values, kwargs)[1]
def append(self, env, name, values, kwargs): def append(self, env, name, values, kwargs):
sep, value = self.get_value(name, values, kwargs) sep, value = self.get_value(values, kwargs)
if name in env: if name in env:
return env[name] + sep + value return env[name] + sep + value
return value return value
def prepend(self, env, name, values, kwargs): def prepend(self, env, name, values, kwargs):
sep, value = self.get_value(name, values, kwargs) sep, value = self.get_value(values, kwargs)
if name in env: if name in env:
return value + sep + env[name] return value + sep + env[name]

@ -51,8 +51,8 @@ c_suffixes = lang_suffixes['c'] + ('h',)
# used in build.py:process_compilers() and build.py:get_dynamic_linker() # used in build.py:process_compilers() and build.py:get_dynamic_linker()
clike_langs = ('objcpp', 'objc', 'd', 'cpp', 'c', 'fortran',) clike_langs = ('objcpp', 'objc', 'd', 'cpp', 'c', 'fortran',)
clike_suffixes = () clike_suffixes = ()
for l in clike_langs: for _l in clike_langs:
clike_suffixes += lang_suffixes[l] clike_suffixes += lang_suffixes[_l]
clike_suffixes += ('h', 'll', 's') clike_suffixes += ('h', 'll', 's')
# All these are only for C-like languages; see `clike_langs` above. # All these are only for C-like languages; see `clike_langs` above.
@ -329,8 +329,7 @@ def build_unix_rpath_args(build_dir, rpath_paths, install_rpath):
return ['-Wl,-rpath,' + paths] return ['-Wl,-rpath,' + paths]
class CrossNoRunException(MesonException): class CrossNoRunException(MesonException):
def __init(self, *args, **kwargs): pass
Exception.__init__(self, *args, **kwargs)
class RunResult: class RunResult:
def __init__(self, compiled, returncode=999, stdout='UNDEFINED', stderr='UNDEFINED'): def __init__(self, compiled, returncode=999, stdout='UNDEFINED', stderr='UNDEFINED'):
@ -1018,31 +1017,31 @@ class CCompiler(Compiler):
int main() {{ static int a[1-2*!({expression})]; a[0]=0; return 0; }}''' int main() {{ static int a[1-2*!({expression})]; a[0]=0; return 0; }}'''
return self.compiles(t.format(**fargs), env, extra_args, dependencies) return self.compiles(t.format(**fargs), env, extra_args, dependencies)
def cross_compute_int(self, expression, l, h, guess, prefix, env, extra_args, dependencies): def cross_compute_int(self, expression, low, high, guess, prefix, env, extra_args, dependencies):
if isinstance(guess, int): if isinstance(guess, int):
if self._compile_int('%s == %d' % (expression, guess), prefix, env, extra_args, dependencies): if self._compile_int('%s == %d' % (expression, guess), prefix, env, extra_args, dependencies):
return guess return guess
cur = l cur = low
while l < h: while low < high:
cur = int((l + h) / 2) cur = int((low + high) / 2)
if cur == l: if cur == low:
break break
if self._compile_int('%s >= %d' % (expression, cur), prefix, env, extra_args, dependencies): if self._compile_int('%s >= %d' % (expression, cur), prefix, env, extra_args, dependencies):
l = cur low = cur
else: else:
h = cur high = cur
if self._compile_int('%s == %d' % (expression, cur), prefix, env, extra_args, dependencies): if self._compile_int('%s == %d' % (expression, cur), prefix, env, extra_args, dependencies):
return cur return cur
raise EnvironmentException('Cross-compile check overflowed') raise EnvironmentException('Cross-compile check overflowed')
def compute_int(self, expression, l, h, guess, prefix, env, extra_args=None, dependencies=None): def compute_int(self, expression, low, high, guess, prefix, env, extra_args=None, dependencies=None):
if extra_args is None: if extra_args is None:
extra_args = [] extra_args = []
if self.is_cross: if self.is_cross:
return self.cross_compute_int(expression, l, h, guess, prefix, env, extra_args, dependencies) return self.cross_compute_int(expression, low, high, guess, prefix, env, extra_args, dependencies)
fargs = {'prefix': prefix, 'expression': expression} fargs = {'prefix': prefix, 'expression': expression}
t = '''#include<stdio.h> t = '''#include<stdio.h>
{prefix} {prefix}

@ -547,6 +547,7 @@ class ExtraFrameworkDependency(Dependency):
def __init__(self, name, required, path, kwargs): def __init__(self, name, required, path, kwargs):
Dependency.__init__(self, 'extraframeworks', kwargs) Dependency.__init__(self, 'extraframeworks', kwargs)
self.name = None self.name = None
self.required = required
self.detect(name, path) self.detect(name, path)
if self.found(): if self.found():
mlog.log('Dependency', mlog.bold(name), 'found:', mlog.green('YES'), mlog.log('Dependency', mlog.bold(name), 'found:', mlog.green('YES'),
@ -570,6 +571,8 @@ class ExtraFrameworkDependency(Dependency):
self.path = p self.path = p
self.name = d self.name = d
return return
if not self.found() and self.required:
raise DependencyException('Framework dependency %s not found.' % (name, ))
def get_compile_args(self): def get_compile_args(self):
if self.found(): if self.found():

@ -95,7 +95,6 @@ class BoostDependency(Dependency):
def get_compile_args(self): def get_compile_args(self):
args = [] args = []
include_dir = ''
if self.boost_root is not None: if self.boost_root is not None:
if mesonlib.is_windows(): if mesonlib.is_windows():
include_dir = self.boost_root include_dir = self.boost_root

@ -12,10 +12,10 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import os, re, subprocess, platform import os
from . import coredata import platform
from . import mesonlib import re
from . import mlog
from .compilers import * from .compilers import *
from .mesonlib import EnvironmentException, Popen_safe from .mesonlib import EnvironmentException, Popen_safe
import configparser import configparser
@ -459,11 +459,11 @@ class Environment:
for compiler in compilers: for compiler in compilers:
if isinstance(compiler, str): if isinstance(compiler, str):
compiler = [compiler] compiler = [compiler]
try:
if 'cl' in compiler or 'cl.exe' in compiler: if 'cl' in compiler or 'cl.exe' in compiler:
arg = '/?' arg = '/?'
else: else:
arg = '--version' arg = '--version'
try:
p, out, err = Popen_safe(compiler + [arg]) p, out, err = Popen_safe(compiler + [arg])
except OSError as e: except OSError as e:
popen_exceptions[' '.join(compiler + [arg])] = e popen_exceptions[' '.join(compiler + [arg])] = e
@ -738,7 +738,7 @@ class Environment:
if p.returncode == 1 and err.startswith('usage'): # OSX if p.returncode == 1 and err.startswith('usage'): # OSX
return ArLinker(linker) return ArLinker(linker)
self._handle_exceptions(popen_exceptions, linkers, 'linker') self._handle_exceptions(popen_exceptions, linkers, 'linker')
raise EnvironmentException('Unknown static linker "%s"' % ' '.join(linker)) raise EnvironmentException('Unknown static linker "%s"' % ' '.join(linkers))
def detect_ccache(self): def detect_ccache(self):
try: try:

@ -100,7 +100,7 @@ class RunProcess(InterpreterObject):
try: try:
return Popen_safe(command_array, env=child_env, cwd=cwd) return Popen_safe(command_array, env=child_env, cwd=cwd)
except FileNotFoundError: except FileNotFoundError:
raise InterpreterException('Could not execute command "%s".' % cmd_name) raise InterpreterException('Could not execute command "%s".' % ' '.join(command_array))
def returncode_method(self, args, kwargs): def returncode_method(self, args, kwargs):
return self.returncode return self.returncode
@ -573,6 +573,7 @@ class CustomTargetHolder(TargetHolder):
class RunTargetHolder(InterpreterObject): class RunTargetHolder(InterpreterObject):
def __init__(self, name, command, args, dependencies, subdir): def __init__(self, name, command, args, dependencies, subdir):
super().__init__()
self.held_object = build.RunTarget(name, command, args, dependencies, subdir) self.held_object = build.RunTarget(name, command, args, dependencies, subdir)
def __repr__(self): def __repr__(self):
@ -1353,7 +1354,6 @@ class Interpreter(InterpreterBase):
def module_method_callback(self, return_object): def module_method_callback(self, return_object):
if not isinstance(return_object, ModuleReturnValue): if not isinstance(return_object, ModuleReturnValue):
assert False
raise InterpreterException('Bug in module, it returned an invalid object') raise InterpreterException('Bug in module, it returned an invalid object')
invalues = return_object.new_objects invalues = return_object.new_objects
self.process_new_values(invalues) self.process_new_values(invalues)
@ -2625,11 +2625,10 @@ different subdirectory.
raise InterpreterException('Tried to add non-existing source file %s.' % s) raise InterpreterException('Tried to add non-existing source file %s.' % s)
def format_string(self, templ, args): def format_string(self, templ, args):
templ = self.to_native(templ)
if isinstance(args, mparser.ArgumentNode): if isinstance(args, mparser.ArgumentNode):
args = args.arguments args = args.arguments
for (i, arg) in enumerate(args): for (i, arg) in enumerate(args):
arg = self.to_native(self.evaluate_statement(arg)) arg = self.evaluate_statement(arg)
if isinstance(arg, bool): # Python boolean is upper case. if isinstance(arg, bool): # Python boolean is upper case.
arg = str(arg).lower() arg = str(arg).lower()
templ = templ.replace('@{}@'.format(i), str(arg)) templ = templ.replace('@{}@'.format(i), str(arg))

@ -198,8 +198,6 @@ class InterpreterBase:
def evaluate_notstatement(self, cur): def evaluate_notstatement(self, cur):
v = self.evaluate_statement(cur.value) v = self.evaluate_statement(cur.value)
if isinstance(v, mparser.BooleanNode):
v = v.value
if not isinstance(v, bool): if not isinstance(v, bool):
raise InterpreterException('Argument to "not" is not a boolean.') raise InterpreterException('Argument to "not" is not a boolean.')
return not v return not v
@ -217,20 +215,21 @@ class InterpreterBase:
self.evaluate_codeblock(node.elseblock) self.evaluate_codeblock(node.elseblock)
def evaluate_comparison(self, node): def evaluate_comparison(self, node):
v1 = self.evaluate_statement(node.left) val1 = self.evaluate_statement(node.left)
v2 = self.evaluate_statement(node.right) val2 = self.evaluate_statement(node.right)
if self.is_elementary_type(v1):
val1 = v1
else:
val1 = v1.value
if self.is_elementary_type(v2):
val2 = v2
else:
val2 = v2.value
if node.ctype == '==': if node.ctype == '==':
return val1 == val2 return val1 == val2
elif node.ctype == '!=': elif node.ctype == '!=':
return val1 != val2 return val1 != val2
elif not isinstance(val1, type(val2)):
raise InterpreterException(
'Values of different types ({}, {}) cannot be compared using {}.'.format(type(val1).__name__,
type(val2).__name__,
node.ctype))
elif not self.is_elementary_type(val1):
raise InterpreterException('{} can only be compared for equality.'.format(node.left.value))
elif not self.is_elementary_type(val2):
raise InterpreterException('{} can only be compared for equality.'.format(node.right.value))
elif node.ctype == '<': elif node.ctype == '<':
return val1 < val2 return val1 < val2
elif node.ctype == '<=': elif node.ctype == '<=':
@ -244,45 +243,35 @@ class InterpreterBase:
def evaluate_andstatement(self, cur): def evaluate_andstatement(self, cur):
l = self.evaluate_statement(cur.left) l = self.evaluate_statement(cur.left)
if isinstance(l, mparser.BooleanNode):
l = l.value
if not isinstance(l, bool): if not isinstance(l, bool):
raise InterpreterException('First argument to "and" is not a boolean.') raise InterpreterException('First argument to "and" is not a boolean.')
if not l: if not l:
return False return False
r = self.evaluate_statement(cur.right) r = self.evaluate_statement(cur.right)
if isinstance(r, mparser.BooleanNode):
r = r.value
if not isinstance(r, bool): if not isinstance(r, bool):
raise InterpreterException('Second argument to "and" is not a boolean.') raise InterpreterException('Second argument to "and" is not a boolean.')
return r return r
def evaluate_orstatement(self, cur): def evaluate_orstatement(self, cur):
l = self.evaluate_statement(cur.left) l = self.evaluate_statement(cur.left)
if isinstance(l, mparser.BooleanNode):
l = l.get_value()
if not isinstance(l, bool): if not isinstance(l, bool):
raise InterpreterException('First argument to "or" is not a boolean.') raise InterpreterException('First argument to "or" is not a boolean.')
if l: if l:
return True return True
r = self.evaluate_statement(cur.right) r = self.evaluate_statement(cur.right)
if isinstance(r, mparser.BooleanNode):
r = r.get_value()
if not isinstance(r, bool): if not isinstance(r, bool):
raise InterpreterException('Second argument to "or" is not a boolean.') raise InterpreterException('Second argument to "or" is not a boolean.')
return r return r
def evaluate_uminusstatement(self, cur): def evaluate_uminusstatement(self, cur):
v = self.evaluate_statement(cur.value) v = self.evaluate_statement(cur.value)
if isinstance(v, mparser.NumberNode):
v = v.value
if not isinstance(v, int): if not isinstance(v, int):
raise InterpreterException('Argument to negation is not an integer.') raise InterpreterException('Argument to negation is not an integer.')
return -v return -v
def evaluate_arithmeticstatement(self, cur): def evaluate_arithmeticstatement(self, cur):
l = self.to_native(self.evaluate_statement(cur.left)) l = self.evaluate_statement(cur.left)
r = self.to_native(self.evaluate_statement(cur.right)) r = self.evaluate_statement(cur.right)
if cur.operation == 'add': if cur.operation == 'add':
try: try:
@ -382,8 +371,6 @@ class InterpreterBase:
obj = self.evaluate_statement(invokable) obj = self.evaluate_statement(invokable)
method_name = node.name method_name = node.name
args = node.args args = node.args
if isinstance(obj, mparser.StringNode):
obj = obj.get_value()
if isinstance(obj, str): if isinstance(obj, str):
return self.string_method_call(obj, method_name, args) return self.string_method_call(obj, method_name, args)
if isinstance(obj, bool): if isinstance(obj, bool):
@ -402,7 +389,6 @@ class InterpreterBase:
return obj.method_call(method_name, self.flatten(args), kwargs) return obj.method_call(method_name, self.flatten(args), kwargs)
def bool_method_call(self, obj, method_name, args): def bool_method_call(self, obj, method_name, args):
obj = self.to_native(obj)
(posargs, _) = self.reduce_arguments(args) (posargs, _) = self.reduce_arguments(args)
if method_name == 'to_string': if method_name == 'to_string':
if not posargs: if not posargs:
@ -426,7 +412,6 @@ class InterpreterBase:
raise InterpreterException('Unknown method "%s" for a boolean.' % method_name) raise InterpreterException('Unknown method "%s" for a boolean.' % method_name)
def int_method_call(self, obj, method_name, args): def int_method_call(self, obj, method_name, args):
obj = self.to_native(obj)
(posargs, _) = self.reduce_arguments(args) (posargs, _) = self.reduce_arguments(args)
if method_name == 'is_even': if method_name == 'is_even':
if not posargs: if not posargs:
@ -442,7 +427,6 @@ class InterpreterBase:
raise InterpreterException('Unknown method "%s" for an integer.' % method_name) raise InterpreterException('Unknown method "%s" for an integer.' % method_name)
def string_method_call(self, obj, method_name, args): def string_method_call(self, obj, method_name, args):
obj = self.to_native(obj)
(posargs, _) = self.reduce_arguments(args) (posargs, _) = self.reduce_arguments(args)
if method_name == 'strip': if method_name == 'strip':
return obj.strip() return obj.strip()
@ -534,8 +518,6 @@ class InterpreterBase:
raise InvalidArguments('Keyword argument name is not a string.') raise InvalidArguments('Keyword argument name is not a string.')
a = args.kwargs[key] a = args.kwargs[key]
reduced_kw[key] = self.evaluate_statement(a) reduced_kw[key] = self.evaluate_statement(a)
if not isinstance(reduced_pos, list):
reduced_pos = [reduced_pos]
self.argument_depth -= 1 self.argument_depth -= 1
return reduced_pos, reduced_kw return reduced_pos, reduced_kw
@ -564,7 +546,6 @@ To specify a keyword argument, use : instead of =.''')
if not isinstance(var_name, str): if not isinstance(var_name, str):
raise InvalidArguments('Tried to assign value to a non-variable.') raise InvalidArguments('Tried to assign value to a non-variable.')
value = self.evaluate_statement(node.value) value = self.evaluate_statement(node.value)
value = self.to_native(value)
if not self.is_assignable(value): if not self.is_assignable(value):
raise InvalidCode('Tried to assign an invalid value to variable.') raise InvalidCode('Tried to assign an invalid value to variable.')
# For mutable objects we need to make a copy on assignment # For mutable objects we need to make a copy on assignment
@ -593,12 +574,6 @@ To specify a keyword argument, use : instead of =.''')
return self.variables[varname] return self.variables[varname]
raise InvalidCode('Unknown variable "%s".' % varname) raise InvalidCode('Unknown variable "%s".' % varname)
def to_native(self, arg):
if isinstance(arg, (mparser.StringNode, mparser.NumberNode,
mparser.BooleanNode)):
return arg.value
return arg
def is_assignable(self, value): def is_assignable(self, value):
return isinstance(value, (InterpreterObject, dependencies.Dependency, return isinstance(value, (InterpreterObject, dependencies.Dependency,
str, int, list, mesonlib.File)) str, int, list, mesonlib.File))
@ -624,7 +599,7 @@ To specify a keyword argument, use : instead of =.''')
if len(args) != 2: if len(args) != 2:
raise InvalidCode('Set_variable takes two arguments.') raise InvalidCode('Set_variable takes two arguments.')
varname = args[0] varname = args[0]
value = self.to_native(args[1]) value = args[1]
self.set_variable(varname, value) self.set_variable(varname, value)
# @noKwargs # @noKwargs

@ -26,8 +26,7 @@ parser.add_argument('--clearcache', action='store_true', default=False,
help='Clear cached state (e.g. found dependencies)') help='Clear cached state (e.g. found dependencies)')
class ConfException(mesonlib.MesonException): class ConfException(mesonlib.MesonException):
def __init__(self, *args, **kwargs): pass
super().__init__(*args, **kwargs)
class Conf: class Conf:
def __init__(self, build_dir): def __init__(self, build_dir):
@ -62,7 +61,7 @@ class Conf:
len_name = longest_name = len(titles['name']) len_name = longest_name = len(titles['name'])
len_descr = longest_descr = len(titles['descr']) len_descr = longest_descr = len(titles['descr'])
len_value = longest_value = len(titles['value']) len_value = longest_value = len(titles['value'])
len_choices = longest_choices = 0 # not printed if we don't get any optional values longest_choices = 0 # not printed if we don't get any optional values
# calculate the max length of each # calculate the max length of each
for x in arr: for x in arr:

@ -79,9 +79,7 @@ def list_installed(installdata):
def list_targets(coredata, builddata, installdata): def list_targets(coredata, builddata, installdata):
tlist = [] tlist = []
for (idname, target) in builddata.get_targets().items(): for (idname, target) in builddata.get_targets().items():
t = {} t = {'name': target.get_basename(), 'id': idname}
t['name'] = target.get_basename()
t['id'] = idname
fname = target.get_filename() fname = target.get_filename()
if isinstance(fname, list): if isinstance(fname, list):
fname = [os.path.join(target.subdir, x) for x in fname] fname = [os.path.join(target.subdir, x) for x in fname]
@ -132,9 +130,7 @@ def add_keys(optlist, options):
keys.sort() keys.sort()
for key in keys: for key in keys:
opt = options[key] opt = options[key]
optdict = {} optdict = {'name': key, 'value': opt.value}
optdict['name'] = key
optdict['value'] = opt.value
if isinstance(opt, coredata.UserStringOption): if isinstance(opt, coredata.UserStringOption):
typestr = 'string' typestr = 'string'
elif isinstance(opt, coredata.UserBooleanOption): elif isinstance(opt, coredata.UserBooleanOption):
@ -190,9 +186,7 @@ def list_tests(testdata):
print(json.dumps(result)) print(json.dumps(result))
def list_projinfo(builddata): def list_projinfo(builddata):
result = {} result = {'name': builddata.project_name, 'version': builddata.project_version}
result['name'] = builddata.project_name
result['version'] = builddata.project_version
subprojects = [] subprojects = []
for k, v in builddata.subprojects.items(): for k, v in builddata.subprojects.items():
c = {'name': k, c = {'name': k,

@ -730,7 +730,7 @@ class GnomeModule(ExtensionModule):
return args return args
def gtkdoc_html_dir(self, state, args, kwarga): def gtkdoc_html_dir(self, state, args, kwargs):
if len(args) != 1: if len(args) != 1:
raise MesonException('Must have exactly one argument.') raise MesonException('Must have exactly one argument.')
modulename = args[0] modulename = args[0]

@ -15,12 +15,12 @@
import os, sys import os, sys
def run(args): def run(args):
if len(sys.argv) != 3: if len(args) != 2:
print('delwithsuffix.py <root of subdir to process> <suffix to delete>') print('delwithsuffix.py <root of subdir to process> <suffix to delete>')
sys.exit(1) sys.exit(1)
topdir = sys.argv[1] topdir = args[0]
suffix = sys.argv[2] suffix = args[1]
if suffix[0] != '.': if suffix[0] != '.':
suffix = '.' + suffix suffix = '.' + suffix

@ -13,9 +13,8 @@
# limitations under the License. # limitations under the License.
import os, sys import os
import shutil import shutil
import argparse
import subprocess import subprocess
import pickle import pickle
import hashlib import hashlib
@ -113,7 +112,7 @@ def check_dist(packagename, meson_command):
print('Installing the distribution package failed.') print('Installing the distribution package failed.')
return 1 return 1
finally: finally:
shutil.rmtree(srcdir) shutil.rmtree(unpackdir)
shutil.rmtree(builddir) shutil.rmtree(builddir)
shutil.rmtree(installdir) shutil.rmtree(installdir)
print('Distribution package %s tested.' % packagename) print('Distribution package %s tested.' % packagename)
@ -141,8 +140,7 @@ def run(args):
error_count = 0 error_count = 0
for name in names: for name in names:
rc = check_dist(name, meson_command) # Check only one. rc = check_dist(name, meson_command) # Check only one.
rc = 0
if rc == 0: if rc == 0:
create_hash(name) create_hash(name)
error_count += rc error_count += rc
return rc return 1 if error_count else 0

@ -34,7 +34,7 @@ def set_mode(path, mode):
except PermissionError as e: except PermissionError as e:
msg = '{!r}: Unable to set owner {!r} and group {!r}: {}, ignoring...' msg = '{!r}: Unable to set owner {!r} and group {!r}: {}, ignoring...'
print(msg.format(path, mode.owner, mode.group, e.strerror)) print(msg.format(path, mode.owner, mode.group, e.strerror))
except LookupError as e: except LookupError:
msg = '{!r}: Non-existent owner {!r} or group {!r}: ignoring...' msg = '{!r}: Non-existent owner {!r} or group {!r}: ignoring...'
print(msg.format(path, mode.owner, mode.group)) print(msg.format(path, mode.owner, mode.group))
except OSError as e: except OSError as e:

@ -178,7 +178,6 @@ class Resolver:
if is_there: if is_there:
try: try:
subprocess.check_call(['git', 'rev-parse'], cwd=checkoutdir) subprocess.check_call(['git', 'rev-parse'], cwd=checkoutdir)
is_there = True
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
raise RuntimeError('%s is not empty but is not a valid ' raise RuntimeError('%s is not empty but is not a valid '
'git repository, we can not work with it' 'git repository, we can not work with it'
@ -302,12 +301,13 @@ class Resolver:
try: try:
import lzma import lzma
del lzma del lzma
except ImportError:
pass
else:
try: try:
shutil.register_unpack_format('xztar', ['.tar.xz', '.txz'], shutil._unpack_tarfile, [], "xz'ed tar-file") shutil.register_unpack_format('xztar', ['.tar.xz', '.txz'], shutil._unpack_tarfile, [], "xz'ed tar-file")
except shutil.RegistryError: except shutil.RegistryError:
pass pass
except ImportError:
pass
target_dir = os.path.join(self.subdir_root, package.get('directory')) target_dir = os.path.join(self.subdir_root, package.get('directory'))
if os.path.isdir(target_dir): if os.path.isdir(target_dir):
return return

@ -304,7 +304,7 @@ class TestHarness:
if jsonlogfile: if jsonlogfile:
write_json_log(jsonlogfile, name, result) write_json_log(jsonlogfile, name, result)
def print_summary(self, logfile, jsonlogfile): def print_summary(self, logfile):
msg = ''' msg = '''
OK: %4d OK: %4d
FAIL: %4d FAIL: %4d
@ -446,7 +446,7 @@ TIMEOUT: %4d
assert(isinstance(wrap, list)) assert(isinstance(wrap, list))
return wrap return wrap
def get_pretty_suite(self, test, tests): def get_pretty_suite(self, test):
if len(self.suites) > 1: if len(self.suites) > 1:
rv = TestHarness.split_suite_string(test.suite[0])[0] rv = TestHarness.split_suite_string(test.suite[0])[0]
s = "+".join(TestHarness.split_suite_string(s)[1] for s in test.suite) s = "+".join(TestHarness.split_suite_string(s)[1] for s in test.suite)
@ -457,24 +457,24 @@ TIMEOUT: %4d
return test.name return test.name
def run_tests(self, tests): def run_tests(self, tests):
try:
executor = None executor = None
logfile = None logfile = None
jsonlogfile = None jsonlogfile = None
futures = [] futures = []
try:
numlen = len('%d' % len(tests)) numlen = len('%d' % len(tests))
(logfile, logfilename, jsonlogfile, jsonlogfilename) = self.open_log_files() (logfile, logfilename, jsonlogfile, jsonlogfilename) = self.open_log_files()
wrap = self.get_wrapper() wrap = self.get_wrapper()
for i in range(self.options.repeat): for _ in range(self.options.repeat):
for i, test in enumerate(tests): for i, test in enumerate(tests):
visible_name = self.get_pretty_suite(test, tests) visible_name = self.get_pretty_suite(test)
if self.options.gdb: if self.options.gdb:
test.timeout = None test.timeout = None
if not test.is_parallel or self.options.gdb: if not test.is_parallel or self.options.gdb:
self.drain_futures(futures, logfile, jsonlogfile) self.drain_futures(futures)
futures = [] futures = []
res = self.run_single_test(wrap, test) res = self.run_single_test(wrap, test)
self.print_stats(numlen, tests, visible_name, res, i, logfile, jsonlogfile) self.print_stats(numlen, tests, visible_name, res, i, logfile, jsonlogfile)
@ -488,8 +488,8 @@ TIMEOUT: %4d
if self.options.repeat > 1 and self.fail_count: if self.options.repeat > 1 and self.fail_count:
break break
self.drain_futures(futures, logfile, jsonlogfile) self.drain_futures(futures)
self.print_summary(logfile, jsonlogfile) self.print_summary(logfile)
self.print_collected_logs() self.print_collected_logs()
if logfilename: if logfilename:
@ -500,7 +500,7 @@ TIMEOUT: %4d
if logfile: if logfile:
logfile.close() logfile.close()
def drain_futures(self, futures, logfile, jsonlogfile): def drain_futures(self, futures):
for i in futures: for i in futures:
(result, numlen, tests, name, i, logfile, jsonlogfile) = i (result, numlen, tests, name, i, logfile, jsonlogfile) = i
if self.options.repeat > 1 and self.fail_count: if self.options.repeat > 1 and self.fail_count:
@ -525,7 +525,7 @@ TIMEOUT: %4d
def list_tests(th): def list_tests(th):
tests = th.get_tests() tests = th.get_tests()
for t in tests: for t in tests:
print(th.get_pretty_suite(t, tests)) print(th.get_pretty_suite(t))
def merge_suite_options(options): def merge_suite_options(options):
buildfile = os.path.join(options.wd, 'meson-private/build.dat') buildfile = os.path.join(options.wd, 'meson-private/build.dat')
@ -558,7 +558,7 @@ def rebuild_all(wd):
return False return False
p = subprocess.Popen([ninja, '-C', wd]) p = subprocess.Popen([ninja, '-C', wd])
(stdo, stde) = p.communicate() p.communicate()
if p.returncode != 0: if p.returncode != 0:
print("Could not rebuild") print("Could not rebuild")

@ -66,9 +66,6 @@ class DummyFuture(conc.Future):
ask for the result. Used on platforms where sem_open() is not available: ask for the result. Used on platforms where sem_open() is not available:
MSYS2, OpenBSD, etc: https://bugs.python.org/issue3770 MSYS2, OpenBSD, etc: https://bugs.python.org/issue3770
''' '''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def set_function(self, fn, *args, **kwargs): def set_function(self, fn, *args, **kwargs):
self.fn = fn self.fn = fn
self.fn_args = args self.fn_args = args
@ -220,7 +217,6 @@ def validate_install(srcdir, installdir, compiler):
# If this exists, the test does not install any other files # If this exists, the test does not install any other files
noinst_file = 'usr/no-installed-files' noinst_file = 'usr/no-installed-files'
expected = {} expected = {}
found = {}
ret_msg = '' ret_msg = ''
# Generate list of expected files # Generate list of expected files
if os.path.exists(os.path.join(installdir, noinst_file)): if os.path.exists(os.path.join(installdir, noinst_file)):

@ -18,7 +18,10 @@ import shlex
import subprocess import subprocess
import re, json import re, json
import tempfile import tempfile
import unittest, os, sys, shutil, time import os
import shutil
import sys
import unittest
from glob import glob from glob import glob
from pathlib import PurePath from pathlib import PurePath
import mesonbuild.compilers import mesonbuild.compilers
@ -247,6 +250,7 @@ class InternalTests(unittest.TestCase):
self.assertEqual(substfunc(cmd, d), inputs + cmd[2:]) self.assertEqual(substfunc(cmd, d), inputs + cmd[2:])
# Many inputs, can't use @INPUT@ like this # Many inputs, can't use @INPUT@ like this
cmd = ['@INPUT@.out', 'ordinary', 'strings'] cmd = ['@INPUT@.out', 'ordinary', 'strings']
self.assertRaises(ME, substfunc, cmd, d)
# Not enough inputs # Not enough inputs
cmd = ['@INPUT2@.out', 'ordinary', 'strings'] cmd = ['@INPUT2@.out', 'ordinary', 'strings']
self.assertRaises(ME, substfunc, cmd, d) self.assertRaises(ME, substfunc, cmd, d)
@ -281,6 +285,7 @@ class InternalTests(unittest.TestCase):
self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out', inputs[1] + '.ok'] + cmd[2:]) self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out', inputs[1] + '.ok'] + cmd[2:])
# Many inputs, can't use @INPUT@ like this # Many inputs, can't use @INPUT@ like this
cmd = ['@INPUT@.out', 'ordinary', 'strings'] cmd = ['@INPUT@.out', 'ordinary', 'strings']
self.assertRaises(ME, substfunc, cmd, d)
# Not enough inputs # Not enough inputs
cmd = ['@INPUT2@.out', 'ordinary', 'strings'] cmd = ['@INPUT2@.out', 'ordinary', 'strings']
self.assertRaises(ME, substfunc, cmd, d) self.assertRaises(ME, substfunc, cmd, d)
@ -307,6 +312,7 @@ class InternalTests(unittest.TestCase):
self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out', inputs[1] + '.ok', 'dir']) self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out', inputs[1] + '.ok', 'dir'])
# Many inputs, can't use @INPUT@ like this # Many inputs, can't use @INPUT@ like this
cmd = ['@INPUT@.out', 'ordinary', 'strings'] cmd = ['@INPUT@.out', 'ordinary', 'strings']
self.assertRaises(ME, substfunc, cmd, d)
# Not enough inputs # Not enough inputs
cmd = ['@INPUT2@.out', 'ordinary', 'strings'] cmd = ['@INPUT2@.out', 'ordinary', 'strings']
self.assertRaises(ME, substfunc, cmd, d) self.assertRaises(ME, substfunc, cmd, d)
@ -853,7 +859,6 @@ class AllPlatformTests(BasePlatformTests):
env = Environment(testdir, self.builddir, self.meson_command, env = Environment(testdir, self.builddir, self.meson_command,
get_fake_options(self.prefix), []) get_fake_options(self.prefix), [])
for lang, evar in langs: for lang, evar in langs:
evalue = None
# Detect with evar and do sanity checks on that # Detect with evar and do sanity checks on that
if evar in os.environ: if evar in os.environ:
ecc = getattr(env, 'detect_{}_compiler'.format(lang))(False) ecc = getattr(env, 'detect_{}_compiler'.format(lang))(False)

@ -1,5 +1,7 @@
project('comparison', 'c') project('comparison', 'c')
# Compare equality of strings
var1 = 'foo' var1 = 'foo'
var2 = 'bar' var2 = 'bar'
@ -31,3 +33,96 @@ test('equalfalse', exe1)
test('equaltrue', exe2) test('equaltrue', exe2)
test('nequaltrue', exe3) test('nequaltrue', exe3)
test('nequalfalse', exe4) test('nequalfalse', exe4)
# Non-equality comparisons
var3 = 3
var4 = 4
if var3 < var4
exe5 = executable('prog5', 'prog.c')
else
exe5 = executable('broken', 'broken.c')
endif
if var3 < var3
exe6 = executable('broken', 'broken.c')
else
exe6 = executable('prog6', 'prog.c')
endif
if var4 > var3
exe7 = executable('prog7', 'prog.c')
else
exe7 = executable('broken', 'broken.c')
endif
if var3 > var3
exe8 = executable('broken', 'broken.c')
else
exe8 = executable('prog8', 'prog.c')
endif
if var4 <= var3
exe9 = executable('broken', 'broken.c')
else
exe9 = executable('prog9', 'prog.c')
endif
if var3 <= var3
exe10 = executable('prog10', 'prog.c')
else
exe10 = executable('broken', 'broken.c')
endif
if var3 >= var4
exe11 = executable('broken', 'broken.c')
else
exe11 = executable('prog11', 'prog.c')
endif
if var3 >= var3
exe12 = executable('prog12', 'prog.c')
else
exe12 = executable('broken', 'broken.c')
endif
test('lttrue', exe5)
test('ltfalse', exe6)
test('gttrue', exe7)
test('gtfalse', exe8)
test('lefalse', exe9)
test('letrue', exe10)
test('gefalse', exe11)
test('getrue', exe12)
# Non-elementary type comparisons
if exe1 == exe2
exe13 = executable('broken', 'broken.c')
else
exe13 = executable('prog13', 'prog.c')
endif
if exe1 == exe1
exe14 = executable('prog14', 'prog.c')
else
exe14 = executable('broken', 'broken.c')
endif
if exe1 != exe2
exe15 = executable('prog15', 'prog.c')
else
exe15 = executable('broken', 'broken.c')
endif
if exe1 != exe1
exe16 = executable('broken', 'broken.c')
else
exe16 = executable('prog16', 'prog.c')
endif
test('equalfalse', exe13)
test('equaltrue', exe14)
test('nequaltrue', exe15)
test('nequalfalse', exe16)

@ -0,0 +1,6 @@
project('executable comparison', 'c')
exe1 = executable('prog1', sources : 'prog.c')
exe2 = executable('prog2', sources : 'prog.c')
assert(exe1 < exe2, 'should fail')

@ -0,0 +1 @@
int main(int argc, char **argv) { return 0; }

@ -0,0 +1,7 @@
project('kwarg before arg', 'c')
# All of these should fail, though only the first one will error out if
# everything's working correctly.
assert([] < 'st', 'should fail')
assert([] < 1, 'should fail')
assert(2 < 'st', 'should fail')
Loading…
Cancel
Save