Skip to content

Commit

Permalink
Simplify Python code with: ruff --select=Q,SIM --fix . (nodejs#188)
Browse files Browse the repository at this point in the history
* Simplify Python code with: ruff --select=Q,SIM --fix .

* Fix a long line

* Fix a long line
  • Loading branch information
cclauss committed Feb 20, 2023
1 parent f0ac743 commit 9f38221
Show file tree
Hide file tree
Showing 16 changed files with 87 additions and 155 deletions.
24 changes: 11 additions & 13 deletions pylib/gyp/MSVSNew.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,19 +285,17 @@ def Write(self, writer=gyp.common.WriteOnDiff):
"\tEndProjectSection\r\n"
)

if isinstance(e, MSVSFolder):
if e.items:
f.write("\tProjectSection(SolutionItems) = preProject\r\n")
for i in e.items:
f.write(f"\t\t{i} = {i}\r\n")
f.write("\tEndProjectSection\r\n")

if isinstance(e, MSVSProject):
if e.dependencies:
f.write("\tProjectSection(ProjectDependencies) = postProject\r\n")
for d in e.dependencies:
f.write(f"\t\t{d.get_guid()} = {d.get_guid()}\r\n")
f.write("\tEndProjectSection\r\n")
if isinstance(e, MSVSFolder) and e.items:
f.write("\tProjectSection(SolutionItems) = preProject\r\n")
for i in e.items:
f.write(f"\t\t{i} = {i}\r\n")
f.write("\tEndProjectSection\r\n")

if isinstance(e, MSVSProject) and e.dependencies:
f.write("\tProjectSection(ProjectDependencies) = postProject\r\n")
for d in e.dependencies:
f.write(f"\t\t{d.get_guid()} = {d.get_guid()}\r\n")
f.write("\tEndProjectSection\r\n")

f.write("EndProject\r\n")

Expand Down
2 changes: 1 addition & 1 deletion pylib/gyp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,7 @@ def gyp_main(args):
if options.generator_flags:
gen_flags += options.generator_flags
generator_flags = NameValueListToDict(gen_flags)
if DEBUG_GENERAL in gyp.debug.keys():
if DEBUG_GENERAL in gyp.debug:
DebugOutput(DEBUG_GENERAL, "generator_flags: %s", generator_flags)

# Generate all requested formats (use a set in case we got one format request
Expand Down
21 changes: 7 additions & 14 deletions pylib/gyp/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,20 +144,16 @@ def RelativePath(path, relative_to, follow_path_symlink=True):
# symlink, this option has no effect.

# Convert to normalized (and therefore absolute paths).
if follow_path_symlink:
path = os.path.realpath(path)
else:
path = os.path.abspath(path)
path = os.path.realpath(path) if follow_path_symlink else os.path.abspath(path)
relative_to = os.path.realpath(relative_to)

# On Windows, we can't create a relative path to a different drive, so just
# use the absolute path.
if sys.platform == "win32":
if (
os.path.splitdrive(path)[0].lower()
!= os.path.splitdrive(relative_to)[0].lower()
):
return path
if sys.platform == "win32" and (
os.path.splitdrive(path)[0].lower()
!= os.path.splitdrive(relative_to)[0].lower()
):
return path

# Split the paths into components.
path_split = path.split(os.path.sep)
Expand Down Expand Up @@ -277,10 +273,7 @@ def EncodePOSIXShellArgument(argument):
if not isinstance(argument, str):
argument = str(argument)

if _quote.search(argument):
quote = '"'
else:
quote = ""
quote = '"' if _quote.search(argument) else ""

encoded = quote + re.sub(_escape, r"\\\1", argument) + quote

Expand Down
2 changes: 1 addition & 1 deletion pylib/gyp/generator/analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,7 @@ def _GetUnqualifiedToTargetMapping(all_targets, to_find):
if not to_find:
return {}, []
to_find = set(to_find)
for target_name in all_targets.keys():
for target_name in all_targets:
extracted = gyp.common.ParseQualifiedTarget(target_name)
if len(extracted) > 1 and extracted[1] in to_find:
to_find.remove(extracted[1])
Expand Down
5 changes: 1 addition & 4 deletions pylib/gyp/generator/cmake.py
Original file line number Diff line number Diff line change
Expand Up @@ -929,10 +929,7 @@ def WriteTarget(
product_prefix = spec.get("product_prefix", default_product_prefix)
product_name = spec.get("product_name", default_product_name)
product_ext = spec.get("product_extension")
if product_ext:
product_ext = "." + product_ext
else:
product_ext = default_product_ext
product_ext = "." + product_ext if product_ext else default_product_ext

SetTargetProperty(output, cmake_target_name, "PREFIX", product_prefix)
SetTargetProperty(
Expand Down
2 changes: 1 addition & 1 deletion pylib/gyp/generator/compile_commands_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@


def IsMac(params):
return "mac" == gyp.common.GetFlavor(params)
return gyp.common.GetFlavor(params) == "mac"


def CalculateVariables(default_variables, params):
Expand Down
5 changes: 1 addition & 4 deletions pylib/gyp/generator/eclipse.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,10 +248,7 @@ def GetAllDefines(target_list, target_dicts, data, config_name, params, compiler
continue
cpp_line_parts = cpp_line.split(" ", 2)
key = cpp_line_parts[1]
if len(cpp_line_parts) >= 3:
val = cpp_line_parts[2]
else:
val = "1"
val = cpp_line_parts[2] if len(cpp_line_parts) >= 3 else "1"
all_defines[key] = val

return all_defines
Expand Down
7 changes: 2 additions & 5 deletions pylib/gyp/generator/make.py
Original file line number Diff line number Diff line change
Expand Up @@ -681,10 +681,7 @@ def WriteRootHeaderSuffixRules(writer):

def Compilable(filename):
"""Return true if the file is compilable (should be in OBJS)."""
for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS):
if res:
return True
return False
return any(res for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS))


def Linkable(filename):
Expand Down Expand Up @@ -778,7 +775,7 @@ def __init__(self, generator_flags, flavor):
self.suffix_rules_objdir2 = {}

# Generate suffix rules for all compilable extensions.
for ext in COMPILABLE_EXTENSIONS.keys():
for ext in COMPILABLE_EXTENSIONS:
# Suffix rules for source folder.
self.suffix_rules_srcdir.update(
{
Expand Down
50 changes: 18 additions & 32 deletions pylib/gyp/generator/msvs.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def _FixPath(path, separator="\\"):
fixpath_prefix
and path
and not os.path.isabs(path)
and not path[0] == "$"
and path[0] != "$"
and not _IsWindowsAbsPath(path)
):
path = os.path.join(fixpath_prefix, path)
Expand Down Expand Up @@ -283,7 +283,7 @@ def _ToolSetOrAppend(tools, tool_name, setting, value, only_if_unset=False):
if not tools.get(tool_name):
tools[tool_name] = dict()
tool = tools[tool_name]
if "CompileAsWinRT" == setting:
if setting == "CompileAsWinRT":
return
if tool.get(setting):
if only_if_unset:
Expand Down Expand Up @@ -412,10 +412,7 @@ def _BuildCommandLineForRuleRaw(
return input_dir_preamble + cmd
else:
# Convert cat --> type to mimic unix.
if cmd[0] == "cat":
command = ["type"]
else:
command = [cmd[0].replace("/", "\\")]
command = ["type"] if cmd[0] == "cat" else [cmd[0].replace("/", "\\")]
# Add call before command to ensure that commands can be tied together one
# after the other without aborting in Incredibuild, since IB makes a bat
# file out of the raw command string, and some commands (like python) are
Expand Down Expand Up @@ -1384,10 +1381,7 @@ def _GetDefines(config):
"""
defines = []
for d in config.get("defines", []):
if type(d) == list:
fd = "=".join([str(dpart) for dpart in d])
else:
fd = str(d)
fd = "=".join([str(dpart) for dpart in d]) if isinstance(d, list) else str(d)
defines.append(fd)
return defines

Expand Down Expand Up @@ -1598,10 +1592,7 @@ def _IdlFilesHandledNonNatively(spec, sources):
if rule["extension"] == "idl" and int(rule.get("msvs_external_rule", 0)):
using_idl = True
break
if using_idl:
excluded_idl = [i for i in sources if i.endswith(".idl")]
else:
excluded_idl = []
excluded_idl = [i for i in sources if i.endswith(".idl")] if using_idl else []
return excluded_idl


Expand Down Expand Up @@ -3020,11 +3011,10 @@ def _GetMSBuildConfigurationDetails(spec, build_file):
_AddConditionalProperty(
properties, condition, "TargetVersion", _ConfigTargetVersion(settings)
)
if character_set:
if "msvs_enable_winrt" not in spec:
_AddConditionalProperty(
properties, condition, "CharacterSet", character_set
)
if character_set and "msvs_enable_winrt" not in spec:
_AddConditionalProperty(
properties, condition, "CharacterSet", character_set
)
return _GetMSBuildPropertyGroup(spec, "Configuration", properties)


Expand Down Expand Up @@ -3326,15 +3316,14 @@ def _GetMSBuildToolSettingsSections(spec, configurations):
for tool_name, tool_settings in sorted(msbuild_settings.items()):
# Skip the tool named '' which is a holder of global settings handled
# by _GetMSBuildConfigurationGlobalProperties.
if tool_name:
if tool_settings:
tool = [tool_name]
for name, value in sorted(tool_settings.items()):
formatted_value = _GetValueFormattedForMSBuild(
tool_name, name, value
)
tool.append([name, formatted_value])
group.append(tool)
if tool_name and tool_settings:
tool = [tool_name]
for name, value in sorted(tool_settings.items()):
formatted_value = _GetValueFormattedForMSBuild(
tool_name, name, value
)
tool.append([name, formatted_value])
group.append(tool)
groups.append(group)
return groups

Expand Down Expand Up @@ -3462,10 +3451,7 @@ def _GetValueFormattedForMSBuild(tool_name, name, value):
"Link": ["AdditionalOptions"],
"Lib": ["AdditionalOptions"],
}
if tool_name in exceptions and name in exceptions[tool_name]:
char = " "
else:
char = ";"
char = " " if name in exceptions.get(tool_name, []) else ";"
formatted_value = char.join(
[MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in value]
)
Expand Down
5 changes: 1 addition & 4 deletions pylib/gyp/generator/ninja.py
Original file line number Diff line number Diff line change
Expand Up @@ -1815,10 +1815,7 @@ def ComputeOutputFileName(self, spec, type=None):
"executable": default_variables["EXECUTABLE_SUFFIX"],
}
extension = spec.get("product_extension")
if extension:
extension = "." + extension
else:
extension = DEFAULT_EXTENSION.get(type, "")
extension = "." + extension if extension else DEFAULT_EXTENSION.get(type, "")

if "product_name" in spec:
# If we were given an explicit name, use that.
Expand Down
7 changes: 2 additions & 5 deletions pylib/gyp/generator/xcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ def Finalize2(self, xcode_targets, xcode_target_to_target_dict):
# it opens the project file, which will result in unnecessary diffs.
# TODO(mark): This is evil because it relies on internal knowledge of
# PBXProject._other_pbxprojects.
for other_pbxproject in self.project._other_pbxprojects.keys():
for other_pbxproject in self.project._other_pbxprojects:
self.project.AddOrGetProjectReference(other_pbxproject)

self.project.SortRemoteProductReferences()
Expand Down Expand Up @@ -1118,10 +1118,7 @@ def GenerateOutput(target_list, target_dicts, data, params):
for concrete_output_index, concrete_output in enumerate(
concrete_outputs
):
if concrete_output_index == 0:
bol = ""
else:
bol = " "
bol = "" if concrete_output_index == 0 else " "
makefile.write(f"{bol}{concrete_output} \\\n")

concrete_output_dir = posixpath.dirname(concrete_output)
Expand Down
45 changes: 16 additions & 29 deletions pylib/gyp/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def LoadOneBuildFile(build_file_path, data, aux_data, includes, is_target, check
return data[build_file_path]

if os.path.exists(build_file_path):
build_file_contents = open(build_file_path, encoding='utf-8').read()
build_file_contents = open(build_file_path, encoding="utf-8").read()
else:
raise GypError(f"{build_file_path} not found (cwd: {os.getcwd()})")

Expand Down Expand Up @@ -870,10 +870,7 @@ def ExpandVariables(input, phase, variables, build_file):
# This works around actions/rules which have more inputs than will
# fit on the command line.
if file_list:
if type(contents) is list:
contents_list = contents
else:
contents_list = contents.split(" ")
contents_list = contents if type(contents) is list else contents.split(" ")
replacement = contents_list[0]
if os.path.isabs(replacement):
raise GypError('| cannot handle absolute paths, got "%s"' % replacement)
Expand Down Expand Up @@ -1630,15 +1627,14 @@ def RemoveSelfDependencies(targets):
dependencies = target_dict.get(dependency_key, [])
if dependencies:
for t in dependencies:
if t == target_name:
if (
targets[t]
.get("variables", {})
.get("prune_self_dependency", 0)
):
target_dict[dependency_key] = Filter(
dependencies, target_name
)
if t == target_name and (
targets[t]
.get("variables", {})
.get("prune_self_dependency", 0)
):
target_dict[dependency_key] = Filter(
dependencies, target_name
)


def RemoveLinkDependenciesFromNoneTargets(targets):
Expand Down Expand Up @@ -2238,10 +2234,7 @@ def is_in_set_or_list(x, s, items):
singleton = False
if type(item) in (str, int):
# The cheap and easy case.
if is_paths:
to_item = MakePathRelative(to_file, fro_file, item)
else:
to_item = item
to_item = MakePathRelative(to_file, fro_file, item) if is_paths else item

if not (type(item) is str and item.startswith("-")):
# Any string that doesn't begin with a "-" is a singleton - it can
Expand Down Expand Up @@ -2467,10 +2460,7 @@ def SetUpConfigurations(target, target_dict):
new_configuration_dict = {}
for (key, target_val) in target_dict.items():
key_ext = key[-1:]
if key_ext in key_suffixes:
key_base = key[:-1]
else:
key_base = key
key_base = key[:-1] if key_ext in key_suffixes else key
if key_base not in non_configuration_keys:
new_configuration_dict[key] = gyp.simple_copy.deepcopy(target_val)

Expand All @@ -2482,7 +2472,7 @@ def SetUpConfigurations(target, target_dict):
merged_configurations[configuration] = new_configuration_dict

# Put the new configurations back into the target dict as a configuration.
for configuration in merged_configurations.keys():
for configuration in merged_configurations:
target_dict["configurations"][configuration] = merged_configurations[
configuration
]
Expand All @@ -2499,19 +2489,16 @@ def SetUpConfigurations(target, target_dict):
delete_keys = []
for key in target_dict:
key_ext = key[-1:]
if key_ext in key_suffixes:
key_base = key[:-1]
else:
key_base = key
key_base = key[:-1] if key_ext in key_suffixes else key
if key_base not in non_configuration_keys:
delete_keys.append(key)
for key in delete_keys:
del target_dict[key]

# Check the configurations to see if they contain invalid keys.
for configuration in target_dict["configurations"].keys():
for configuration in target_dict["configurations"]:
configuration_dict = target_dict["configurations"][configuration]
for key in configuration_dict.keys():
for key in configuration_dict:
if key in invalid_configuration_keys:
raise GypError(
"%s not allowed in the %s configuration, found in "
Expand Down
Loading

0 comments on commit 9f38221

Please sign in to comment.