Skip to content

Commit

Permalink
Siimplify Python code with some ruff rules SIM
Browse files Browse the repository at this point in the history
  • Loading branch information
cclauss committed Jul 30, 2024
1 parent 2daf5f7 commit aa0a4ce
Show file tree
Hide file tree
Showing 72 changed files with 162 additions and 425 deletions.
5 changes: 1 addition & 4 deletions mesonbuild/arglist.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,10 +225,7 @@ def to_native(self, copy: bool = False) -> T.List[str]:
# needed by static libraries that are provided by object files or
# shared libraries.
self.flush_pre_post()
if copy:
new = self.copy()
else:
new = self
new = self.copy() if copy else self
return self.compiler.unix_args_to_native(new._container)

def append_direct(self, arg: str) -> None:
Expand Down
5 changes: 1 addition & 4 deletions mesonbuild/ast/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,10 +405,7 @@ def quick_resolve(n: BaseNode, loop_detect: T.Optional[T.List[str]] = None) -> T

def flatten_args(self, args_raw: T.Union[TYPE_var, T.Sequence[TYPE_var]], include_unknown_args: bool = False, id_loop_detect: T.Optional[T.List[str]] = None) -> T.List[TYPE_var]:
# Make sure we are always dealing with lists
if isinstance(args_raw, list):
args = args_raw
else:
args = [args_raw]
args = args_raw if isinstance(args_raw, list) else [args_raw]

flattened_args: T.List[TYPE_var] = []

Expand Down
15 changes: 3 additions & 12 deletions mesonbuild/backend/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,10 +324,7 @@ def get_target_debug_filename_abs(self, target: build.BuildTarget) -> T.Optional

def get_source_dir_include_args(self, target: build.BuildTarget, compiler: 'Compiler', *, absolute_path: bool = False) -> T.List[str]:
curdir = target.get_subdir()
if absolute_path:
lead = self.source_dir
else:
lead = self.build_to_src
lead = self.source_dir if absolute_path else self.build_to_src
tmppath = os.path.normpath(os.path.join(lead, curdir))
return compiler.get_include_args(tmppath, False)

Expand Down Expand Up @@ -506,10 +503,7 @@ def _flatten_object_list(self, target: build.BuildTarget,

@staticmethod
def is_swift_target(target: build.BuildTarget) -> bool:
for s in target.sources:
if s.endswith('swift'):
return True
return False
return any(s.endswith('swift') for s in target.sources)

def determine_swift_dep_dirs(self, target: build.BuildTarget) -> T.List[str]:
result: T.List[str] = []
Expand Down Expand Up @@ -708,10 +702,7 @@ def determine_linker_and_stdlib_args(self, target: build.BuildTarget) -> T.Tuple
@staticmethod
def _libdir_is_system(libdir: str, compilers: T.Mapping[str, 'Compiler'], env: 'Environment') -> bool:
libdir = os.path.normpath(libdir)
for cc in compilers.values():
if libdir in cc.get_library_dirs(env):
return True
return False
return any(libdir in cc.get_library_dirs(env) for cc in compilers.values())

def get_external_rpath_dirs(self, target: build.BuildTarget) -> T.Set[str]:
args: T.List[str] = []
Expand Down
59 changes: 15 additions & 44 deletions mesonbuild/backend/ninjabackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,7 @@ def get_rsp_threshold() -> int:
NINJA_QUOTE_VAR_PAT = re.compile(r"[$ \n]")

def ninja_quote(text: str, is_build_line: bool = False) -> str:
if is_build_line:
quote_re = NINJA_QUOTE_BUILD_PAT
else:
quote_re = NINJA_QUOTE_VAR_PAT
quote_re = NINJA_QUOTE_BUILD_PAT if is_build_line else NINJA_QUOTE_VAR_PAT
# Fast path for when no quoting is necessary
if not quote_re.search(text):
return text
Expand Down Expand Up @@ -295,10 +292,7 @@ def length_estimate(self, infiles: str, outfiles: str,
if m.start(1) != -1:
estimate -= m.end(1) - m.start(1)
chunk = m.group(1)
if chunk[1] == '{':
chunk = chunk[2:-1]
else:
chunk = chunk[1:]
chunk = chunk[2:-1] if chunk[1] == '{' else chunk[1:]
chunk = ninja_vars.get(chunk, []) # undefined ninja variables are empty
estimate += len(' '.join(chunk))

Expand Down Expand Up @@ -960,7 +954,7 @@ def generate_target(self, target):
# 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: T.List[File] = []
for rel_src in generated_sources.keys():
for rel_src in generated_sources:
raw_src = File.from_built_relative(rel_src)
if self.environment.is_source(rel_src):
if is_unity and self.get_target_source_can_unity(target, rel_src):
Expand Down Expand Up @@ -1100,9 +1094,7 @@ def should_use_dyndeps_for_target(self, target: 'build.BuildTarget') -> bool:
return False
if not mesonlib.current_vs_supports_modules():
return False
if mesonlib.version_compare(cpp.version, '<19.28.28617'):
return False
return True
return not mesonlib.version_compare(cpp.version, '<19.28.28617')

def generate_dependency_scan_target(self, target: build.BuildTarget,
compiled_sources: T.List[str],
Expand Down Expand Up @@ -1180,10 +1172,7 @@ def generate_custom_target(self, target: build.CustomTarget):
deps += self.get_target_depend_files(target)
if target.build_always_stale:
deps.append('PHONY')
if target.depfile is None:
rulename = 'CUSTOM_COMMAND'
else:
rulename = 'CUSTOM_COMMAND_DEP'
rulename = 'CUSTOM_COMMAND' if target.depfile is None else 'CUSTOM_COMMAND_DEP'
elem = NinjaBuildElement(self.all_outputs, ofilenames, rulename, srcs)
elem.add_dep(deps)
for d in target.extra_depends:
Expand All @@ -1197,10 +1186,7 @@ def generate_custom_target(self, target: build.CustomTarget):
feed=srcs[0] if target.feed else None,
env=target.env,
verbose=target.console)
if reason:
cmd_type = f' (wrapped by meson {reason})'
else:
cmd_type = ''
cmd_type = f' (wrapped by meson {reason})' if reason else ''
if target.depfile is not None:
depfile = target.get_dep_outname(elem.infilenames)
rel_dfile = os.path.join(self.get_target_dir(target), depfile)
Expand All @@ -1216,10 +1202,7 @@ def generate_custom_target(self, target: build.CustomTarget):
self.processed_targets.add(target.get_id())

def build_run_target_name(self, target):
if target.subproject != '':
subproject_prefix = f'{target.subproject}@@'
else:
subproject_prefix = ''
subproject_prefix = f'{target.subproject}@@' if target.subproject != '' else ''
return f'{subproject_prefix}{target.name}'

def generate_run_target(self, target: build.RunTarget):
Expand Down Expand Up @@ -1426,7 +1409,7 @@ def generate_jar_target(self, target: build.Jar):
# Add possible java generated files to src list
generated_sources = self.get_target_generated_sources(target)
gen_src_list = []
for rel_src in generated_sources.keys():
for rel_src in generated_sources:
raw_src = File.from_built_relative(rel_src)
if rel_src.endswith('.java'):
gen_src_list.append(raw_src)
Expand Down Expand Up @@ -1513,7 +1496,7 @@ def generate_cs_target(self, target: build.BuildTarget):
outputs = [outname_rel]
generated_sources = self.get_target_generated_sources(target)
generated_rel_srcs = []
for rel_src in generated_sources.keys():
for rel_src in generated_sources:
if rel_src.lower().endswith('.cs'):
generated_rel_srcs.append(os.path.normpath(rel_src))
deps.append(os.path.normpath(rel_src))
Expand Down Expand Up @@ -1547,7 +1530,7 @@ def determine_java_compile_args(self, target, compiler):
def generate_java_compile(self, srcs, 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 in generated_sources.keys():
for rel_src in generated_sources:
if rel_src.endswith('.java'):
deps.append(rel_src)

Expand Down Expand Up @@ -2218,10 +2201,7 @@ def generate_swift_target(self, target):
for i in reversed(target.get_include_dirs()):
basedir = i.get_curdir()
for d in i.get_incdirs():
if d not in ('', '.'):
expdir = os.path.join(basedir, d)
else:
expdir = basedir
expdir = basedir if d in {'', '.'} else os.path.join(basedir, d)
srctreedir = os.path.normpath(os.path.join(self.environment.get_build_dir(), self.build_to_src, expdir))
sargs = swiftc.get_include_args(srctreedir, False)
compile_args += sargs
Expand Down Expand Up @@ -2336,10 +2316,7 @@ def generate_static_link_rules(self):
ranlib = ['ranlib']
cmdlist.extend(['&&'] + ranlib + ['-c', '$out'])
description = 'Linking static target $out'
if num_pools > 0:
pool = 'pool = link_pool'
else:
pool = None
pool = 'pool = link_pool' if num_pools > 0 else None

options = self._rsp_options(static_linker)
self.add_rule(NinjaRule(rule, cmdlist, args, description, **options, extra=pool))
Expand All @@ -2355,10 +2332,7 @@ def generate_dynamic_link_rules(self):
command = compiler.get_linker_exelist()
args = ['$ARGS'] + NinjaCommandArg.list(compiler.get_linker_output_args('$out'), Quoting.none) + ['$in', '$LINK_ARGS']
description = 'Linking target $out'
if num_pools > 0:
pool = 'pool = link_pool'
else:
pool = None
pool = 'pool = link_pool' if num_pools > 0 else None

options = self._rsp_options(compiler)
self.add_rule(NinjaRule(rule, command, args, description, **options, extra=pool))
Expand Down Expand Up @@ -2450,10 +2424,7 @@ def generate_fortran_dep_hack(self, crstr: str) -> None:
if self.use_dyndeps_for_fortran():
return
rule = f'FORTRAN_DEP_HACK{crstr}'
if mesonlib.is_windows():
cmd = ['cmd', '/C']
else:
cmd = ['true']
cmd = ['cmd', '/C'] if mesonlib.is_windows() else ['true']
self.add_rule_comment(NinjaComment('''Workaround for these issues:
https://groups.google.com/forum/#!topic/ninja-build/j-2RfBIOd_8
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47485'''))
Expand Down Expand Up @@ -2932,7 +2903,7 @@ def generate_common_compile_args_per_src_type(self, target: build.BuildTarget) -

use_pch = self.target_uses_pch(target)

for src_type_str in target.compilers.keys():
for src_type_str in target.compilers:
compiler = target.compilers[src_type_str]
commands = self._generate_single_compile_base_args(target, compiler)

Expand Down
14 changes: 5 additions & 9 deletions mesonbuild/backend/vs2010backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,7 @@ def get_vcvars_command(self):

# Use vcvarsall.bat if we found it.
if 'VCINSTALLDIR' in os.environ:
vs_version = os.environ['VisualStudioVersion'] \
if 'VisualStudioVersion' in os.environ else None
vs_version = os.environ.get('VisualStudioVersion', None)
relative_path = 'Auxiliary\\Build\\' if vs_version is not None and vs_version >= '15.0' else ''
script_path = os.environ['VCINSTALLDIR'] + relative_path + 'vcvarsall.bat'
if os.path.exists(script_path):
Expand Down Expand Up @@ -426,7 +425,7 @@ def generate_solution(self, sln_filename: str, projlist: T.List[Project]) -> Non
target = self.build.targets[prj[0]]
lang = 'default'
if hasattr(target, 'compilers') and target.compilers:
for lang_out in target.compilers.keys():
for lang_out in target.compilers:
lang = lang_out
break
prj_line = prj_templ % (
Expand Down Expand Up @@ -870,7 +869,7 @@ def add_project_nmake_defs_incs_and_opts(self, parent_node, src: str, defs_paths
# defs/dirs/opts that are set for the nominal 'primary' src type.
ext = src.split('.')[-1]
lang = compilers.compilers.SUFFIX_TO_LANG.get(ext, None)
if lang in defs_paths_opts_per_lang_and_buildtype.keys():
if lang in defs_paths_opts_per_lang_and_buildtype:
# This is a non-primary src type for which can't simply reference the project's nmake fields;
# we must laboriously fill in the fields for all buildtypes.
for buildtype in coredata.get_genvs_default_buildtype_list():
Expand Down Expand Up @@ -1011,7 +1010,7 @@ def get_args_defines_and_inc_dirs(self, target, compiler, generated_files_includ
file_args[l] += args
# Compile args added from the env or cross file: CFLAGS/CXXFLAGS, etc. We want these
# to override all the defaults, but not the per-target compile args.
for lang in file_args.keys():
for lang in file_args:
file_args[lang] += target.get_option(OptionKey(f'{lang}_args', machine=target.for_machine))
for args in file_args.values():
# This is where Visual Studio will insert target_args, target_defines,
Expand Down Expand Up @@ -1068,10 +1067,7 @@ def get_args_defines_and_inc_dirs(self, target, compiler, generated_files_includ
if arg.startswith(('-D', '/D')) or arg == '%(PreprocessorDefinitions)':
file_args[l].remove(arg)
# Don't escape the marker
if arg == '%(PreprocessorDefinitions)':
define = arg
else:
define = arg[2:]
define = arg if arg == '%(PreprocessorDefinitions)' else arg[2:]
# De-dup
if define not in file_defines[l]:
file_defines[l].append(define)
Expand Down
4 changes: 1 addition & 3 deletions mesonbuild/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -2695,9 +2695,7 @@ def is_linkable_output(self, output: str) -> bool:
if output.endswith(('.a', '.dll', '.lib', '.so', '.dylib')):
return True
# libfoo.so.X soname
if re.search(r'\.so(\.\d+)*$', output):
return True
return False
return bool(re.search('\\.so(\\.\\d+)*$', output))

def is_linkable_target(self) -> bool:
if len(self.outputs) != 1:
Expand Down
5 changes: 2 additions & 3 deletions mesonbuild/cargo/cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,8 @@ def _parse(ast: _LEX_STREAM_AH) -> IR:
ntoken, _ = (None, None)

stream: T.List[_LEX_TOKEN]
if token is TokenType.IDENTIFIER:
if ntoken is TokenType.EQUAL:
return Equal(Identifier(value), _parse(ast))
if token is TokenType.IDENTIFIER and ntoken is TokenType.EQUAL:
return Equal(Identifier(value), _parse(ast))
if token is TokenType.STRING:
return String(value)
if token is TokenType.EQUAL:
Expand Down
2 changes: 1 addition & 1 deletion mesonbuild/cmake/fileapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,6 @@ def _reply_file_content(self, filename: Path) -> T.Dict[str, T.Any]:

data = json.loads(real_path.read_text(encoding='utf-8'))
assert isinstance(data, dict)
for i in data.keys():
for i in data:
assert isinstance(i, str)
return data
4 changes: 1 addition & 3 deletions mesonbuild/cmake/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,9 +452,7 @@ def rel_path(x: Path, is_header: bool, is_generated: bool) -> T.Optional[Path]:
def check_flag(flag: str) -> bool:
if flag.lower() in BLACKLIST_LINK_FLAGS or flag in BLACKLIST_COMPILER_FLAGS or flag in BLACKLIST_CLANG_CL_LINK_FLAGS:
return False
if flag.startswith('/D'):
return False
return True
return not flag.startswith('/D')

self.link_libraries = [x for x in self.link_libraries if x.lower() not in BLACKLIST_LINK_LIBS]
self.link_flags = [x for x in self.link_flags if check_flag(x)]
Expand Down
5 changes: 1 addition & 4 deletions mesonbuild/cmake/traceparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,10 +258,7 @@ def var_to_str(self, var: str) -> T.Optional[str]:
def _str_to_bool(self, expr: T.Union[str, T.List[str]]) -> bool:
if not expr:
return False
if isinstance(expr, list):
expr_str = expr[0]
else:
expr_str = expr
expr_str = expr[0] if isinstance(expr, list) else expr
expr_str = expr_str.upper()
return expr_str not in ['0', 'OFF', 'NO', 'FALSE', 'N', 'IGNORE'] and not expr_str.endswith('NOTFOUND')

Expand Down
5 changes: 1 addition & 4 deletions mesonbuild/compilers/compilers.py
Original file line number Diff line number Diff line change
Expand Up @@ -772,10 +772,7 @@ def _get_compile_output(self, dirname: str, mode: CompileCheckMode) -> str:
assert mode != CompileCheckMode.PREPROCESS, 'In pre-processor mode, the output is sent to stdout and discarded'
# Extension only matters if running results; '.exe' is
# guaranteed to be executable on every platform.
if mode == CompileCheckMode.LINK:
suffix = 'exe'
else:
suffix = 'obj'
suffix = 'exe' if mode == CompileCheckMode.LINK else 'obj'
return os.path.join(dirname, 'output.' + suffix)

def get_compiler_args_for_mode(self, mode: CompileCheckMode) -> T.List[str]:
Expand Down
5 changes: 1 addition & 4 deletions mesonbuild/compilers/cs.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,7 @@ def sanity_check(self, work_dir: str, environment: 'Environment') -> None:
pc.wait()
if pc.returncode != 0:
raise EnvironmentException('C# compiler %s cannot compile programs.' % self.name_string())
if self.runner:
cmdlist = [self.runner, obj]
else:
cmdlist = [os.path.join(work_dir, obj)]
cmdlist = [self.runner, obj] if self.runner else [os.path.join(work_dir, obj)]
pe = subprocess.Popen(cmdlist, cwd=work_dir)
pe.wait()
if pe.returncode != 0:
Expand Down
10 changes: 2 additions & 8 deletions mesonbuild/compilers/d.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,10 +286,7 @@ def _translate_args_to_nongnu(cls, args: T.List[str], info: MachineInfo, link_id
# The logic that follows tries to detect all these cases (some may be missing)
# in order to prepend a -L only for the library search paths with a single -L

if arg.startswith('-L='):
suffix = arg[3:]
else:
suffix = arg[2:]
suffix = arg[3:] if arg.startswith('-L=') else arg[2:]

if link_expect_arg:
# flags like rpath and soname expect a path or filename respectively,
Expand Down Expand Up @@ -529,10 +526,7 @@ def get_feature_args(self, kwargs: DFeatures, build_to_src: str) -> T.List[str]:
for idir in idir_obj.get_incdirs():
bldtreedir = os.path.join(basedir, idir)
# Avoid superfluous '/.' at the end of paths when d is '.'
if idir not in ('', '.'):
expdir = bldtreedir
else:
expdir = basedir
expdir = basedir if idir in {'', '.'} else bldtreedir
srctreedir = os.path.join(build_to_src, expdir)
res.append(f'{import_dir_arg}{srctreedir}')
res.append(f'{import_dir_arg}{bldtreedir}')
Expand Down
5 changes: 1 addition & 4 deletions mesonbuild/compilers/detect.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,10 +421,7 @@ def sanitize(p: T.Optional[str]) -> T.Optional[str]:
popen_exceptions[join_args(compiler + [arg])] = e
version = search_version(out)
match = re.search('^Target: (.*?)-', out, re.MULTILINE)
if match:
target = match.group(1)
else:
target = 'unknown target'
target = match.group(1) if match else 'unknown target'
cls = c.ClangClCCompiler if lang == 'c' else cpp.ClangClCPPCompiler
linker = guess_win_linker(env, ['lld-link'], cls, version, for_machine)
return cls(
Expand Down
Loading

0 comments on commit aa0a4ce

Please sign in to comment.