diff --git a/README.md b/README.md index 64e82dbbe3..d9c5d31263 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ Depending on your operating system, you will need to install: ### On Unix - * Python v2.7, v3.5, v3.6, v3.7, or v3.8 + * Python v3.5, v3.6, v3.7, v3.8, or v3.9 * `make` * A proper C/C++ compiler toolchain, like [GCC](https://gcc.gnu.org) @@ -38,7 +38,7 @@ Depending on your operating system, you will need to install: **ATTENTION**: If your Mac has been _upgraded_ to macOS Catalina (10.15), please read [macOS_Catalina.md](macOS_Catalina.md). - * Python v2.7, v3.5, v3.6, v3.7, or v3.8 + * Python v3.5, v3.6, v3.7, v3.8, or v3.9 * [Xcode](https://developer.apple.com/xcode/download/) * You also need to install the `XCode Command Line Tools` by running `xcode-select --install`. Alternatively, if you already have the full Xcode installed, you can find them under the menu `Xcode -> Open Developer Tool -> More Developer Tools...`. This step will install `clang`, `clang++`, and `make`. @@ -46,12 +46,6 @@ Depending on your operating system, you will need to install: Install the current version of Python from the [Microsoft Store package](https://docs.python.org/3/using/windows.html#the-microsoft-store-package). -#### Option 1 - -Install all the required tools and configurations using Microsoft's [windows-build-tools](https://github.com/felixrieseberg/windows-build-tools) using `npm install --global windows-build-tools` from an elevated PowerShell or CMD.exe (run as Administrator). - -#### Option 2 - Install tools and configuration manually: * Install Visual C++ Build Environment: [Visual Studio Build Tools](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools) (using "Visual C++ build tools" workload) or [Visual Studio 2017 Community](https://visualstudio.microsoft.com/pl/thank-you-downloading-visual-studio/?sku=Community) @@ -64,8 +58,8 @@ Install tools and configuration manually: ### Configuring Python Dependency -`node-gyp` requires that you have installed a compatible version of Python, one of: v2.7, v3.5, v3.6, -v3.7, or v3.8. If you have multiple Python versions installed, you can identify which Python +`node-gyp` requires that you have installed a compatible version of Python, one of: v3.5, v3.6, +v3.7, v3.8, or v3.9. If you have multiple Python versions installed, you can identify which Python version `node-gyp` should use in one of the following ways: 1. by setting the `--python` command-line option, e.g.: diff --git a/gyp/pylib/gyp/MSVSNew.py b/gyp/pylib/gyp/MSVSNew.py index 04bbb3df71..16e3d5a877 100644 --- a/gyp/pylib/gyp/MSVSNew.py +++ b/gyp/pylib/gyp/MSVSNew.py @@ -69,7 +69,7 @@ def MakeGuid(name, seed="msvs_new"): # ------------------------------------------------------------------------------ -class MSVSSolutionEntry(object): +class MSVSSolutionEntry: def __cmp__(self, other): # Sort by name then guid (so things are in order on vs2008). return cmp((self.name, self.get_guid()), (other.name, other.get_guid())) @@ -190,7 +190,7 @@ def set_msbuild_toolset(self, msbuild_toolset): # ------------------------------------------------------------------------------ -class MSVSSolution(object): +class MSVSSolution: """Visual Studio solution.""" def __init__( @@ -292,14 +292,14 @@ def Write(self, writer=gyp.common.WriteOnDiff): if e.items: f.write("\tProjectSection(SolutionItems) = preProject\r\n") for i in e.items: - f.write("\t\t%s = %s\r\n" % (i, i)) + 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("\t\t%s = %s\r\n" % (d.get_guid(), d.get_guid())) + f.write(f"\t\t{d.get_guid()} = {d.get_guid()}\r\n") f.write("\tEndProjectSection\r\n") f.write("EndProject\r\n") @@ -310,7 +310,7 @@ def Write(self, writer=gyp.common.WriteOnDiff): # Configurations (variants) f.write("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n") for v in self.variants: - f.write("\t\t%s = %s\r\n" % (v, v)) + f.write(f"\t\t{v} = {v}\r\n") f.write("\tEndGlobalSection\r\n") # Sort config guids for easier diffing of solution changes. @@ -362,7 +362,7 @@ def Write(self, writer=gyp.common.WriteOnDiff): if not isinstance(e, MSVSFolder): continue # Does not apply to projects, only folders for subentry in e.entries: - f.write("\t\t%s = %s\r\n" % (subentry.get_guid(), e.get_guid())) + f.write(f"\t\t{subentry.get_guid()} = {e.get_guid()}\r\n") f.write("\tEndGlobalSection\r\n") f.write("EndGlobal\r\n") diff --git a/gyp/pylib/gyp/MSVSProject.py b/gyp/pylib/gyp/MSVSProject.py index f953d52cd0..f0cfabe834 100644 --- a/gyp/pylib/gyp/MSVSProject.py +++ b/gyp/pylib/gyp/MSVSProject.py @@ -9,7 +9,7 @@ # ------------------------------------------------------------------------------ -class Tool(object): +class Tool: """Visual Studio tool.""" def __init__(self, name, attrs=None): @@ -31,7 +31,7 @@ def _GetSpecification(self): return ["Tool", self._attrs] -class Filter(object): +class Filter: """Visual Studio filter - that is, a virtual folder.""" def __init__(self, name, contents=None): @@ -48,7 +48,7 @@ def __init__(self, name, contents=None): # ------------------------------------------------------------------------------ -class Writer(object): +class Writer: """Visual Studio XML project writer.""" def __init__(self, project_path, version, name, guid=None, platforms=None): diff --git a/gyp/pylib/gyp/MSVSSettings.py b/gyp/pylib/gyp/MSVSSettings.py index 6ef16f2a0b..65b8a42991 100644 --- a/gyp/pylib/gyp/MSVSSettings.py +++ b/gyp/pylib/gyp/MSVSSettings.py @@ -14,7 +14,6 @@ MSBuild install directory, e.g. c:\Program Files (x86)\MSBuild """ -from __future__ import print_function from gyp import string_types @@ -36,7 +35,7 @@ _msbuild_name_of_tool = {} -class _Tool(object): +class _Tool: """Represents a tool used by MSVS or MSBuild. Attributes: @@ -68,7 +67,7 @@ def _GetMSBuildToolSettings(msbuild_settings, tool): return msbuild_settings.setdefault(tool.msbuild_name, {}) -class _Type(object): +class _Type: """Type of settings (Base class).""" def ValidateMSVS(self, value): @@ -195,7 +194,7 @@ class _Enumeration(_Type): def __init__(self, label_list, new=None): _Type.__init__(self) self._label_list = label_list - self._msbuild_values = set(value for value in label_list if value is not None) + self._msbuild_values = {value for value in label_list if value is not None} if new is not None: self._msbuild_values.update(new) @@ -342,7 +341,7 @@ def _Translate(value, msbuild_settings): if value == "true": tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool) if "AdditionalOptions" in tool_settings: - new_flags = "%s %s" % (tool_settings["AdditionalOptions"], flag) + new_flags = "{} {}".format(tool_settings["AdditionalOptions"], flag) else: new_flags = flag tool_settings["AdditionalOptions"] = new_flags @@ -536,14 +535,14 @@ def _ValidateSettings(validators, settings, stderr): tool_validators[setting](value) except ValueError as e: print( - "Warning: for %s/%s, %s" % (tool_name, setting, e), + f"Warning: for {tool_name}/{setting}, {e}", file=stderr, ) else: _ValidateExclusionSetting( setting, tool_validators, - ("Warning: unrecognized setting %s/%s" % (tool_name, setting)), + (f"Warning: unrecognized setting {tool_name}/{setting}"), stderr, ) diff --git a/gyp/pylib/gyp/MSVSToolFile.py b/gyp/pylib/gyp/MSVSToolFile.py index 2c08589e06..2e5c811bdd 100644 --- a/gyp/pylib/gyp/MSVSToolFile.py +++ b/gyp/pylib/gyp/MSVSToolFile.py @@ -7,7 +7,7 @@ import gyp.easy_xml as easy_xml -class Writer(object): +class Writer: """Visual Studio XML tool file writer.""" def __init__(self, tool_file_path, name): diff --git a/gyp/pylib/gyp/MSVSUserFile.py b/gyp/pylib/gyp/MSVSUserFile.py index de0896e693..e580c00fb7 100644 --- a/gyp/pylib/gyp/MSVSUserFile.py +++ b/gyp/pylib/gyp/MSVSUserFile.py @@ -53,7 +53,7 @@ def _QuoteWin32CommandLineArgs(args): return new_args -class Writer(object): +class Writer: """Visual Studio XML user user file writer.""" def __init__(self, user_file_path, version, name): @@ -93,7 +93,7 @@ def AddDebugSettings( abs_command = _FindCommandInPath(command[0]) if environment and isinstance(environment, dict): - env_list = ['%s="%s"' % (key, val) for (key, val) in environment.items()] + env_list = [f'{key}="{val}"' for (key, val) in environment.items()] environment = " ".join(env_list) else: environment = "" diff --git a/gyp/pylib/gyp/MSVSUtil.py b/gyp/pylib/gyp/MSVSUtil.py index 83a9c297ed..cb55305eae 100644 --- a/gyp/pylib/gyp/MSVSUtil.py +++ b/gyp/pylib/gyp/MSVSUtil.py @@ -55,7 +55,7 @@ def _SuffixName(name, suffix): Target name with suffix added (foo_suffix#target) """ parts = name.rsplit("#", 1) - parts[0] = "%s_%s" % (parts[0], suffix) + parts[0] = "{}_{}".format(parts[0], suffix) return "#".join(parts) @@ -160,7 +160,7 @@ def _GetPdbPath(target_dict, config_name, vars): return pdb_path pdb_base = target_dict.get("product_name", target_dict["target_name"]) - pdb_base = "%s.%s.pdb" % (pdb_base, TARGET_TYPE_EXT[target_dict["type"]]) + pdb_base = "{}.{}.pdb".format(pdb_base, TARGET_TYPE_EXT[target_dict["type"]]) pdb_path = vars["PRODUCT_DIR"] + "/" + pdb_base return pdb_path diff --git a/gyp/pylib/gyp/MSVSVersion.py b/gyp/pylib/gyp/MSVSVersion.py index 36b006aaa9..5da02dc25a 100644 --- a/gyp/pylib/gyp/MSVSVersion.py +++ b/gyp/pylib/gyp/MSVSVersion.py @@ -18,7 +18,7 @@ def JoinPath(*args): return os.path.normpath(os.path.join(*args)) -class VisualStudioVersion(object): +class VisualStudioVersion: """Information regarding a version of Visual Studio.""" def __init__( @@ -235,7 +235,7 @@ def _RegistryGetValueUsingWinReg(key, value): assert root == "HKLM" # Only need HKLM for now. with OpenKey(HKEY_LOCAL_MACHINE, subkey) as hkey: return QueryValueEx(hkey, value)[0] - except WindowsError: + except OSError: return None diff --git a/gyp/pylib/gyp/__init__.py b/gyp/pylib/gyp/__init__.py index f6ea625d40..4e9f8cd2dc 100755 --- a/gyp/pylib/gyp/__init__.py +++ b/gyp/pylib/gyp/__init__.py @@ -4,7 +4,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -from __future__ import print_function import copy import gyp.input @@ -193,7 +192,7 @@ def ShlexEnv(env_name): def FormatOpt(opt, value): if opt.startswith("--"): - return "%s=%s" % (opt, value) + return f"{opt}={value}" return opt + value diff --git a/gyp/pylib/gyp/common.py b/gyp/pylib/gyp/common.py index a915643867..fce8954a35 100644 --- a/gyp/pylib/gyp/common.py +++ b/gyp/pylib/gyp/common.py @@ -20,7 +20,7 @@ # A minimal memoizing decorator. It'll blow up if the args aren't immutable, # among other "problems". -class memoize(object): +class memoize: def __init__(self, func): self.func = func self.cache = {} @@ -348,7 +348,7 @@ def WriteOnDiff(filename): the target if it differs (on close). """ - class Writer(object): + class Writer: """Wrapper around file which only covers the target if it differs.""" def __init__(self): @@ -566,8 +566,8 @@ def pop(self, last=True): # pylint: disable=W0221 def __repr__(self): if not self: - return "%s()" % (self.__class__.__name__,) - return "%s(%r)" % (self.__class__.__name__, list(self)) + return f"{self.__class__.__name__}()" + return "{}({!r})".format(self.__class__.__name__, list(self)) def __eq__(self, other): if isinstance(other, OrderedSet): diff --git a/gyp/pylib/gyp/easy_xml.py b/gyp/pylib/gyp/easy_xml.py index e0628ef4d8..e475b5530c 100644 --- a/gyp/pylib/gyp/easy_xml.py +++ b/gyp/pylib/gyp/easy_xml.py @@ -84,7 +84,7 @@ def _ConstructContentList(xml_parts, specification, pretty, level=0): rest = specification[1:] if rest and isinstance(rest[0], dict): for at, val in sorted(rest[0].items()): - xml_parts.append(' %s="%s"' % (at, _XmlEscape(val, attr=True))) + xml_parts.append(' {}="{}"'.format(at, _XmlEscape(val, attr=True))) rest = rest[1:] if rest: xml_parts.append(">") @@ -101,7 +101,7 @@ def _ConstructContentList(xml_parts, specification, pretty, level=0): _ConstructContentList(xml_parts, child_spec, pretty, level + 1) if multi_line and indentation: xml_parts.append(indentation) - xml_parts.append("%s" % (name, new_line)) + xml_parts.append(f"{new_line}") else: xml_parts.append("/>%s" % new_line) @@ -125,9 +125,9 @@ def WriteXmlIfChanged(content, path, encoding="utf-8", pretty=False, win32=False # Get the old content try: - with open(path, "r") as file: + with open(path) as file: existing = file.read() - except IOError: + except OSError: existing = None # It has changed, write it diff --git a/gyp/pylib/gyp/flock_tool.py b/gyp/pylib/gyp/flock_tool.py index f9f89e520a..c649a89ef8 100755 --- a/gyp/pylib/gyp/flock_tool.py +++ b/gyp/pylib/gyp/flock_tool.py @@ -18,7 +18,7 @@ def main(args): executor.Dispatch(args) -class FlockTool(object): +class FlockTool: """This class emulates the 'flock' command.""" def Dispatch(self, args): diff --git a/gyp/pylib/gyp/generator/analyzer.py b/gyp/pylib/gyp/generator/analyzer.py index 7a393c1f93..f15df00c36 100644 --- a/gyp/pylib/gyp/generator/analyzer.py +++ b/gyp/pylib/gyp/generator/analyzer.py @@ -62,7 +62,6 @@ then the "all" target includes "b1" and "b2". """ -from __future__ import print_function import gyp.common import json @@ -216,7 +215,7 @@ def _ExtractSources(target, target_dict, toplevel_dir): return results -class Target(object): +class Target: """Holds information about a particular target: deps: set of Targets this Target depends upon. This is not recursive, only the direct dependent Targets. @@ -252,7 +251,7 @@ def __init__(self, name): self.is_or_has_linked_ancestor = False -class Config(object): +class Config: """Details what we're looking for files: set of files to search for targets: see file description for details.""" @@ -271,10 +270,10 @@ def Init(self, params): if not config_path: return try: - f = open(config_path, "r") + f = open(config_path) config = json.load(f) f.close() - except IOError: + except OSError: raise Exception("Unable to open file " + config_path) except ValueError as e: raise Exception("Unable to parse config file " + config_path + str(e)) @@ -586,7 +585,7 @@ def _WriteOutput(params, **values): f = open(output_path, "w") f.write(json.dumps(values) + "\n") f.close() - except IOError as e: + except OSError as e: print("Error writing to output file", output_path, str(e)) @@ -627,7 +626,7 @@ def CalculateVariables(default_variables, params): default_variables.setdefault("OS", operating_system) -class TargetCalculator(object): +class TargetCalculator: """Calculates the matching test_targets and matching compile_targets.""" def __init__( diff --git a/gyp/pylib/gyp/generator/android.py b/gyp/pylib/gyp/generator/android.py index 16728847c5..f0d22e6064 100644 --- a/gyp/pylib/gyp/generator/android.py +++ b/gyp/pylib/gyp/generator/android.py @@ -14,7 +14,6 @@ # variables set potentially clash with other Android build system variables. # Try to avoid setting global variables where possible. -from __future__ import print_function import gyp import gyp.common @@ -100,7 +99,7 @@ def Sourceify(path): target_link_deps = {} -class AndroidMkWriter(object): +class AndroidMkWriter: """AndroidMkWriter packages up the writing of one target-specific Android.mk. Its only real entry point is Write(), and is mostly used for namespacing. @@ -262,7 +261,7 @@ def WriteActions(self, actions, extra_sources, extra_outputs): """ for action in actions: name = make.StringToMakefileVariable( - "%s_%s" % (self.relative_target, action["action_name"]) + "{}_{}".format(self.relative_target, action["action_name"]) ) self.WriteLn('### Rules for action "%s":' % action["action_name"]) inputs = action["inputs"] @@ -350,7 +349,7 @@ def WriteActions(self, actions, extra_sources, extra_outputs): for output in outputs[1:]: # Make each output depend on the main output, with an empty command # to force make to notice that the mtime has changed. - self.WriteLn("%s: %s ;" % (self.LocalPathify(output), main_output)) + self.WriteLn("{}: {} ;".format(self.LocalPathify(output), main_output)) extra_outputs += outputs self.WriteLn() @@ -372,7 +371,7 @@ def WriteRules(self, rules, extra_sources, extra_outputs): if len(rule.get("rule_sources", [])) == 0: continue name = make.StringToMakefileVariable( - "%s_%s" % (self.relative_target, rule["rule_name"]) + "{}_{}".format(self.relative_target, rule["rule_name"]) ) self.WriteLn('\n### Generated for rule "%s":' % name) self.WriteLn('# "%s":' % rule) @@ -452,7 +451,7 @@ def WriteRules(self, rules, extra_sources, extra_outputs): for output in outputs[1:]: # Make each output depend on the main output, with an empty command # to force make to notice that the mtime has changed. - self.WriteLn("%s: %s ;" % (output, main_output)) + self.WriteLn(f"{output}: {main_output} ;") self.WriteLn() self.WriteLn() @@ -488,14 +487,14 @@ def WriteCopies(self, copies, extra_outputs): ) self.WriteLn( - "%s: %s $(GYP_TARGET_DEPENDENCIES) | $(ACP)" % (output, path) + f"{output}: {path} $(GYP_TARGET_DEPENDENCIES) | $(ACP)" ) self.WriteLn("\t@echo Copying: $@") self.WriteLn("\t$(hide) mkdir -p $(dir $@)") self.WriteLn("\t$(hide) $(ACP) -rpf $< $@") self.WriteLn() outputs.append(output) - self.WriteLn("%s = %s" % (variable, " ".join(map(make.QuoteSpaces, outputs)))) + self.WriteLn("{} = {}".format(variable, " ".join(map(make.QuoteSpaces, outputs)))) extra_outputs.append("$(%s)" % variable) self.WriteLn() @@ -617,7 +616,7 @@ def WriteSources(self, spec, configs, extra_sources): if IsCPPExtension(ext) and ext != local_cpp_extension: local_file = root + local_cpp_extension if local_file != source: - self.WriteLn("%s: %s" % (local_file, self.LocalPathify(source))) + self.WriteLn("{}: {}".format(local_file, self.LocalPathify(source))) self.WriteLn("\tmkdir -p $(@D); cp $< $@") origin_src_dirs.append(os.path.dirname(source)) final_generated_sources.append(local_file) @@ -662,7 +661,7 @@ def ComputeAndroidModule(self, spec): suffix = "_gyp" if self.path: - middle = make.StringToMakefileVariable("%s_%s" % (self.path, self.target)) + middle = make.StringToMakefileVariable(f"{self.path}_{self.target}") else: middle = make.StringToMakefileVariable(self.target) @@ -740,7 +739,7 @@ def ComputeOutput(self, spec): % (self.android_class, self.android_module) ) else: - path = "$(call intermediates-dir-for,%s,%s,,,$(GYP_VAR_PREFIX))" % ( + path = "$(call intermediates-dir-for,{},{},,,$(GYP_VAR_PREFIX))".format( self.android_class, self.android_module, ) @@ -909,7 +908,7 @@ def WriteTarget( if isinstance(v, list): self.WriteList(v, k) else: - self.WriteLn("%s := %s" % (k, make.QuoteIfNecessary(v))) + self.WriteLn("{} := {}".format(k, make.QuoteIfNecessary(v))) self.WriteLn("") # Add to the set of targets which represent the gyp 'all' target. We use the @@ -928,7 +927,7 @@ def WriteTarget( if self.target != self.android_module and write_alias_target: self.WriteLn("# Alias gyp target name.") self.WriteLn(".PHONY: %s" % self.target) - self.WriteLn("%s: %s" % (self.target, self.android_module)) + self.WriteLn(f"{self.target}: {self.android_module}") self.WriteLn("") # Add the command to trigger build of the target type depending @@ -985,7 +984,7 @@ def WriteList( if local_pathify: value_list = [self.LocalPathify(value) for value in value_list] values = " \\\n\t" + " \\\n\t".join(value_list) - self.fp.write("%s :=%s\n\n" % (variable, values)) + self.fp.write(f"{variable} :={values}\n\n") def WriteLn(self, text=""): self.fp.write(text + "\n") @@ -1006,7 +1005,7 @@ def LocalPathify(self, path): # so we don't look for a slash. assert local_path.startswith( "$(LOCAL_PATH)" - ), "Path %s attempts to escape from gyp path %s !)" % (path, self.path) + ), f"Path {path} attempts to escape from gyp path {self.path} !)" return local_path def ExpandInputRoot(self, template, expansion, dirname): diff --git a/gyp/pylib/gyp/generator/cmake.py b/gyp/pylib/gyp/generator/cmake.py index 75f5822369..487c236cc2 100644 --- a/gyp/pylib/gyp/generator/cmake.py +++ b/gyp/pylib/gyp/generator/cmake.py @@ -28,7 +28,6 @@ CMakeLists.txt file. """ -from __future__ import print_function import multiprocessing import os @@ -223,7 +222,7 @@ def WriteVariable(output, variable_name, prepend=None): output.write("}") -class CMakeTargetType(object): +class CMakeTargetType: def __init__(self, command, modifier, property_modifier): self.command = command self.modifier = modifier @@ -263,7 +262,7 @@ def WriteActions(target_name, actions, extra_sources, extra_deps, path_to_gyp, o """ for action in actions: action_name = StringToCMakeTargetName(action["action_name"]) - action_target_name = "%s__%s" % (target_name, action_name) + action_target_name = f"{target_name}__{action_name}" inputs = action["inputs"] inputs_name = action_target_name + "__input" @@ -282,7 +281,7 @@ def WriteActions(target_name, actions, extra_sources, extra_deps, path_to_gyp, o # Build up a list of outputs. # Collect the output dirs we'll need. - dirs = set(dir for dir in (os.path.dirname(o) for o in outputs) if dir) + dirs = {dir for dir in (os.path.dirname(o) for o in outputs) if dir} if int(action.get("process_outputs_as_sources", False)): extra_sources.extend(zip(cmake_outputs, outputs)) @@ -377,7 +376,7 @@ def WriteRules(target_name, rules, extra_sources, extra_deps, path_to_gyp, outpu # Build up a list of outputs. # Collect the output dirs we'll need. - dirs = set(dir for dir in (os.path.dirname(o) for o in outputs) if dir) + dirs = {dir for dir in (os.path.dirname(o) for o in outputs) if dir} # Create variables for the output, as 'local' variable will be unset. these_outputs = [] @@ -478,7 +477,7 @@ def WriteCopies(target_name, copies, extra_deps, path_to_gyp, output): extra_deps.append(copy_name) return - class Copy(object): + class Copy: def __init__(self, ext, command): self.cmake_inputs = [] self.cmake_outputs = [] @@ -587,7 +586,7 @@ def CreateCMakeTargetFullName(qualified_target): return StringToCMakeTargetName(cmake_target_full_name) -class CMakeNamer(object): +class CMakeNamer: """Converts Gyp target names into CMake target names. CMake requires that target names be globally unique. One way to ensure @@ -1285,11 +1284,11 @@ def PerformBuild(data, configurations, params): os.path.join(generator_dir, output_dir, config_name) ) arguments = ["cmake", "-G", "Ninja"] - print("Generating [%s]: %s" % (config_name, arguments)) + print(f"Generating [{config_name}]: {arguments}") subprocess.check_call(arguments, cwd=build_dir) arguments = ["ninja", "-C", build_dir] - print("Building [%s]: %s" % (config_name, arguments)) + print(f"Building [{config_name}]: {arguments}") subprocess.check_call(arguments) diff --git a/gyp/pylib/gyp/generator/dump_dependency_json.py b/gyp/pylib/gyp/generator/dump_dependency_json.py index 46f68e0384..99d5c1fd69 100644 --- a/gyp/pylib/gyp/generator/dump_dependency_json.py +++ b/gyp/pylib/gyp/generator/dump_dependency_json.py @@ -2,7 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -from __future__ import print_function import os import gyp diff --git a/gyp/pylib/gyp/generator/gypsh.py b/gyp/pylib/gyp/generator/gypsh.py index 2d8aba5d1c..82a07ddc65 100644 --- a/gyp/pylib/gyp/generator/gypsh.py +++ b/gyp/pylib/gyp/generator/gypsh.py @@ -49,7 +49,7 @@ def GenerateOutput(target_list, target_dicts, data, params): # Use a banner that looks like the stock Python one and like what # code.interact uses by default, but tack on something to indicate what # locals are available, and identify gypsh. - banner = "Python %s on %s\nlocals.keys() = %s\ngypsh" % ( + banner = "Python {} on {}\nlocals.keys() = {}\ngypsh".format( sys.version, sys.platform, repr(sorted(locals.keys())), diff --git a/gyp/pylib/gyp/generator/make.py b/gyp/pylib/gyp/generator/make.py index d163ae3135..e2e4c3ec0d 100644 --- a/gyp/pylib/gyp/generator/make.py +++ b/gyp/pylib/gyp/generator/make.py @@ -21,7 +21,6 @@ # toplevel Makefile. It may make sense to generate some .mk files on # the side to keep the files readable. -from __future__ import print_function import os import re @@ -679,7 +678,7 @@ def SourceifyAndQuoteSpaces(path): target_link_deps = {} -class MakefileWriter(object): +class MakefileWriter: """MakefileWriter packages up the writing of one target-specific foobar.mk. Its only real entry point is Write(), and is mostly used for namespacing. @@ -844,7 +843,7 @@ def Write( sources = [x for x in all_sources if Compilable(x)] if sources: self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT1) - extensions = set([os.path.splitext(s)[1] for s in sources]) + extensions = {os.path.splitext(s)[1] for s in sources} for ext in extensions: if ext in self.suffix_rules_srcdir: self.WriteLn(self.suffix_rules_srcdir[ext]) @@ -910,7 +909,7 @@ def WriteSubMake(self, output_filename, makefile_path, targets, build_dir): self.WriteLn("all:") if makefile_path: makefile_path = " -C " + makefile_path - self.WriteLn("\t$(MAKE)%s %s" % (makefile_path, " ".join(targets))) + self.WriteLn("\t$(MAKE){} {}".format(makefile_path, " ".join(targets))) self.fp.close() def WriteActions( @@ -933,7 +932,7 @@ def WriteActions( env = self.GetSortedXcodeEnv() for action in actions: name = StringToMakefileVariable( - "%s_%s" % (self.qualified_target, action["action_name"]) + "{}_{}".format(self.qualified_target, action["action_name"]) ) self.WriteLn('### Rules for action "%s":' % action["action_name"]) inputs = action["inputs"] @@ -960,9 +959,9 @@ def WriteActions( ] command = gyp.common.EncodePOSIXShellList(action_commands) if "message" in action: - self.WriteLn("quiet_cmd_%s = ACTION %s $@" % (name, action["message"])) + self.WriteLn("quiet_cmd_{} = ACTION {} $@".format(name, action["message"])) else: - self.WriteLn("quiet_cmd_%s = ACTION %s $@" % (name, name)) + self.WriteLn(f"quiet_cmd_{name} = ACTION {name} $@") if len(dirs) > 0: command = "mkdir -p %s" % " ".join(dirs) + "; " + command @@ -1022,7 +1021,7 @@ def WriteActions( # Stuff the outputs in a variable so we can refer to them later. outputs_variable = "action_%s_outputs" % name - self.WriteLn("%s := %s" % (outputs_variable, " ".join(outputs))) + self.WriteLn("{} := {}".format(outputs_variable, " ".join(outputs))) extra_outputs.append("$(%s)" % outputs_variable) self.WriteLn() @@ -1047,7 +1046,7 @@ def WriteRules( env = self.GetSortedXcodeEnv() for rule in rules: name = StringToMakefileVariable( - "%s_%s" % (self.qualified_target, rule["rule_name"]) + "{}_{}".format(self.qualified_target, rule["rule_name"]) ) count = 0 self.WriteLn("### Generated for rule %s:" % name) @@ -1206,7 +1205,7 @@ def WriteCopies(self, copies, extra_outputs, part_of_all): path = gyp.xcode_emulation.ExpandEnvVars(path, env) self.WriteDoCmd([output], [path], "copy", part_of_all) outputs.append(output) - self.WriteLn("%s = %s" % (variable, " ".join(QuoteSpaces(o) for o in outputs))) + self.WriteLn("{} = {}".format(variable, " ".join(QuoteSpaces(o) for o in outputs))) extra_outputs.append("$(%s)" % variable) self.WriteLn() @@ -1364,7 +1363,7 @@ def WriteSources( if pchdeps: self.WriteLn("# Dependencies from obj files to their precompiled headers") for source, obj, gch in pchdeps: - self.WriteLn("%s: %s" % (obj, gch)) + self.WriteLn(f"{obj}: {gch}") self.WriteLn("# End precompiled header dependencies") if objs: @@ -1436,12 +1435,12 @@ def WritePchTargets(self, pch_commands): "mm": "GYP_PCH_OBJCXXFLAGS", }[lang] self.WriteLn( - "%s: %s := %s " % (gch, var_name, lang_flag) + "$(DEFS_$(BUILDTYPE)) " + f"{gch}: {var_name} := {lang_flag} " + "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "$(CFLAGS_$(BUILDTYPE)) " + extra_flags ) - self.WriteLn("%s: %s FORCE_DO_CMD" % (gch, input)) + self.WriteLn(f"{gch}: {input} FORCE_DO_CMD") self.WriteLn("\t@$(call do_cmd,pch_%s,1)" % lang) self.WriteLn("") assert " " not in gch, "Spaces in gch filenames not supported (%s)" % gch @@ -1860,7 +1859,7 @@ def WriteTarget( and self.toolset == "target" ): # On mac, products are created in install_path immediately. - assert install_path == self.output, "%s != %s" % ( + assert install_path == self.output, "{} != {}".format( install_path, self.output, ) @@ -1905,7 +1904,7 @@ def WriteList(self, value_list, variable=None, prefix="", quoter=QuoteIfNecessar if value_list: value_list = [quoter(prefix + value) for value in value_list] values = " \\\n\t" + " \\\n\t".join(value_list) - self.fp.write("%s :=%s\n\n" % (variable, values)) + self.fp.write(f"{variable} :={values}\n\n") def WriteDoCmd( self, outputs, inputs, command, part_of_all, comment=None, postbuilds=False @@ -1922,7 +1921,7 @@ def WriteDoCmd( self.WriteMakeRule( outputs, inputs, - actions=["$(call do_cmd,%s%s)" % (command, suffix)], + actions=[f"$(call do_cmd,{command}{suffix})"], comment=comment, command=command, force=True, @@ -1974,11 +1973,11 @@ def WriteMakeRule( # Order only rule: Just write a simple rule. # TODO(evanm): just make order_only a list of deps instead of this hack. self.WriteLn( - "%s: | %s%s" % (" ".join(outputs), " ".join(inputs), force_append) + "{}: | {}{}".format(" ".join(outputs), " ".join(inputs), force_append) ) elif len(outputs) == 1: # Regular rule, one output: Just write a simple rule. - self.WriteLn("%s: %s%s" % (outputs[0], " ".join(inputs), force_append)) + self.WriteLn("{}: {}{}".format(outputs[0], " ".join(inputs), force_append)) else: # Regular rule, more than one output: Multiple outputs are tricky in # make. We will write three rules: @@ -1994,10 +1993,10 @@ def WriteMakeRule( (command or self.target).encode("utf-8") ).hexdigest() intermediate = "%s.intermediate" % cmddigest - self.WriteLn("%s: %s" % (" ".join(outputs), intermediate)) + self.WriteLn("{}: {}".format(" ".join(outputs), intermediate)) self.WriteLn("\t%s" % "@:") - self.WriteLn("%s: %s" % (".INTERMEDIATE", intermediate)) - self.WriteLn("%s: %s%s" % (intermediate, " ".join(inputs), force_append)) + self.WriteLn("{}: {}".format(".INTERMEDIATE", intermediate)) + self.WriteLn("{}: {}{}".format(intermediate, " ".join(inputs), force_append)) actions.insert(0, "$(call do_cmd,touch)") if actions: @@ -2129,14 +2128,14 @@ def WriteSortedXcodeEnv(self, target, env): # export foo := a\ b # it does not -- the backslash is written to the env as literal character. # So don't escape spaces in |env[k]|. - self.WriteLn("%s: export %s := %s" % (QuoteSpaces(target), k, v)) + self.WriteLn("{}: export {} := {}".format(QuoteSpaces(target), k, v)) def Objectify(self, path): """Convert a path to its output directory form.""" if "$(" in path: path = path.replace("$(obj)/", "$(obj).%s/$(TARGET)/" % self.toolset) if "$(obj)" not in path: - path = "$(obj).%s/$(TARGET)/%s" % (self.toolset, path) + path = f"$(obj).{self.toolset}/$(TARGET)/{path}" return path def Pchify(self, path, lang): @@ -2144,10 +2143,10 @@ def Pchify(self, path, lang): path = self.Absolutify(path) if "$(" in path: path = path.replace( - "$(obj)/", "$(obj).%s/$(TARGET)/pch-%s" % (self.toolset, lang) + "$(obj)/", f"$(obj).{self.toolset}/$(TARGET)/pch-{lang}" ) return path - return "$(obj).%s/$(TARGET)/pch-%s/%s" % (self.toolset, lang, path) + return f"$(obj).{self.toolset}/$(TARGET)/pch-{lang}/{path}" def Absolutify(self, path): """Convert a subdirectory-relative path into a base-relative path. @@ -2219,7 +2218,7 @@ def PerformBuild(data, configurations, params): if options.toplevel_dir and options.toplevel_dir != ".": arguments += "-C", options.toplevel_dir arguments.append("BUILDTYPE=" + config) - print("Building [%s]: %s" % (config, arguments)) + print(f"Building [{config}]: {arguments}") subprocess.check_call(arguments) @@ -2253,7 +2252,7 @@ def CalculateMakefilePath(build_file, base_name): # away when we add verification that all targets have the # necessary configurations. default_configuration = None - toolsets = set([target_dicts[target]["toolset"] for target in target_list]) + toolsets = {target_dicts[target]["toolset"] for target in target_list} for target in target_list: spec = target_dicts[target] if spec["default_configuration"] != "Default": @@ -2362,7 +2361,7 @@ def CalculateMakefilePath(build_file, base_name): value = "$(abspath %s)" % value wrapper = wrappers.get(key) if wrapper: - value = "%s %s" % (wrapper, value) + value = f"{wrapper} {value}" del wrappers[key] if key in ("CC", "CC.host", "CXX", "CXX.host"): make_global_settings += ( @@ -2372,10 +2371,10 @@ def CalculateMakefilePath(build_file, base_name): env_key = key.replace(".", "_") # CC.host -> CC_host if env_key in os.environ: value = os.environ[env_key] - make_global_settings += " %s = %s\n" % (key, value) + make_global_settings += f" {key} = {value}\n" make_global_settings += "endif\n" else: - make_global_settings += "%s ?= %s\n" % (key, value) + make_global_settings += f"{key} ?= {value}\n" # TODO(ukai): define cmd when only wrapper is specified in # make_global_settings. diff --git a/gyp/pylib/gyp/generator/msvs.py b/gyp/pylib/gyp/generator/msvs.py index 96283b2757..e4268bb5ec 100644 --- a/gyp/pylib/gyp/generator/msvs.py +++ b/gyp/pylib/gyp/generator/msvs.py @@ -2,7 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -from __future__ import print_function import ntpath import os @@ -319,7 +318,7 @@ def _ConfigBaseName(config_name, platform_name): def _ConfigFullName(config_name, config_data): platform_name = _ConfigPlatform(config_data) - return "%s|%s" % (_ConfigBaseName(config_name, platform_name), platform_name) + return "{}|{}".format(_ConfigBaseName(config_name, platform_name), platform_name) def _ConfigWindowsTargetPlatformVersion(config_data, version): @@ -614,7 +613,7 @@ def _GenerateNativeRulesForMSVS(p, rules, output_dir, spec, options): spec: the project dict options: global generator options """ - rules_filename = "%s%s.rules" % (spec["target_name"], options.suffix) + rules_filename = "{}{}.rules".format(spec["target_name"], options.suffix) rules_file = MSVSToolFile.Writer( os.path.join(output_dir, rules_filename), spec["target_name"] ) @@ -660,7 +659,7 @@ def _GenerateExternalRules(rules, output_dir, spec, sources, options, actions_to options: global generator options actions_to_add: The list of actions we will add to. """ - filename = "%s_rules%s.mk" % (spec["target_name"], options.suffix) + filename = "{}_rules{}.mk".format(spec["target_name"], options.suffix) mk_file = gyp.common.WriteOnDiff(os.path.join(output_dir, filename)) # Find cygwin style versions of some paths. mk_file.write('OutDirCygwin:=$(shell cygpath -u "$(OutDir)")\n') @@ -703,7 +702,7 @@ def _GenerateExternalRules(rules, output_dir, spec, sources, options, actions_to cmd = ['"%s"' % i for i in cmd] cmd = " ".join(cmd) # Add it to the makefile. - mk_file.write("%s: %s\n" % (" ".join(outputs), " ".join(inputs))) + mk_file.write("{}: {}\n".format(" ".join(outputs), " ".join(inputs))) mk_file.write("\t%s\n\n" % cmd) # Close up the file. mk_file.close() @@ -1570,7 +1569,7 @@ def _AdjustSourcesAndConvertToFilterHierarchy( if version.UsesVcxproj(): while ( all([isinstance(s, MSVSProject.Filter) for s in sources]) - and len(set([s.name for s in sources])) == 1 + and len({s.name for s in sources}) == 1 ): assert all([len(s.contents) == 1 for s in sources]) sources = [s.contents[0] for s in sources] @@ -1776,8 +1775,8 @@ def _GetCopies(spec): base_dir = posixpath.split(src_bare)[0] outer_dir = posixpath.split(src_bare)[1] fixed_dst = _FixPath(dst) - full_dst = '"%s\\%s\\"' % (fixed_dst, outer_dir) - cmd = 'mkdir %s 2>nul & cd "%s" && xcopy /e /f /y "%s" %s' % ( + full_dst = f'"{fixed_dst}\\{outer_dir}\\"' + cmd = 'mkdir {} 2>nul & cd "{}" && xcopy /e /f /y "{}" {}'.format( full_dst, _FixPath(base_dir), outer_dir, @@ -1788,17 +1787,17 @@ def _GetCopies(spec): [src], ["dummy_copies", dst], cmd, - "Copying %s to %s" % (src, fixed_dst), + f"Copying {src} to {fixed_dst}", ) ) else: fix_dst = _FixPath(cpy["destination"]) - cmd = 'mkdir "%s" 2>nul & set ERRORLEVEL=0 & copy /Y "%s" "%s"' % ( + cmd = 'mkdir "{}" 2>nul & set ERRORLEVEL=0 & copy /Y "{}" "{}"'.format( fix_dst, _FixPath(src), _FixPath(dst), ) - copies.append(([src], [dst], cmd, "Copying %s to %s" % (src, fix_dst))) + copies.append(([src], [dst], cmd, f"Copying {src} to {fix_dst}")) return copies @@ -1898,12 +1897,12 @@ def _GetPlatformOverridesOfProject(spec): for config_name, c in spec["configurations"].items(): config_fullname = _ConfigFullName(config_name, c) platform = c.get("msvs_target_platform", _ConfigPlatform(c)) - fixed_config_fullname = "%s|%s" % ( + fixed_config_fullname = "{}|{}".format( _ConfigBaseName(config_name, _ConfigPlatform(c)), platform, ) if spec["toolset"] == "host" and generator_supports_multiple_toolsets: - fixed_config_fullname = "%s|x64" % (config_name,) + fixed_config_fullname = f"{config_name}|x64" config_platform_overrides[config_fullname] = fixed_config_fullname return config_platform_overrides @@ -2056,7 +2055,7 @@ def PerformBuild(data, configurations, params): for config in configurations: arguments = [devenv, sln_path, "/Build", config] - print("Building [%s]: %s" % (config, arguments)) + print(f"Building [{config}]: {arguments}") subprocess.check_call(arguments) @@ -2242,7 +2241,7 @@ def _AppendFiltersForMSBuild( if not parent_filter_name: filter_name = source.name else: - filter_name = "%s\\%s" % (parent_filter_name, source.name) + filter_name = f"{parent_filter_name}\\{source.name}" # Add the filter to the group. filter_group.append( [ @@ -2370,7 +2369,7 @@ def _GenerateRulesForMSBuild( _AdjustSourcesForRules(rules, sources, excluded_sources, True) -class MSBuildRule(object): +class MSBuildRule: """Used to store information used to generate an MSBuild rule. Attributes: @@ -2569,7 +2568,7 @@ def _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules): "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != " "'true'" % (rule.tlog, rule.tlog), "File": "$(IntDir)$(ProjectName).read.1.tlog", - "Lines": "^%%(%s.Source);%%(%s.Inputs)" % (rule.tlog, rule.tlog), + "Lines": f"^%({rule.tlog}.Source);%({rule.tlog}.Inputs)", }, ] command_and_input_section = [ @@ -2915,7 +2914,7 @@ def _GetMSBuildProjectConfigurations(configurations, spec): group = ["ItemGroup", {"Label": "ProjectConfigurations"}] for (name, settings) in sorted(configurations.items()): configuration, platform = _GetConfigurationAndPlatform(name, settings, spec) - designation = "%s|%s" % (configuration, platform) + designation = f"{configuration}|{platform}" group.append( [ "ProjectConfiguration", @@ -3280,13 +3279,11 @@ def GetEdges(node): # Self references are ignored. Self reference is used in a few places to # append to the default value. I.e. PATH=$(PATH);other_path edges.update( - set( - [ + { v for v in MSVS_VARIABLE_REFERENCE.findall(value) if v in properties and v != node - ] - ) + } ) return edges diff --git a/gyp/pylib/gyp/generator/ninja.py b/gyp/pylib/gyp/generator/ninja.py index e064bad7ed..a01d032c4d 100644 --- a/gyp/pylib/gyp/generator/ninja.py +++ b/gyp/pylib/gyp/generator/ninja.py @@ -2,7 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -from __future__ import print_function import collections import copy @@ -99,10 +98,10 @@ def Define(d, flavor): def AddArch(output, arch): """Adds an arch string to an output path.""" output, extension = os.path.splitext(output) - return "%s.%s%s" % (output, arch, extension) + return f"{output}.{arch}{extension}" -class Target(object): +class Target: """Target represents the paths used within a single gyp target. Conceptually, building a single target A is a series of steps: @@ -214,7 +213,7 @@ def FinalOutput(self): # to the input file name as well as the output target name. -class NinjaWriter(object): +class NinjaWriter: def __init__( self, hash_for_rules, @@ -377,7 +376,7 @@ def WriteCollapsedDependencies(self, name, targets, order_only=None): def _SubninjaNameForArch(self, arch): output_file_base = os.path.splitext(self.output_file_name)[0] - return "%s.%s.ninja" % (output_file_base, arch) + return f"{output_file_base}.{arch}.ninja" def WriteSpec(self, spec, config_name, generator_flags): """The main entry point for NinjaWriter: write the build rules for a spec. @@ -418,9 +417,8 @@ def WriteSpec(self, spec, config_name, generator_flags): if self.flavor == "mac": self.archs = self.xcode_settings.GetActiveArchs(config_name) if len(self.archs) > 1: - self.arch_subninjas = dict( - ( - arch, + self.arch_subninjas = { + arch: ninja_syntax.Writer( OpenOutput( os.path.join( @@ -428,10 +426,9 @@ def WriteSpec(self, spec, config_name, generator_flags): ), "w", ) - ), - ) + ) for arch in self.archs - ) + } # Compute predepends for all rules. # actions_depends is the dependencies this target depends on before running @@ -645,9 +642,9 @@ def GenerateDescription(self, verb, message, fallback): if self.toolset != "target": verb += "(%s)" % self.toolset if message: - return "%s %s" % (verb, self.ExpandSpecial(message)) + return "{} {}".format(verb, self.ExpandSpecial(message)) else: - return "%s %s: %s" % (verb, self.name, fallback) + return f"{verb} {self.name}: {fallback}" def WriteActions( self, actions, extra_sources, prebuild, extra_mac_bundle_resources @@ -657,7 +654,7 @@ def WriteActions( all_outputs = [] for action in actions: # First write out a rule for the action. - name = "%s_%s" % (action["action_name"], self.hash_for_rules) + name = "{}_{}".format(action["action_name"], self.hash_for_rules) description = self.GenerateDescription( "ACTION", action.get("message", None), name ) @@ -706,7 +703,7 @@ def WriteRules( continue # First write out a rule for the rule action. - name = "%s_%s" % (rule["rule_name"], self.hash_for_rules) + name = "{}_{}".format(rule["rule_name"], self.hash_for_rules) args = rule["action"] description = self.GenerateDescription( @@ -731,7 +728,7 @@ def WriteRules( # must vary per source file. # Compute the list of variables we'll need to provide. special_locals = ("source", "root", "dirname", "ext", "name") - needed_variables = set(["source"]) + needed_variables = {"source"} for argument in args: for var in special_locals: if "${%s}" % var in argument: @@ -875,7 +872,7 @@ def WriteiOSFrameworkHeaders(self, spec, outputs, prebuild): output = self.GypPathToUniqueOutput("headers.hmap") self.xcode_settings.header_map_path = output all_headers = map( - self.GypPathToNinja, filter(lambda x: x.endswith((".h")), all_sources) + self.GypPathToNinja, filter(lambda x: x.endswith(".h"), all_sources) ) variables = [ ("framework", framework), @@ -1047,9 +1044,8 @@ def WriteSources( spec, ) else: - return dict( - ( - arch, + return { + arch: self.WriteSourcesForArch( self.arch_subninjas[arch], config_name, @@ -1059,10 +1055,9 @@ def WriteSources( precompiled_header, spec, arch=arch, - ), - ) + ) for arch in self.archs - ) + } def WriteSourcesForArch( self, @@ -1842,7 +1837,7 @@ def ComputeOutputFileName(self, spec, type=None): "shared_library", "executable", ): - return "%s%s%s" % (prefix, target, extension) + return f"{prefix}{target}{extension}" elif type == "none": return "%s.stamp" % target else: @@ -2891,7 +2886,7 @@ def PerformBuild(data, configurations, params): for config in configurations: builddir = os.path.join(options.toplevel_dir, "out", config) arguments = ["ninja", "-C", builddir] - print("Building [%s]: %s" % (config, arguments)) + print(f"Building [{config}]: {arguments}") subprocess.check_call(arguments) diff --git a/gyp/pylib/gyp/generator/xcode.py b/gyp/pylib/gyp/generator/xcode.py index 9e7e99e9e1..2f4d17e514 100644 --- a/gyp/pylib/gyp/generator/xcode.py +++ b/gyp/pylib/gyp/generator/xcode.py @@ -2,7 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -from __future__ import print_function import filecmp import gyp.common @@ -110,7 +109,7 @@ def CreateXCConfigurationList(configuration_names): return xccl -class XcodeProject(object): +class XcodeProject: def __init__(self, gyp_path, path, build_file_dict): self.gyp_path = gyp_path self.path = path @@ -613,7 +612,7 @@ def PerformBuild(data, configurations, params): for config in configurations: arguments = ["xcodebuild", "-project", xcodeproj_path] arguments += ["-configuration", config] - print("Building [%s]: %s" % (config, arguments)) + print(f"Building [{config}]: {arguments}") subprocess.check_call(arguments) @@ -1072,7 +1071,7 @@ def GenerateOutput(target_list, target_dicts, data, params): # TODO(mark): There's a possibility for collision here. Consider # target "t" rule "A_r" and target "t_A" rule "r". makefile_name = "%s.make" % re.sub( - "[^a-zA-Z0-9_]", "_", "%s_%s" % (target_name, rule["rule_name"]) + "[^a-zA-Z0-9_]", "_", "{}_{}".format(target_name, rule["rule_name"]) ) makefile_path = os.path.join( xcode_projects[build_file].path, makefile_name @@ -1102,7 +1101,7 @@ def GenerateOutput(target_list, target_dicts, data, params): eol = "" else: eol = " \\" - makefile.write(" %s%s\n" % (concrete_output, eol)) + makefile.write(f" {concrete_output}{eol}\n") for (rule_source, concrete_outputs, message, action) in zip( rule["rule_sources"], @@ -1123,7 +1122,7 @@ def GenerateOutput(target_list, target_dicts, data, params): bol = "" else: bol = " " - makefile.write("%s%s \\\n" % (bol, concrete_output)) + makefile.write(f"{bol}{concrete_output} \\\n") concrete_output_dir = posixpath.dirname(concrete_output) if ( @@ -1143,7 +1142,7 @@ def GenerateOutput(target_list, target_dicts, data, params): eol = "" else: eol = " \\" - makefile.write(" %s%s\n" % (prerequisite, eol)) + makefile.write(f" {prerequisite}{eol}\n") # Make sure that output directories exist before executing the rule # action. diff --git a/gyp/pylib/gyp/input.py b/gyp/pylib/gyp/input.py index 9039776240..7096d96aea 100644 --- a/gyp/pylib/gyp/input.py +++ b/gyp/pylib/gyp/input.py @@ -2,7 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -from __future__ import print_function import ast @@ -234,11 +233,11 @@ def LoadOneBuildFile(build_file_path, data, aux_data, includes, is_target, check if PY3 or sys.platform == "zos": # On z/OS, universal-newlines mode treats the file as an ascii file. # But since node-gyp produces ebcdic files, do not use that mode. - build_file_contents = open(build_file_path, "r").read() + build_file_contents = open(build_file_path).read() else: - build_file_contents = open(build_file_path, "rU").read() + build_file_contents = open(build_file_path).read() else: - raise GypError("%s not found (cwd: %s)" % (build_file_path, os.getcwd())) + raise GypError(f"{build_file_path} not found (cwd: {os.getcwd()})") build_file_data = None try: @@ -567,7 +566,7 @@ class ParallelProcessingError(Exception): pass -class ParallelState(object): +class ParallelState: """Class to keep track of state when processing input files in parallel. If build files are loaded in parallel, use this to keep track of @@ -1219,7 +1218,7 @@ def EvalSingleCondition(cond_expr, true_dict, false_dict, phase, variables, buil except NameError as e: gyp.common.ExceptionAppend( e, - "while evaluating condition '%s' in %s" % (cond_expr_expanded, build_file), + f"while evaluating condition '{cond_expr_expanded}' in {build_file}", ) raise GypError(e) @@ -1675,7 +1674,7 @@ def RemoveLinkDependenciesFromNoneTargets(targets): ) -class DependencyGraphNode(object): +class DependencyGraphNode: """ Attributes: @@ -2252,7 +2251,7 @@ def is_in_set_or_list(x, s, items): # Make membership testing of hashables in |to| (in particular, strings) # faster. - hashable_to_set = set(x for x in to if is_hashable(x)) + hashable_to_set = {x for x in to if is_hashable(x)} for item in fro: singleton = False if type(item) in (str, int): @@ -2772,7 +2771,7 @@ def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules): rule_name = rule["rule_name"] if rule_name in rule_names: raise GypError( - "rule %s exists in duplicate, target %s" % (rule_name, target) + f"rule {rule_name} exists in duplicate, target {target}" ) rule_names[rule_name] = rule diff --git a/gyp/pylib/gyp/mac_tool.py b/gyp/pylib/gyp/mac_tool.py index 07412578d1..da338f6b85 100755 --- a/gyp/pylib/gyp/mac_tool.py +++ b/gyp/pylib/gyp/mac_tool.py @@ -8,7 +8,6 @@ These functions are executed via gyp-mac-tool when using the Makefile generator. """ -from __future__ import print_function import fcntl import fnmatch @@ -33,7 +32,7 @@ def main(args): sys.exit(exit_code) -class MacTool(object): +class MacTool: """This class performs all the Mac tooling steps. The methods can either be executed directly, or dispatched from an argument list.""" @@ -179,7 +178,7 @@ def _DetectInputEncoding(self, file_name): def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys): """Copies the |source| Info.plist to the destination directory |dest|.""" # Read the source Info.plist into memory. - with open(source, "r") as fd: + with open(source) as fd: lines = fd.read() # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild). @@ -251,7 +250,7 @@ def _WritePkgInfo(self, info_plist): dest = os.path.join(os.path.dirname(info_plist), "PkgInfo") with open(dest, "w") as fp: - fp.write("%s%s" % (package_type, signature_code)) + fp.write(f"{package_type}{signature_code}") def ExecFlock(self, lockfile, *cmd_list): """Emulates the most basic behavior of Linux's flock(1).""" @@ -540,7 +539,7 @@ def _FindProvisioningProfile(self, profile, bundle_identifier): "application-identifier", "" ) for team_identifier in profile_data.get("TeamIdentifier", []): - app_id = "%s.%s" % (team_identifier, bundle_identifier) + app_id = f"{team_identifier}.{bundle_identifier}" if fnmatch.fnmatch(app_id, app_id_pattern): valid_provisioning_profiles[app_id_pattern] = ( profile_path, diff --git a/gyp/pylib/gyp/msvs_emulation.py b/gyp/pylib/gyp/msvs_emulation.py index 1afc1d687e..575b74cb84 100644 --- a/gyp/pylib/gyp/msvs_emulation.py +++ b/gyp/pylib/gyp/msvs_emulation.py @@ -193,7 +193,7 @@ def ExtractSharedMSVSSystemIncludes(configs, generator_flags): return expanded_system_includes -class MsvsSettings(object): +class MsvsSettings: """A class that understands the gyp 'msvs_...' values (especially the msvs_settings field). They largely correpond to the VS2008 IDE DOM. This class helps map those settings to command line options.""" @@ -229,7 +229,7 @@ def __init__(self, spec, generator_flags): for config in configs.values(): if field in config: unsupported += [ - "%s not supported (target %s)." % (field, spec["target_name"]) + "{} not supported (target {}).".format(field, spec["target_name"]) ] if unsupported: raise Exception("\n".join(unsupported)) @@ -302,7 +302,7 @@ def _GetAndMunge(self, field, path, default, prefix, append, map): result = _AddPrefix(result, prefix) return _AppendOrReturn(append, result) - class _GetWrapper(object): + class _GetWrapper: def __init__(self, parent, field, base_path, append=None): self.parent = parent self.field = field @@ -709,7 +709,7 @@ def GetLdflags( ) if stack_commit_size: stack_commit_size = "," + stack_commit_size - ldflags.append("/STACK:%s%s" % (stack_reserve_size, stack_commit_size)) + ldflags.append(f"/STACK:{stack_reserve_size}{stack_commit_size}") ld("TerminalServerAware", map={"1": ":NO", "2": ""}, prefix="/TSAWARE") ld("LinkIncremental", map={"1": ":NO", "2": ""}, prefix="/INCREMENTAL") @@ -835,10 +835,10 @@ def _GetLdManifestFlags( - + -""" % ( +""".format( execution_level_map[execution_level], ui_access, ) @@ -932,7 +932,7 @@ def BuildCygwinBashCommandLine(self, args, path_to_base): bash_cmd = " ".join(args) cmd = ( 'call "%s\\setup_env.bat" && set CYGWIN=nontsec && ' % cygwin_dir - + 'bash -c "%s ; %s"' % (cd, bash_cmd) + + f'bash -c "{cd} ; {bash_cmd}"' ) return cmd @@ -1010,7 +1010,7 @@ def _LanguageMatchesForPch(source_ext, pch_source_ext): ) -class PrecompiledHeader(object): +class PrecompiledHeader: """Helper to generate dependencies and build rules to handle generation of precompiled headers. Interface matches the GCH handler in xcode_emulation.py. """ diff --git a/gyp/pylib/gyp/ninja_syntax.py b/gyp/pylib/gyp/ninja_syntax.py index 1421235808..0e3e86c743 100644 --- a/gyp/pylib/gyp/ninja_syntax.py +++ b/gyp/pylib/gyp/ninja_syntax.py @@ -16,7 +16,7 @@ def escape_path(word): return word.replace("$ ", "$$ ").replace(" ", "$ ").replace(":", "$:") -class Writer(object): +class Writer: def __init__(self, output, width=78): self.output = output self.width = width @@ -33,7 +33,7 @@ def variable(self, key, value, indent=0): return if isinstance(value, list): value = " ".join(filter(None, value)) # Filter out empty strings. - self._line("%s = %s" % (key, value), indent) + self._line(f"{key} = {value}", indent) def pool(self, name, depth): self._line("pool %s" % name) @@ -89,7 +89,7 @@ def build( all_inputs.extend(order_only) self._line( - "build %s: %s" % (" ".join(out_outputs), " ".join([rule] + all_inputs)) + "build {}: {}".format(" ".join(out_outputs), " ".join([rule] + all_inputs)) ) if variables: diff --git a/gyp/pylib/gyp/win_tool.py b/gyp/pylib/gyp/win_tool.py index 758e9f5c45..d2751bfe61 100755 --- a/gyp/pylib/gyp/win_tool.py +++ b/gyp/pylib/gyp/win_tool.py @@ -9,7 +9,6 @@ These functions are executed via gyp-win-tool when using the ninja generator. """ -from __future__ import print_function import os import re @@ -34,7 +33,7 @@ def main(args): sys.exit(exit_code) -class WinTool(object): +class WinTool: """This class performs all the Windows tooling steps. The methods can either be executed directly, or dispatched from an argument list.""" @@ -223,8 +222,8 @@ def ExecLinkWithManifests( our_manifest = "%(out)s.manifest" % variables # Load and normalize the manifests. mt.exe sometimes removes whitespace, # and sometimes doesn't unfortunately. - with open(our_manifest, "r") as our_f: - with open(assert_manifest, "r") as assert_f: + with open(our_manifest) as our_f: + with open(assert_manifest) as assert_f: our_data = our_f.read().translate(None, string.whitespace) assert_data = assert_f.read().translate(None, string.whitespace) if our_data != assert_data: @@ -233,7 +232,7 @@ def ExecLinkWithManifests( def dump(filename): print(filename, file=sys.stderr) print("-----", file=sys.stderr) - with open(filename, "r") as f: + with open(filename) as f: print(f.read(), file=sys.stderr) print("-----", file=sys.stderr) @@ -311,7 +310,7 @@ def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, *flags # objidl.idl lines = out.splitlines() prefixes = ("Processing ", "64 bit Processing ") - processing = set(os.path.basename(x) for x in lines if x.startswith(prefixes)) + processing = {os.path.basename(x) for x in lines if x.startswith(prefixes)} for line in lines: if not line.startswith(prefixes) and line not in processing: print(line) diff --git a/gyp/pylib/gyp/xcode_emulation.py b/gyp/pylib/gyp/xcode_emulation.py index a79aaa41fb..012bcb3025 100644 --- a/gyp/pylib/gyp/xcode_emulation.py +++ b/gyp/pylib/gyp/xcode_emulation.py @@ -7,7 +7,6 @@ other build systems, such as make and ninja. """ -from __future__ import print_function import copy import gyp.common @@ -40,7 +39,7 @@ def XcodeArchsVariableMapping(archs, archs_including_64_bit=None): return mapping -class XcodeArchsDefault(object): +class XcodeArchsDefault: """A class to resolve ARCHS variable from xcode_settings, resolving Xcode macros and implementing filtering by VALID_ARCHS. The expansion of macros depends on the SDKROOT used ("macosx", "iphoneos", "iphonesimulator") and @@ -148,7 +147,7 @@ def GetXcodeArchsDefault(): return XCODE_ARCHS_DEFAULT_CACHE -class XcodeSettings(object): +class XcodeSettings: """A class that understands the gyp 'xcode_settings' object.""" # Populated lazily by _SdkPath(). Shared by all XcodeSettings, so cached @@ -281,7 +280,7 @@ def GetWrapperExtension(self): else: return "." + self.spec.get("product_extension", "app") else: - assert False, "Don't know extension for '%s', target '%s'" % ( + assert False, "Don't know extension for '{}', target '{}'".format( self.spec["type"], self.spec["target_name"], ) @@ -1088,7 +1087,7 @@ def _GetStripPostbuilds(self, configname, output_binary, quiet): if not quiet: result.append("echo STRIP\\(%s\\)" % self.spec["target_name"]) - result.append("strip %s %s" % (strip_flags, output_binary)) + result.append(f"strip {strip_flags} {output_binary}") self.configname = None return result @@ -1110,7 +1109,7 @@ def _GetDebugInfoPostbuilds(self, configname, output, output_binary, quiet): ): if not quiet: result.append("echo DSYMUTIL\\(%s\\)" % self.spec["target_name"]) - result.append("dsymutil %s -o %s" % (output_binary, output + ".dSYM")) + result.append("dsymutil {} -o {}".format(output_binary, output + ".dSYM")) self.configname = None return result @@ -1143,7 +1142,7 @@ def _GetIOSPostbuilds(self, configname, output_binary): source = os.path.join("${BUILT_PRODUCTS_DIR}", product_name) test_host = os.path.dirname(settings.get("TEST_HOST")) xctest_destination = os.path.join(test_host, "PlugIns", product_name) - postbuilds.extend(["ditto %s %s" % (source, xctest_destination)]) + postbuilds.extend([f"ditto {source} {xctest_destination}"]) key = self._GetIOSCodeSignIdentityKey(settings) if not key: @@ -1170,7 +1169,7 @@ def _GetIOSPostbuilds(self, configname, output_binary): for framework in frameworks: source = os.path.join(platform_root, framework) destination = os.path.join(frameworks_dir, os.path.basename(framework)) - postbuilds.extend(["ditto %s %s" % (source, destination)]) + postbuilds.extend([f"ditto {source} {destination}"]) # Then re-sign everything with 'preserve=True' postbuilds.extend( @@ -1371,7 +1370,7 @@ def _DefaultSdkRoot(self): return "" -class MacPrefixHeader(object): +class MacPrefixHeader: """A class that helps with emulating Xcode's GCC_PREFIX_HEADER feature. This feature consists of several pieces: @@ -1871,7 +1870,7 @@ def GetEdges(node): # definition contains all variables it references in a single string. # We can then reverse the result of the topological sort at the end. # Since: reverse(topsort(DAG)) = topsort(reverse_edges(DAG)) - matches = set([v for v in regex.findall(env[node]) if v in env]) + matches = {v for v in regex.findall(env[node]) if v in env} for dependee in matches: assert "${" not in dependee, "Nested variables not supported: " + dependee return matches diff --git a/gyp/pylib/gyp/xcode_ninja.py b/gyp/pylib/gyp/xcode_ninja.py index 10ddcbccd0..bb74eacbea 100644 --- a/gyp/pylib/gyp/xcode_ninja.py +++ b/gyp/pylib/gyp/xcode_ninja.py @@ -43,11 +43,11 @@ def _WriteWorkspace(main_gyp, sources_gyp, params): workspace_file = os.path.join(workspace_path, "contents.xcworkspacedata") try: - with open(workspace_file, "r") as input_file: + with open(workspace_file) as input_file: input_string = input_file.read() if input_string == output_string: return - except IOError: + except OSError: # Ignore errors if the file doesn't exist. pass @@ -214,7 +214,7 @@ def CreateWrapper(target_list, target_dicts, data, params): if IsValidTargetForWrapper(target_extras, executable_target_pattern, spec): # Add to new_target_list. target_name = spec.get("target_name") - new_target_name = "%s:%s#target" % (main_gyp, target_name) + new_target_name = f"{main_gyp}:{target_name}#target" new_target_list.append(new_target_name) # Add to new_target_dicts. @@ -282,7 +282,7 @@ def CreateWrapper(target_list, target_dicts, data, params): # Put sources_to_index in it's own gyp. sources_gyp = os.path.join(os.path.dirname(main_gyp), sources_target_name + ".gyp") - fully_qualified_target_name = "%s:%s#target" % (sources_gyp, sources_target_name) + fully_qualified_target_name = f"{sources_gyp}:{sources_target_name}#target" # Add to new_target_list, new_target_dicts and new_data. new_target_list.append(fully_qualified_target_name) diff --git a/gyp/pylib/gyp/xcodeproj_file.py b/gyp/pylib/gyp/xcodeproj_file.py index d90dd99dcc..e8a3f29427 100644 --- a/gyp/pylib/gyp/xcodeproj_file.py +++ b/gyp/pylib/gyp/xcodeproj_file.py @@ -199,7 +199,7 @@ def ConvertVariablesToShellSyntax(input_string): return re.sub(r"\$\((.*?)\)", "${\\1}", input_string) -class XCObject(object): +class XCObject: """The abstract base of all class types used in Xcode project files. Class variables: @@ -301,8 +301,8 @@ def __repr__(self): try: name = self.Name() except NotImplementedError: - return "<%s at 0x%x>" % (self.__class__.__name__, id(self)) - return "<%s %r at 0x%x>" % (self.__class__.__name__, name, id(self)) + return "<{} at 0x{:x}>".format(self.__class__.__name__, id(self)) + return "<{} {!r} at 0x{:x}>".format(self.__class__.__name__, name, id(self)) def Copy(self): """Make a copy of this object. @@ -2185,7 +2185,7 @@ def SetDestination(self, path): relative_path = path[1:] else: raise ValueError( - "Can't use path %s in a %s" % (path, self.__class__.__name__) + f"Can't use path {path} in a {self.__class__.__name__}" ) self._properties["dstPath"] = relative_path @@ -2250,8 +2250,8 @@ class PBXContainerItemProxy(XCObject): def __repr__(self): props = self._properties - name = "%s.gyp:%s" % (props["containerPortal"].Name(), props["remoteInfo"]) - return "<%s %r at 0x%x>" % (self.__class__.__name__, name, id(self)) + name = "{}.gyp:{}".format(props["containerPortal"].Name(), props["remoteInfo"]) + return "<{} {!r} at 0x{:x}>".format(self.__class__.__name__, name, id(self)) def Name(self): # Admittedly not the best name, but it's what Xcode uses. @@ -2288,7 +2288,7 @@ class PBXTargetDependency(XCObject): def __repr__(self): name = self._properties.get("name") or self._properties["target"].Name() - return "<%s %r at 0x%x>" % (self.__class__.__name__, name, id(self)) + return "<{} {!r} at 0x{:x}>".format(self.__class__.__name__, name, id(self)) def Name(self): # Admittedly not the best name, but it's what Xcode uses. diff --git a/gyp/pylib/gyp/xml_fix.py b/gyp/pylib/gyp/xml_fix.py index 0a945322b4..5301963669 100644 --- a/gyp/pylib/gyp/xml_fix.py +++ b/gyp/pylib/gyp/xml_fix.py @@ -39,12 +39,12 @@ def _Replacement_writexml(self, writer, indent="", addindent="", newl=""): writer.write(">%s" % newl) for node in self.childNodes: node.writexml(writer, indent + addindent, addindent, newl) - writer.write("%s%s" % (indent, self.tagName, newl)) + writer.write(f"{indent}{newl}") else: writer.write("/>%s" % newl) -class XmlFix(object): +class XmlFix: """Object to manage temporary patching of xml.dom.minidom.""" def __init__(self): diff --git a/gyp/setup.py b/gyp/setup.py index 766a7651ba..02ebd4949e 100644 --- a/gyp/setup.py +++ b/gyp/setup.py @@ -25,7 +25,7 @@ package_dir={"": "pylib"}, packages=["gyp", "gyp.generator"], entry_points={"console_scripts": ["gyp=gyp:script_main"]}, - python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*", + python_requires=">=3.5", classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Console", @@ -33,12 +33,11 @@ "License :: OSI Approved :: BSD License", "Natural Language :: English", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", ], ) diff --git a/gyp/test_gyp.py b/gyp/test_gyp.py index 382e75272d..8ee2e48c1e 100755 --- a/gyp/test_gyp.py +++ b/gyp/test_gyp.py @@ -5,7 +5,6 @@ """gyptest.py -- test runner for GYP tests.""" -from __future__ import print_function import argparse import os @@ -153,7 +152,7 @@ def print_configuration_info(): sys.path.append(os.path.abspath("test/lib")) import TestMac - print(" Mac %s %s" % (platform.mac_ver()[0], platform.mac_ver()[2])) + print(" Mac {} {}".format(platform.mac_ver()[0], platform.mac_ver()[2])) print(" Xcode %s" % TestMac.Xcode.Version()) elif sys.platform == "win32": sys.path.append(os.path.abspath("pylib")) @@ -168,7 +167,7 @@ def print_configuration_info(): print() -class Runner(object): +class Runner: def __init__(self, formats, tests, gyp_options, verbose): self.formats = formats self.tests = tests @@ -217,10 +216,10 @@ def run_test(self, test, fmt, i): res = "skipped" elif proc.returncode: res = "failed" - self.failures.append("(%s) %s" % (test, fmt)) + self.failures.append(f"({test}) {fmt}") else: res = "passed" - res_msg = " %s %.3fs" % (res, took) + res_msg = f" {res} {took:.3f}s" self.print_(res_msg) if ( diff --git a/gyp/tools/graphviz.py b/gyp/tools/graphviz.py index 1f3acf37fc..9005d2c55a 100755 --- a/gyp/tools/graphviz.py +++ b/gyp/tools/graphviz.py @@ -8,7 +8,6 @@ generate input suitable for graphviz to render a dependency graph of targets.""" -from __future__ import print_function import collections import json @@ -66,7 +65,7 @@ def WriteGraph(edges): target = targets[0] build_file, target_name, toolset = ParseTarget(target) print( - ' "%s" [shape=box, label="%s\\n%s"]' % (target, filename, target_name) + f' "{target}" [shape=box, label="{filename}\\n{target_name}"]' ) else: # Group multiple nodes together in a subgraph. @@ -74,14 +73,14 @@ def WriteGraph(edges): print(' label = "%s"' % filename) for target in targets: build_file, target_name, toolset = ParseTarget(target) - print(' "%s" [label="%s"]' % (target, target_name)) + print(f' "{target}" [label="{target_name}"]') print(" }") # Now that we've placed all the nodes within subgraphs, output all # the edges between nodes. for src, dsts in edges.items(): for dst in dsts: - print(' "%s" -> "%s"' % (src, dst)) + print(f' "{src}" -> "{dst}"') print("}") diff --git a/gyp/tools/pretty_gyp.py b/gyp/tools/pretty_gyp.py index 7313b4fe1b..c8c7578fda 100755 --- a/gyp/tools/pretty_gyp.py +++ b/gyp/tools/pretty_gyp.py @@ -6,7 +6,6 @@ """Pretty-prints the contents of a GYP file.""" -from __future__ import print_function import sys import re @@ -34,7 +33,7 @@ def mask_comments(input): def quote_replace(matchobj): - return "%s%s%s%s" % ( + return "{}{}{}{}".format( matchobj.group(1), matchobj.group(2), "x" * len(matchobj.group(3)), diff --git a/gyp/tools/pretty_sln.py b/gyp/tools/pretty_sln.py index 2b1cb1de74..87c03b8880 100755 --- a/gyp/tools/pretty_sln.py +++ b/gyp/tools/pretty_sln.py @@ -12,7 +12,6 @@ Then it outputs a possible build order. """ -from __future__ import print_function import os import re diff --git a/gyp/tools/pretty_vcproj.py b/gyp/tools/pretty_vcproj.py index b171fae6cf..01802fa91d 100755 --- a/gyp/tools/pretty_vcproj.py +++ b/gyp/tools/pretty_vcproj.py @@ -12,7 +12,6 @@ It outputs the resulting xml to stdout. """ -from __future__ import print_function import os import sys @@ -34,14 +33,14 @@ def cmp(x, y): ARGUMENTS = None -class CmpTuple(object): +class CmpTuple: """Compare function between 2 tuple.""" def __call__(self, x, y): return cmp(x[0], y[0]) -class CmpNode(object): +class CmpNode: """Compare function between 2 xml nodes.""" def __call__(self, x, y): @@ -72,7 +71,7 @@ def get_string(node): def PrettyPrintNode(node, indent=0): if node.nodeType == Node.TEXT_NODE: if node.data.strip(): - print("%s%s" % (" " * indent, node.data.strip())) + print("{}{}".format(" " * indent, node.data.strip())) return if node.childNodes: @@ -84,23 +83,23 @@ def PrettyPrintNode(node, indent=0): # Print the main tag if attr_count == 0: - print("%s<%s>" % (" " * indent, node.nodeName)) + print("{}<{}>".format(" " * indent, node.nodeName)) else: - print("%s<%s" % (" " * indent, node.nodeName)) + print("{}<{}".format(" " * indent, node.nodeName)) all_attributes = [] for (name, value) in node.attributes.items(): all_attributes.append((name, value)) all_attributes.sort(CmpTuple()) for (name, value) in all_attributes: - print('%s %s="%s"' % (" " * indent, name, value)) + print('{} {}="{}"'.format(" " * indent, name, value)) print("%s>" % (" " * indent)) if node.nodeValue: - print("%s %s" % (" " * indent, node.nodeValue)) + print("{} {}".format(" " * indent, node.nodeValue)) for sub_node in node.childNodes: PrettyPrintNode(sub_node, indent=indent + 2) - print("%s" % (" " * indent, node.nodeName)) + print("{}".format(" " * indent, node.nodeName)) def FlattenFilter(node): diff --git a/test/fixtures/test-charmap.py b/test/fixtures/test-charmap.py index b338f915bc..033eb9bcf4 100644 --- a/test/fixtures/test-charmap.py +++ b/test/fixtures/test-charmap.py @@ -1,4 +1,3 @@ -from __future__ import print_function import sys import locale @@ -18,9 +17,9 @@ def main(): pass textmap = { - 'cp936': u'\u4e2d\u6587', - 'cp1252': u'Lat\u012Bna', - 'cp932': u'\u306b\u307b\u3093\u3054' + 'cp936': '\u4e2d\u6587', + 'cp1252': 'Lat\u012Bna', + 'cp932': '\u306b\u307b\u3093\u3054' } if encoding in textmap: print(textmap[encoding])