Cherry-picking - (rm python2 % add python3 .format) (#6725)

pull/5071/head
Michael Brockus 5 years ago committed by GitHub
parent 21e543fea8
commit 98ddd52ced
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 35
      mesonbuild/build.py
  2. 6
      mesonbuild/mdist.py
  3. 18
      mesonbuild/minstall.py
  4. 8
      mesonbuild/msetup.py
  5. 10
      mesonbuild/msubprojects.py
  6. 58
      mesonbuild/mtest.py

@ -341,9 +341,9 @@ class Target:
def __init__(self, name, subdir, subproject, build_by_default, for_machine: MachineChoice):
if has_path_sep(name):
# Fix failing test 53 when this becomes an error.
mlog.warning('''Target "%s" has a path separator in its name.
mlog.warning('''Target "{}" has a path separator in its name.
This is not supported, it can cause unexpected failures and will become
a hard error in the future.''' % name)
a hard error in the future.'''.format(name))
self.name = name
self.subdir = subdir
self.subproject = subproject
@ -502,7 +502,7 @@ class BuildTarget(Target):
self.check_unknown_kwargs(kwargs)
self.process_compilers()
if not any([self.sources, self.generated, self.objects, self.link_whole]):
raise InvalidArguments('Build target %s has no sources.' % name)
raise InvalidArguments('Build target {} has no sources.'.format(name))
self.process_compilers_late()
self.validate_sources()
self.validate_install(environment)
@ -530,8 +530,7 @@ class BuildTarget(Target):
if k not in known_kwargs:
unknowns.append(k)
if len(unknowns) > 0:
mlog.warning('Unknown keyword argument(s) in target %s: %s.' %
(self.name, ', '.join(unknowns)))
mlog.warning('Unknown keyword argument(s) in target {}: {}.'.format(self.name, ', '.join(unknowns)))
def process_objectlist(self, objects):
assert(isinstance(objects, list))
@ -756,7 +755,7 @@ class BuildTarget(Target):
raise MesonException('Object extraction arguments must be strings or Files.')
# FIXME: It could be a generated source
if src not in self.sources:
raise MesonException('Tried to extract unknown source %s.' % src)
raise MesonException('Tried to extract unknown source {}.'.format(src))
obj_src.append(src)
return ExtractedObjects(self, obj_src)
@ -901,7 +900,7 @@ This will become a hard error in a future Meson release.''')
assert(isinstance(i, File))
trial = os.path.join(environment.get_source_dir(), i.subdir, i.fname)
if not(os.path.isfile(trial)):
raise InvalidArguments('Tried to add non-existing extra file %s.' % i)
raise InvalidArguments('Tried to add non-existing extra file {}.'.format(i))
self.extra_files = extra_files
self.install_rpath = kwargs.get('install_rpath', '')
if not isinstance(self.install_rpath, str):
@ -915,7 +914,7 @@ This will become a hard error in a future Meson release.''')
raise InvalidArguments('Resource argument is not a string.')
trial = os.path.join(environment.get_source_dir(), self.subdir, r)
if not os.path.isfile(trial):
raise InvalidArguments('Tried to add non-existing resource %s.' % r)
raise InvalidArguments('Tried to add non-existing resource {}.'.format(r))
self.resources = resources
if 'name_prefix' in kwargs:
name_prefix = kwargs['name_prefix']
@ -964,8 +963,7 @@ This will become a hard error in a future Meson release.''')
if self.gnu_symbol_visibility != '':
permitted = ['default', 'internal', 'hidden', 'protected', 'inlineshidden']
if self.gnu_symbol_visibility not in permitted:
raise InvalidArguments('GNU symbol visibility arg %s not one of: %s',
self.symbol_visibility, ', '.join(permitted))
raise InvalidArguments('GNU symbol visibility arg {} not one of: {}'.format(self.symbol_visibility, ', '.join(permitted)))
def _extract_pic_pie(self, kwargs, arg):
# Check if we have -fPIC, -fpic, -fPIE, or -fpie in cflags
@ -1146,7 +1144,7 @@ You probably should put it in link_with instead.''')
return
elif len(pchlist) == 1:
if not environment.is_header(pchlist[0]):
raise InvalidArguments('PCH argument %s is not a header.' % pchlist[0])
raise InvalidArguments('PCH argument {} is not a header.'.format(pchlist[0]))
elif len(pchlist) == 2:
if environment.is_header(pchlist[0]):
if not environment.is_source(pchlist[1]):
@ -1156,7 +1154,7 @@ You probably should put it in link_with instead.''')
raise InvalidArguments('PCH definition must contain one header and at most one source.')
pchlist = [pchlist[1], pchlist[0]]
else:
raise InvalidArguments('PCH argument %s is of unknown type.' % pchlist[0])
raise InvalidArguments('PCH argument {} is of unknown type.'.format(pchlist[0]))
if (os.path.dirname(pchlist[0]) != os.path.dirname(pchlist[1])):
raise InvalidArguments('PCH files must be stored in the same folder.')
@ -1168,7 +1166,7 @@ You probably should put it in link_with instead.''')
if not isinstance(f, str):
raise MesonException('PCH arguments must be strings.')
if not os.path.isfile(os.path.join(self.environment.source_dir, self.subdir, f)):
raise MesonException('File %s does not exist.' % f)
raise MesonException('File {} does not exist.'.format(f))
self.pch[language] = pchlist
def add_include_dirs(self, args, set_is_system: T.Optional[str] = None):
@ -2018,8 +2016,7 @@ class CustomTarget(Target):
if k not in CustomTarget.known_kwargs:
unknowns.append(k)
if len(unknowns) > 0:
mlog.warning('Unknown keyword arguments in target %s: %s' %
(self.name, ', '.join(unknowns)))
mlog.warning('Unknown keyword arguments in target {}: {}'.format(self.name, ', '.join(unknowns)))
def get_default_install_dir(self, environment):
return None
@ -2169,8 +2166,8 @@ class CustomTarget(Target):
while hasattr(ed, 'held_object'):
ed = ed.held_object
if not isinstance(ed, (CustomTarget, BuildTarget)):
raise InvalidArguments('Can only depend on toplevel targets: custom_target or build_target (executable or a library) got: %s(%s)'
% (type(ed), ed))
raise InvalidArguments('Can only depend on toplevel targets: custom_target or build_target (executable or a library) got: {}({})'
.format(type(ed), ed))
self.extra_depends.append(ed)
for i in depend_files:
if isinstance(i, (File, str)):
@ -2310,10 +2307,10 @@ class Jar(BuildTarget):
super().__init__(name, subdir, subproject, for_machine, sources, objects, environment, kwargs)
for s in self.sources:
if not s.endswith('.java'):
raise InvalidArguments('Jar source %s is not a java file.' % s)
raise InvalidArguments('Jar source {} is not a java file.'.format(s))
for t in self.link_targets:
if not isinstance(t, Jar):
raise InvalidArguments('Link target %s is not a jar target.' % t)
raise InvalidArguments('Link target {} is not a jar target.'.format(t))
self.filename = self.name + '.jar'
self.outputs = [self.filename]
self.java_args = kwargs.get('java_args', [])

@ -46,7 +46,7 @@ def create_hash(fname):
m = hashlib.sha256()
m.update(open(fname, 'rb').read())
with open(hashname, 'w') as f:
f.write('%s %s\n' % (m.hexdigest(), os.path.basename(fname)))
f.write('{} {}\n'.format(m.hexdigest(), os.path.basename(fname)))
def del_gitfiles(dirname):
@ -195,7 +195,7 @@ def run_dist_steps(meson_command, unpacked_src_dir, builddir, installdir, ninja_
return 0
def check_dist(packagename, meson_command, extra_meson_args, bld_root, privdir):
print('Testing distribution package %s' % packagename)
print('Testing distribution package {}'.format(packagename))
unpackdir = os.path.join(privdir, 'dist-unpack')
builddir = os.path.join(privdir, 'dist-build')
installdir = os.path.join(privdir, 'dist-install')
@ -220,7 +220,7 @@ def check_dist(packagename, meson_command, extra_meson_args, bld_root, privdir):
windows_proof_rmtree(unpackdir)
windows_proof_rmtree(builddir)
windows_proof_rmtree(installdir)
print('Distribution package %s tested' % packagename)
print('Distribution package {} tested'.format(packagename))
return ret
def determine_archives_to_generate(options):

@ -248,7 +248,7 @@ class Installer:
raise RuntimeError('Destination {!r} already exists and is not '
'a file'.format(to_file))
if self.should_preserve_existing_file(from_file, to_file):
append_to_log(self.lf, '# Preserving old file %s\n' % to_file)
append_to_log(self.lf, '# Preserving old file {}\n'.format(to_file))
self.preserved_file_count += 1
return False
os.remove(to_file)
@ -257,7 +257,7 @@ class Installer:
dirmaker, outdir = makedirs
# Create dirs if needed
dirmaker.makedirs(outdir, exist_ok=True)
self.log('Installing %s to %s' % (from_file, outdir))
self.log('Installing {} to {}'.format(from_file, outdir))
if os.path.islink(from_file):
if not os.path.exists(from_file):
# Dangling symlink. Replicate as is.
@ -299,9 +299,9 @@ class Installer:
each element of the set is a path relative to src_dir.
'''
if not os.path.isabs(src_dir):
raise ValueError('src_dir must be absolute, got %s' % src_dir)
raise ValueError('src_dir must be absolute, got {}'.format(src_dir))
if not os.path.isabs(dst_dir):
raise ValueError('dst_dir must be absolute, got %s' % dst_dir)
raise ValueError('dst_dir must be absolute, got {}'.format(dst_dir))
if exclude is not None:
exclude_files, exclude_dirs = exclude
else:
@ -319,7 +319,7 @@ class Installer:
if os.path.isdir(abs_dst):
continue
if os.path.exists(abs_dst):
print('Tried to copy directory %s but a file of that name already exists.' % abs_dst)
print('Tried to copy directory {} but a file of that name already exists.'.format(abs_dst))
sys.exit(1)
data.dirmaker.makedirs(abs_dst)
shutil.copystat(abs_src, abs_dst)
@ -331,7 +331,7 @@ class Installer:
continue
abs_dst = os.path.join(dst_dir, filepart)
if os.path.isdir(abs_dst):
print('Tried to copy file %s but a directory of that name already exists.' % abs_dst)
print('Tried to copy file {} but a directory of that name already exists.'.format(abs_dst))
sys.exit(1)
parent_dir = os.path.dirname(abs_dst)
if not os.path.isdir(parent_dir):
@ -379,7 +379,7 @@ class Installer:
for (src_dir, dst_dir, mode, exclude) in d.install_subdirs:
self.did_install_something = True
full_dst_dir = get_destdir_path(d, dst_dir)
self.log('Installing subdir %s to %s' % (src_dir, full_dst_dir))
self.log('Installing subdir {} to {}'.format(src_dir, full_dst_dir))
d.dirmaker.makedirs(full_dst_dir, exist_ok=True)
self.do_copydir(d, src_dir, full_dst_dir, exclude, mode)
@ -473,8 +473,8 @@ class Installer:
ps, stdo, stde = Popen_safe(d.strip_bin + [outname])
if ps.returncode != 0:
print('Could not strip file.\n')
print('Stdout:\n%s\n' % stdo)
print('Stderr:\n%s\n' % stde)
print('Stdout:\n{}\n'.format(stdo))
print('Stderr:\n{}\n'.format(stde))
sys.exit(1)
if fname.endswith('.js'):
# Emscripten outputs js files and optionally a wasm file.

@ -118,18 +118,18 @@ class MesonApp:
if not os.path.exists(ndir2):
os.makedirs(ndir2)
if not stat.S_ISDIR(os.stat(ndir1).st_mode):
raise MesonException('%s is not a directory' % dir1)
raise MesonException('{} is not a directory'.format(dir1))
if not stat.S_ISDIR(os.stat(ndir2).st_mode):
raise MesonException('%s is not a directory' % dir2)
raise MesonException('{} is not a directory'.format(dir2))
if os.path.samefile(dir1, dir2):
raise MesonException('Source and build directories must not be the same. Create a pristine build directory.')
if self.has_build_file(ndir1):
if self.has_build_file(ndir2):
raise MesonException('Both directories contain a build file %s.' % environment.build_filename)
raise MesonException('Both directories contain a build file {}.'.format(environment.build_filename))
return ndir1, ndir2
if self.has_build_file(ndir2):
return ndir2, ndir1
raise MesonException('Neither directory contains a build file %s.' % environment.build_filename)
raise MesonException('Neither directory contains a build file {}.'.format(environment.build_filename))
def validate_dirs(self, dir1: str, dir2: str, reconfigure: bool, wipe: bool) -> T.Tuple[str, str]:
(src_dir, build_dir) = self.validate_core_dirs(dir1, dir2)

@ -129,7 +129,7 @@ def update_svn(wrap, repo_dir, options):
subprocess.check_call(['svn', 'update', '-r', revno], cwd=repo_dir)
def update(wrap, repo_dir, options):
mlog.log('Updating %s...' % wrap.name)
mlog.log('Updating {}...'.format(wrap.name))
if wrap.type == 'file':
update_file(wrap, repo_dir, options)
elif wrap.type == 'git':
@ -148,7 +148,7 @@ def checkout(wrap, repo_dir, options):
cmd = ['checkout', branch_name, '--']
if options.b:
cmd.insert(1, '-b')
mlog.log('Checkout %s in %s...' % (branch_name, wrap.name))
mlog.log('Checkout {} in {}...'.format(branch_name, wrap.name))
try:
git_output(cmd, repo_dir)
git_show(repo_dir)
@ -157,7 +157,7 @@ def checkout(wrap, repo_dir, options):
mlog.log(' -> ', mlog.red(out))
def download(wrap, repo_dir, options):
mlog.log('Download %s...' % wrap.name)
mlog.log('Download {}...'.format(wrap.name))
if os.path.isdir(repo_dir):
mlog.log(' -> Already downloaded')
return
@ -169,7 +169,7 @@ def download(wrap, repo_dir, options):
mlog.log(' ->', mlog.red(str(e)))
def foreach(wrap, repo_dir, options):
mlog.log('Executing command in %s' % repo_dir)
mlog.log('Executing command in {}'.format(repo_dir))
if not os.path.isdir(repo_dir):
mlog.log(' -> Not downloaded yet')
return
@ -179,7 +179,7 @@ def foreach(wrap, repo_dir, options):
cwd=repo_dir).decode()
mlog.log(out, end='')
except subprocess.CalledProcessError as e:
err_message = "Command '%s' returned non-zero exit status %d." % (" ".join(e.cmd), e.returncode)
err_message = "Command '{}' returned non-zero exit status {}.".format(" ".join(e.cmd), e.returncode)
out = e.output.decode()
mlog.log(' -> ', mlog.red(err_message))
mlog.log(out, end='')

@ -67,7 +67,7 @@ def determine_worker_count() -> int:
try:
num_workers = int(os.environ[varname])
except ValueError:
print('Invalid value in %s, using 1 thread.' % varname)
print('Invalid value in {}, using 1 thread.'.format(varname))
num_workers = 1
else:
try:
@ -136,20 +136,20 @@ def returncode_to_status(retcode: int) -> str:
signame = signal.Signals(signum).name
except ValueError:
signame = 'SIGinvalid'
return '(killed by signal %d %s)' % (signum, signame)
return '(killed by signal {} {})'.format(signum, signame)
if retcode <= 128:
return '(exit status %d)' % (retcode,)
return '(exit status {})'.format((retcode,))
signum = retcode - 128
try:
signame = signal.Signals(signum).name
except ValueError:
signame = 'SIGinvalid'
return '(exit status %d or signal %d %s)' % (retcode, signum, signame)
return '(exit status {} or signal {} {})'.format(retcode, signum, signame)
def env_tuple_to_str(env: T.Iterable[T.Tuple[str, str]]) -> str:
return ''.join(["%s='%s' " % (k, v) for k, v in env])
return ''.join(["{}='{}' ".format(k, v) for k, v in env])
class TestException(MesonException):
@ -204,7 +204,7 @@ class TAPParser:
yield self.Test(num, name, TestResult.UNEXPECTEDPASS if ok else TestResult.EXPECTEDFAIL, explanation)
return
else:
yield self.Error('invalid directive "%s"' % (directive,))
yield self.Error('invalid directive "{}"'.format(directive,))
yield self.Test(num, name, TestResult.OK if ok else TestResult.FAIL, explanation)
@ -304,16 +304,16 @@ class TAPParser:
if len(line) == 0:
continue
yield self.Error('unexpected input at line %d' % (lineno,))
yield self.Error('unexpected input at line {}'.format((lineno,)))
if state == self._YAML:
yield self.Error('YAML block not terminated (started on line {})'.format(yaml_lineno))
if not bailed_out and plan and num_tests != plan.count:
if num_tests < plan.count:
yield self.Error('Too few tests run (expected %d, got %d)' % (plan.count, num_tests))
yield self.Error('Too few tests run (expected {}, got {})'.format(plan.count, num_tests))
else:
yield self.Error('Too many tests run (expected %d, got %d)' % (plan.count, num_tests))
yield self.Error('Too many tests run (expected {}, got {})'.format(plan.count, num_tests))
class TestRun:
@ -358,7 +358,7 @@ class TestRun:
if returncode != 0:
res = TestResult.ERROR
stde += '\n(test program exited with status code %d)' % (returncode,)
stde += '\n(test program exited with status code {})'.format(returncode,)
if res is None:
# Now determine the overall result of the test based on the outcome of the subcases
@ -562,7 +562,7 @@ class SingleTestRunner:
print('{} time out (After {} seconds)'.format(self.test.name, timeout))
timed_out = True
except KeyboardInterrupt:
mlog.warning('CTRL-C detected while running %s' % (self.test.name))
mlog.warning('CTRL-C detected while running {}'.format(self.test.name))
kill_test = True
finally:
if self.options.gdb:
@ -671,12 +671,12 @@ class TestHarness:
def merge_suite_options(self, options: argparse.Namespace, test: 'TestSerialisation') -> T.Dict[str, str]:
if ':' in options.setup:
if options.setup not in self.build_data.test_setups:
sys.exit("Unknown test setup '%s'." % options.setup)
sys.exit("Unknown test setup '{}'.".format(options.setup))
current = self.build_data.test_setups[options.setup]
else:
full_name = test.project_name + ":" + options.setup
if full_name not in self.build_data.test_setups:
sys.exit("Test setup '%s' not found from project '%s'." % (options.setup, test.project_name))
sys.exit("Test setup '{}' not found from project '{}'.".format(options.setup, test.project_name))
current = self.build_data.test_setups[full_name]
if not options.gdb:
options.gdb = current.gdb
@ -722,17 +722,16 @@ class TestHarness:
def print_stats(self, numlen: int, tests: T.List['TestSerialisation'],
name: str, result: TestRun, i: int) -> None:
startpad = ' ' * (numlen - len('%d' % (i + 1)))
num = '%s%d/%d' % (startpad, i + 1, len(tests))
startpad = ' ' * (numlen - len('{}'.format(i + 1)))
num = '{}{}/{}'.format(startpad, i + 1, len(tests))
padding1 = ' ' * (38 - len(name))
padding2 = ' ' * (8 - len(result.res.value))
status = ''
if result.res is TestResult.FAIL:
status = returncode_to_status(result.returncode)
result_str = '%s %s %s%s%s%5.2f s %s' % \
(num, name, padding1, result.res.value, padding2, result.duration,
status)
result_str = '{} {} {}{}{}{:5} s {}'.format(num, name, padding1, result.res.value,
padding2, result.duration, status)
ok_statuses = (TestResult.OK, TestResult.EXPECTEDFAIL)
bad_statuses = (TestResult.FAIL, TestResult.TIMEOUT, TestResult.UNEXPECTEDPASS,
TestResult.ERROR)
@ -758,14 +757,14 @@ class TestHarness:
def print_summary(self) -> None:
msg = '''
Ok: %4d
Expected Fail: %4d
Fail: %4d
Unexpected Pass: %4d
Skipped: %4d
Timeout: %4d
''' % (self.success_count, self.expectedfail_count, self.fail_count,
self.unexpectedpass_count, self.skip_count, self.timeout_count)
Ok: {:<4}
Expected Fail: {:<4}
Fail: {:<4}
Unexpected Pass: {:<4}
Skipped: {:<4}
Timeout: {:<4}
'''.format(self.success_count, self.expectedfail_count, self.fail_count,
self.unexpectedpass_count, self.skip_count, self.timeout_count)
print(msg)
if self.logfile:
self.logfile.write(msg)
@ -891,8 +890,7 @@ Timeout: %4d
self.jsonlogfile = open(self.jsonlogfilename, 'w', encoding='utf-8', errors='replace')
self.logfile = open(self.logfilename, 'w', encoding='utf-8', errors='surrogateescape')
self.logfile.write('Log of Meson test suite run on %s\n\n'
% datetime.datetime.now().isoformat())
self.logfile.write('Log of Meson test suite run on {}\n\n'.format(datetime.datetime.now().isoformat()))
inherit_env = env_tuple_to_str(os.environ.items())
self.logfile.write('Inherited environment: {}\n\n'.format(inherit_env))
@ -922,7 +920,7 @@ Timeout: %4d
def run_tests(self, tests: T.List['TestSerialisation']) -> None:
executor = None
futures = [] # type: T.List[T.Tuple[conc.Future[TestRun], int, T.List[TestSerialisation], str, int]]
numlen = len('%d' % len(tests))
numlen = len('{}'.format(len(tests)))
self.open_log_files()
startdir = os.getcwd()
if self.options.wd:
@ -956,7 +954,7 @@ Timeout: %4d
self.print_collected_logs()
if self.logfilename:
print('Full log written to %s' % self.logfilename)
print('Full log written to {}'.format(self.logfilename))
finally:
os.chdir(startdir)

Loading…
Cancel
Save