Use os.path: basename() and dirname() instead of split()

According to Python documentation[1] dirname and basename
are defined as follows:
    os.path.dirname() = os.path.split()[0]
    os.path.basename() = os.path.split()[1]
For the purpose of better readability split() is replaced
by appropriate function if only one part of returned tuple
is used.

[1]: https://docs.python.org/3/library/os.path.html#os.path.split
pull/2842/merge
Aleksey Filippov 7 years ago committed by Jussi Pakkanen
parent 4e5ad57161
commit 2cf85ae16f
  1. 2
      mesonbuild/backend/backends.py
  2. 16
      mesonbuild/backend/ninjabackend.py
  3. 2
      mesonbuild/backend/vs2010backend.py
  4. 2
      mesonbuild/backend/xcodebackend.py
  5. 12
      mesonbuild/build.py
  6. 12
      mesonbuild/compilers/c.py
  7. 6
      mesonbuild/compilers/compilers.py
  8. 2
      mesonbuild/compilers/cpp.py
  9. 2
      mesonbuild/compilers/fortran.py
  10. 2
      mesonbuild/environment.py
  11. 4
      mesonbuild/interpreter.py
  12. 6
      mesonbuild/mesonlib.py
  13. 4
      mesonbuild/mintro.py
  14. 4
      mesonbuild/modules/qt.py
  15. 2
      mesonbuild/mtest.py
  16. 2
      mesonbuild/scripts/gettext.py
  17. 16
      mesonbuild/scripts/meson_install.py
  18. 4
      mesonbuild/wrap/wraptool.py

@ -322,7 +322,7 @@ class Backend:
continue
if os.path.splitext(libpath)[1] not in ['.dll', '.lib', '.so']:
continue
absdir = os.path.split(libpath)[0]
absdir = os.path.dirname(libpath)
rel_to_src = absdir[len(self.environment.get_source_dir()) + 1:]
assert(not os.path.isabs(rel_to_src))
paths.append(os.path.join(self.build_to_src, rel_to_src))

@ -823,7 +823,7 @@ int dummy;
if subdir is None:
subdir = os.path.join(manroot, 'man' + num)
srcabs = f.absolute_path(self.environment.get_source_dir(), self.environment.get_build_dir())
dstabs = os.path.join(subdir, os.path.split(f.fname)[1] + '.gz')
dstabs = os.path.join(subdir, os.path.basename(f.fname) + '.gz')
i = [srcabs, dstabs]
d.man.append(i)
@ -836,7 +836,7 @@ int dummy;
subdir = de.install_dir
for f in de.sources:
assert(isinstance(f, mesonlib.File))
plain_f = os.path.split(f.fname)[1]
plain_f = os.path.basename(f.fname)
dstabs = os.path.join(subdir, plain_f)
i = [f.absolute_path(srcdir, builddir), dstabs, de.install_mode]
d.data.append(i)
@ -1278,7 +1278,7 @@ int dummy;
# Target names really should not have slashes in them, but
# unfortunately we did not check for that and some downstream projects
# now have them. Once slashes are forbidden, remove this bit.
target_slashname_workaround_dir = os.path.join(os.path.split(target.name)[0],
target_slashname_workaround_dir = os.path.join(os.path.dirname(target.name),
self.get_target_dir(target))
else:
target_slashname_workaround_dir = self.get_target_dir(target)
@ -1401,7 +1401,7 @@ int dummy;
objects = [] # Relative to swift invocation dir
rel_objects = [] # Relative to build.ninja
for i in abssrc + abs_generated:
base = os.path.split(i)[1]
base = os.path.basename(i)
oname = os.path.splitext(base)[0] + '.o'
objects.append(oname)
rel_objects.append(os.path.join(self.get_target_private_dir(target), oname))
@ -1928,7 +1928,7 @@ rule FORTRAN_DEP_HACK
# Check if a source uses a module it exports itself.
# Potential bug if multiple targets have a file with
# the same name.
if mod_source_file.fname == os.path.split(src)[1]:
if mod_source_file.fname == os.path.basename(src):
continue
mod_name = compiler.module_name_to_filename(
usematch.group(1))
@ -2271,7 +2271,7 @@ rule FORTRAN_DEP_HACK
commands = []
commands += self.generate_basic_compiler_args(target, compiler)
just_name = os.path.split(header)[1]
just_name = os.path.basename(header)
(objname, pch_args) = compiler.gen_pch_args(just_name, source, dst)
commands += pch_args
commands += self.get_compile_debugfile_args(compiler, target, objname)
@ -2281,7 +2281,7 @@ rule FORTRAN_DEP_HACK
def generate_gcc_pch_command(self, target, compiler, pch):
commands = self._generate_single_compile(target, compiler)
dst = os.path.join(self.get_target_private_dir(target),
os.path.split(pch)[-1] + '.' + compiler.get_pch_suffix())
os.path.basename(pch) + '.' + compiler.get_pch_suffix())
dep = dst + '.' + compiler.get_depfile_suffix()
return commands, dep, dst, [] # Gcc does not create an object file during pch generation.
@ -2476,7 +2476,7 @@ rule FORTRAN_DEP_HACK
# unfortunately we did not check for that and some downstream projects
# now have them. Once slashes are forbidden, remove this bit.
target_slashname_workaround_dir = os.path.join(
os.path.split(target.name)[0],
os.path.dirname(target.name),
self.get_target_dir(target))
else:
target_slashname_workaround_dir = self.get_target_dir(target)

@ -1034,7 +1034,7 @@ class Vs2010Backend(backends.Backend):
pch_file = ET.SubElement(inc_cl, 'PrecompiledHeaderFile')
# MSBuild searches for the header relative from the implementation, so we have to use
# just the file name instead of the relative path to the file.
pch_file.text = os.path.split(header)[1]
pch_file.text = os.path.basename(header)
self.add_additional_options(lang, inc_cl, file_args)
self.add_preprocessor_defines(lang, inc_cl, file_defines)
self.add_include_dirs(lang, inc_cl, file_inc_dirs)

@ -311,7 +311,7 @@ class XCodeBackend(backends.Backend):
for fname, idval in self.filemap.items():
fullpath = os.path.join(self.environment.get_source_dir(), fname)
xcodetype = self.get_xcodetype(fname)
name = os.path.split(fname)[-1]
name = os.path.basename(fname)
path = fname
self.ofile.write(src_templ % (idval, fullpath, xcodetype, name, path))
target_templ = '%s /* %s */ = { isa = PBXFileReference; explicitFileType = "%s"; path = %s; refType = %d; sourceTree = BUILT_PRODUCTS_DIR; };\n'

@ -1065,7 +1065,7 @@ class Generator:
depfile = kwargs['depfile']
if not isinstance(depfile, str):
raise InvalidArguments('Depfile must be a string.')
if os.path.split(depfile)[1] != depfile:
if os.path.basename(depfile) != depfile:
raise InvalidArguments('Depfile must be a plain filename without a subdirectory.')
self.depfile = depfile
if 'capture' in kwargs:
@ -1075,7 +1075,7 @@ class Generator:
self.capture = capture
def get_base_outnames(self, inname):
plainname = os.path.split(inname)[1]
plainname = os.path.basename(inname)
basename = os.path.splitext(plainname)[0]
bases = [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.outputs]
return bases
@ -1083,12 +1083,12 @@ class Generator:
def get_dep_outname(self, inname):
if self.depfile is None:
raise InvalidArguments('Tried to get dep name for rule that does not have dependency file defined.')
plainname = os.path.split(inname)[1]
plainname = os.path.basename(inname)
basename = os.path.splitext(plainname)[0]
return self.depfile.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
def get_arglist(self, inname):
plainname = os.path.split(inname)[1]
plainname = os.path.basename(inname)
basename = os.path.splitext(plainname)[0]
return [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.arglist]
@ -1130,7 +1130,7 @@ class GeneratedList:
in_abs = infile.absolute_path(state.environment.source_dir, state.environment.build_dir)
assert(os.path.isabs(self.preserve_path_from))
rel = os.path.relpath(in_abs, self.preserve_path_from)
path_segment = os.path.split(rel)[0]
path_segment = os.path.dirname(rel)
for of in outfiles:
result.append(os.path.join(path_segment, of))
return result
@ -1659,7 +1659,7 @@ class CustomTarget(Target):
depfile = kwargs['depfile']
if not isinstance(depfile, str):
raise InvalidArguments('Depfile must be a string.')
if os.path.split(depfile)[1] != depfile:
if os.path.basename(depfile) != depfile:
raise InvalidArguments('Depfile must be a plain filename without a subdirectory.')
self.depfile = depfile
self.command = self.flatten_command(kwargs['command'])

@ -172,10 +172,10 @@ class CCompiler(Compiler):
return ' '.join(self.exelist)
def get_pch_use_args(self, pch_dir, header):
return ['-include', os.path.split(header)[-1]]
return ['-include', os.path.basename(header)]
def get_pch_name(self, header_name):
return os.path.split(header_name)[-1] + '.' + self.get_pch_suffix()
return os.path.basename(header_name) + '.' + self.get_pch_suffix()
def get_linker_search_args(self, dirname):
return ['-L' + dirname]
@ -882,7 +882,7 @@ class GnuCCompiler(GnuCompiler, CCompiler):
return ['-shared']
def get_pch_use_args(self, pch_dir, header):
return ['-fpch-preprocess', '-include', os.path.split(header)[-1]]
return ['-fpch-preprocess', '-include', os.path.basename(header)]
class IntelCCompiler(IntelCompiler, CCompiler):
@ -961,13 +961,13 @@ class VisualStudioCCompiler(CCompiler):
return 'pch'
def get_pch_name(self, header):
chopped = os.path.split(header)[-1].split('.')[:-1]
chopped = os.path.basename(header).split('.')[:-1]
chopped.append(self.get_pch_suffix())
pchname = '.'.join(chopped)
return pchname
def get_pch_use_args(self, pch_dir, header):
base = os.path.split(header)[-1]
base = os.path.basename(header)
pchname = self.get_pch_name(header)
return ['/FI' + base, '/Yu' + base, '/Fp' + os.path.join(pch_dir, pchname)]
@ -1094,7 +1094,7 @@ class VisualStudioCCompiler(CCompiler):
mlog.debug('Running VS compile:')
mlog.debug('Command line: ', ' '.join(commands))
mlog.debug('Code:\n', code)
p, stdo, stde = Popen_safe(commands, cwd=os.path.split(srcname)[0])
p, stdo, stde = Popen_safe(commands, cwd=os.path.dirname(srcname))
if p.returncode != 0:
return False
return not(warning_text in stde or warning_text in stdo)

@ -1040,7 +1040,7 @@ class GnuCompiler:
return 'gch'
def split_shlib_to_parts(self, fname):
return os.path.split(fname)[0], fname
return os.path.dirname(fname), fname
def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
return get_gcc_soname_args(self.gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module)
@ -1188,10 +1188,10 @@ class IntelCompiler:
self.lang_header, '-include', header, '-x', 'none']
def get_pch_name(self, header_name):
return os.path.split(header_name)[-1] + '.' + self.get_pch_suffix()
return os.path.basename(header_name) + '.' + self.get_pch_suffix()
def split_shlib_to_parts(self, fname):
return os.path.split(fname)[0], fname
return os.path.dirname(fname), fname
def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
if self.icc_type == ICC_STANDARD:

@ -130,7 +130,7 @@ class GnuCPPCompiler(GnuCompiler, CPPCompiler):
return []
def get_pch_use_args(self, pch_dir, header):
return ['-fpch-preprocess', '-include', os.path.split(header)[-1]]
return ['-fpch-preprocess', '-include', os.path.basename(header)]
class IntelCPPCompiler(IntelCompiler, CPPCompiler):

@ -91,7 +91,7 @@ end program prog
return gnulike_buildtype_linker_args[buildtype]
def split_shlib_to_parts(self, fname):
return os.path.split(fname)[0], fname
return os.path.dirname(fname), fname
def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
return get_gcc_soname_args(self.gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module)

@ -594,7 +594,7 @@ class Environment:
return self.scratch_dir
def get_depfixer(self):
path = os.path.split(__file__)[0]
path = os.path.dirname(__file__)
return os.path.join(path, 'depfixer.py')
def detect_objc_compiler(self, want_cross):

@ -2739,7 +2739,7 @@ root and issuing %s.
values = mesonlib.get_filenames_templates_dict([ifile_abs], None)
outputs = mesonlib.substitute_values([output], values)
output = outputs[0]
if os.path.split(output)[0] != '':
if os.path.dirname(output) != '':
raise InterpreterException('Output file name must not contain a subdirectory.')
(ofile_path, ofile_fname) = os.path.split(os.path.join(self.subdir, output))
ofile_abs = os.path.join(self.environment.build_dir, ofile_path, ofile_fname)
@ -2977,7 +2977,7 @@ different subdirectory.
norm = os.path.relpath(norm, self.environment.source_dir)
assert(not os.path.isabs(norm))
(num_sps, sproj_name) = self.evaluate_subproject_info(norm, self.subproject_dir)
plain_filename = os.path.split(norm)[-1]
plain_filename = os.path.basename(norm)
if num_sps == 0:
if self.subproject == '':
return

@ -857,7 +857,7 @@ def get_filenames_templates_dict(inputs, outputs):
values['@INPUT{}@'.format(ii)] = vv
if len(inputs) == 1:
# Just one value, substitute @PLAINNAME@ and @BASENAME@
values['@PLAINNAME@'] = plain = os.path.split(inputs[0])[1]
values['@PLAINNAME@'] = plain = os.path.basename(inputs[0])
values['@BASENAME@'] = os.path.splitext(plain)[0]
if outputs:
# Gather values derived from the outputs, similar to above.
@ -865,7 +865,7 @@ def get_filenames_templates_dict(inputs, outputs):
for (ii, vv) in enumerate(outputs):
values['@OUTPUT{}@'.format(ii)] = vv
# Outdir should be the same for all outputs
values['@OUTDIR@'] = os.path.split(outputs[0])[0]
values['@OUTDIR@'] = os.path.dirname(outputs[0])
# Many external programs fail on empty arguments.
if values['@OUTDIR@'] == '':
values['@OUTDIR@'] = '.'
@ -895,7 +895,7 @@ def detect_subprojects(spdir_name, current_dir='', result=None):
if not os.path.exists(spdir):
return result
for trial in glob(os.path.join(spdir, '*')):
basename = os.path.split(trial)[1]
basename = os.path.basename(trial)
if trial == 'packagecache':
continue
append_this = True

@ -49,14 +49,14 @@ parser.add_argument('builddir', nargs='?', help='The build directory')
def determine_installed_path(target, installdata):
install_target = None
for i in installdata.targets:
if os.path.split(i[0])[1] == target.get_filename(): # FIXME, might clash due to subprojects.
if os.path.basename(i[0]) == target.get_filename(): # FIXME, might clash due to subprojects.
install_target = i
break
if install_target is None:
raise RuntimeError('Something weird happened. File a bug.')
fname = i[0]
outdir = i[1]
outname = os.path.join(installdata.prefix, outdir, os.path.split(fname)[-1])
outname = os.path.join(installdata.prefix, outdir, os.path.basename(fname))
# Normalize the path by using os.path.sep consistently, etc.
# Does not change the effective path.
return str(pathlib.PurePath(outname))

@ -73,7 +73,7 @@ class QtBaseModule:
def parse_qrc(self, state, fname):
abspath = os.path.join(state.environment.source_dir, state.subdir, fname)
relative_part = os.path.split(fname)[0]
relative_part = os.path.dirname(fname)
try:
tree = ET.parse(abspath)
root = tree.getroot()
@ -116,7 +116,7 @@ class QtBaseModule:
sources.append(res_target)
else:
for rcc_file in rcc_files:
basename = os.path.split(rcc_file)[1]
basename = os.path.basename(rcc_file)
name = 'qt' + str(self.qt_version) + '-' + basename.replace('.', '_')
rcc_kwargs = {'input': rcc_file,
'output': name + '.cpp',

@ -438,7 +438,7 @@ TIMEOUT: %4d
logfile_base = os.path.join(self.options.wd, 'meson-logs', self.options.logbase)
if self.options.wrapper:
namebase = os.path.split(self.get_wrapper()[0])[1]
namebase = os.path.basename(self.get_wrapper()[0])
elif self.options.setup:
namebase = self.options.setup

@ -81,7 +81,7 @@ def do_install(src_sub, bld_sub, dest, pkgname, langs):
srcfile = os.path.join(bld_sub, l + '.gmo')
outfile = os.path.join(dest, l, 'LC_MESSAGES',
pkgname + '.mo')
os.makedirs(os.path.split(outfile)[0], exist_ok=True)
os.makedirs(os.path.dirname(outfile), exist_ok=True)
shutil.copyfile(srcfile, outfile)
shutil.copystat(srcfile, outfile)
print('Installing %s to %s' % (srcfile, outfile))

@ -164,10 +164,10 @@ def do_copydir(data, src_prefix, src_dir, dst_dir, exclude):
print('Tried to copy file %s but a directory of that name already exists.' % abs_dst)
if os.path.exists(abs_dst):
os.unlink(abs_dst)
parent_dir = os.path.split(abs_dst)[0]
parent_dir = os.path.dirname(abs_dst)
if not os.path.isdir(parent_dir):
os.mkdir(parent_dir)
shutil.copystat(os.path.split(abs_src)[0], parent_dir)
shutil.copystat(os.path.dirname(abs_src), parent_dir)
shutil.copy2(abs_src, abs_dst, follow_symlinks=False)
append_to_log(abs_dst)
@ -211,7 +211,7 @@ def install_data(d):
fullfilename = i[0]
outfilename = get_destdir_path(d, i[1])
mode = i[2]
outdir = os.path.split(outfilename)[0]
outdir = os.path.dirname(outfilename)
d.dirmaker.makedirs(outdir, exist_ok=True)
print('Installing %s to %s' % (fullfilename, outdir))
do_copyfile(fullfilename, outfilename)
@ -221,7 +221,7 @@ def install_man(d):
for m in d.man:
full_source_filename = m[0]
outfilename = get_destdir_path(d, m[1])
outdir = os.path.split(outfilename)[0]
outdir = os.path.dirname(outfilename)
d.dirmaker.makedirs(outdir, exist_ok=True)
print('Installing %s to %s' % (full_source_filename, outdir))
if outfilename.endswith('.gz') and not full_source_filename.endswith('.gz'):
@ -238,7 +238,7 @@ def install_man(d):
def install_headers(d):
for t in d.headers:
fullfilename = t[0]
fname = os.path.split(fullfilename)[1]
fname = os.path.basename(fullfilename)
outdir = get_destdir_path(d, t[1])
outfilename = os.path.join(outdir, fname)
print('Installing %s to %s' % (fname, outdir))
@ -304,7 +304,7 @@ def install_targets(d):
for t in d.targets:
fname = check_for_stampfile(t[0])
outdir = get_destdir_path(d, t[1])
outname = os.path.join(outdir, os.path.split(fname)[-1])
outname = os.path.join(outdir, os.path.basename(fname))
aliases = t[2]
should_strip = t[3]
install_rpath = t[4]
@ -316,7 +316,7 @@ def install_targets(d):
do_copyfile(fname, outname)
if should_strip and d.strip_bin is not None:
if fname.endswith('.jar'):
print('Not stripping jar target:', os.path.split(fname)[1])
print('Not stripping jar target:', os.path.basename(fname))
continue
print('Stripping target {!r}'.format(fname))
ps, stdo, stde = Popen_safe(d.strip_bin + [outname])
@ -366,7 +366,7 @@ def run(args):
print('Installer script for Meson. Do not run on your own, mmm\'kay?')
print('meson_install.py [install info file]')
datafilename = args[0]
private_dir = os.path.split(datafilename)[0]
private_dir = os.path.dirname(datafilename)
log_dir = os.path.join(private_dir, '../meson-logs')
with open(os.path.join(log_dir, 'install-log.txt'), 'w') as lf:
install_log_file = lf

@ -150,7 +150,7 @@ def do_promotion(from_path, spdir_name):
assert(from_path.endswith('.wrap'))
shutil.copy(from_path, spdir_name)
elif os.path.isdir(from_path):
sproj_name = os.path.split(from_path)[1]
sproj_name = os.path.basename(from_path)
outputdir = os.path.join(spdir_name, sproj_name)
if os.path.exists(outputdir):
sys.exit('Output dir %s already exists. Will not overwrite.' % outputdir)
@ -178,7 +178,7 @@ def promote(argument):
def status():
print('Subproject status')
for w in glob('subprojects/*.wrap'):
name = os.path.split(w)[1][:-5]
name = os.path.basename(w)[:-5]
try:
(latest_branch, latest_revision) = get_latest_version(name)
except Exception:

Loading…
Cancel
Save