summaryrefslogtreecommitdiff
path: root/tools
diff options
context:
space:
mode:
authorcclauss <cclauss@me.com>2019-07-05 18:39:16 +0200
committerRich Trott <rtrott@gmail.com>2019-07-16 10:40:31 -0700
commit54fcb14467b59e82d6e24bf44803462226a5de4d (patch)
tree21aceef7b5250e29be01f01e6451892a1d191a4e /tools
parent7032e59bb550adcb448b2d24877921e7f97e7399 (diff)
downloadandroid-node-v8-54fcb14467b59e82d6e24bf44803462226a5de4d.tar.gz
android-node-v8-54fcb14467b59e82d6e24bf44803462226a5de4d.tar.bz2
android-node-v8-54fcb14467b59e82d6e24bf44803462226a5de4d.zip
gyp: cherrypick more Python3 changes from node-gyp
PR-URL: https://github.com/nodejs/node/pull/28563 Reviewed-By: Richard Lau <riclau@uk.ibm.com> Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl> Reviewed-By: Rich Trott <rtrott@gmail.com>
Diffstat (limited to 'tools')
-rw-r--r--tools/gyp/pylib/gyp/MSVSSettings.py40
-rw-r--r--tools/gyp/pylib/gyp/MSVSUtil.py2
-rw-r--r--tools/gyp/pylib/gyp/MSVSVersion.py14
-rw-r--r--tools/gyp/pylib/gyp/common.py10
-rw-r--r--tools/gyp/pylib/gyp/easy_xml.py3
-rw-r--r--tools/gyp/pylib/gyp/generator/cmake.py16
-rw-r--r--tools/gyp/pylib/gyp/generator/make.py24
-rw-r--r--tools/gyp/pylib/gyp/generator/msvs.py82
-rw-r--r--tools/gyp/pylib/gyp/generator/ninja.py20
-rw-r--r--tools/gyp/pylib/gyp/generator/xcode.py34
-rwxr-xr-xtools/gyp/pylib/gyp/mac_tool.py20
-rw-r--r--tools/gyp/pylib/gyp/msvs_emulation.py6
-rwxr-xr-xtools/gyp/pylib/gyp/win_tool.py14
-rw-r--r--tools/gyp/pylib/gyp/xcode_emulation.py36
-rw-r--r--tools/gyp/pylib/gyp/xcode_ninja.py6
-rw-r--r--tools/gyp/pylib/gyp/xcodeproj_file.py51
16 files changed, 198 insertions, 180 deletions
diff --git a/tools/gyp/pylib/gyp/MSVSSettings.py b/tools/gyp/pylib/gyp/MSVSSettings.py
index 58ce0bb1ed..0f53ff87c7 100644
--- a/tools/gyp/pylib/gyp/MSVSSettings.py
+++ b/tools/gyp/pylib/gyp/MSVSSettings.py
@@ -14,6 +14,10 @@ The MSBuild schemas were also considered. They are typically found in the
MSBuild install directory, e.g. c:\Program Files (x86)\MSBuild
"""
+from __future__ import print_function
+
+from gyp import string_types
+
import sys
import re
@@ -106,11 +110,11 @@ class _String(_Type):
"""A setting that's just a string."""
def ValidateMSVS(self, value):
- if not isinstance(value, basestring):
+ if not isinstance(value, string_types):
raise ValueError('expected string; got %r' % value)
def ValidateMSBuild(self, value):
- if not isinstance(value, basestring):
+ if not isinstance(value, string_types):
raise ValueError('expected string; got %r' % value)
def ConvertToMSBuild(self, value):
@@ -122,11 +126,11 @@ class _StringList(_Type):
"""A settings that's a list of strings."""
def ValidateMSVS(self, value):
- if not isinstance(value, basestring) and not isinstance(value, list):
+ if not isinstance(value, string_types) and not isinstance(value, list):
raise ValueError('expected string list; got %r' % value)
def ValidateMSBuild(self, value):
- if not isinstance(value, basestring) and not isinstance(value, list):
+ if not isinstance(value, string_types) and not isinstance(value, list):
raise ValueError('expected string list; got %r' % value)
def ConvertToMSBuild(self, value):
@@ -400,7 +404,7 @@ def _ValidateExclusionSetting(setting, settings, error_msg, stderr=sys.stderr):
if unrecognized:
# We don't know this setting. Give a warning.
- print >> stderr, error_msg
+ print(error_msg, file=stderr)
def FixVCMacroSlashes(s):
@@ -433,7 +437,7 @@ def ConvertVCMacrosToMSBuild(s):
'$(PlatformName)': '$(Platform)',
'$(SafeInputName)': '%(Filename)',
}
- for old, new in replace_map.iteritems():
+ for old, new in replace_map.items():
s = s.replace(old, new)
s = FixVCMacroSlashes(s)
return s
@@ -453,17 +457,17 @@ def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr):
dictionaries of settings and their values.
"""
msbuild_settings = {}
- for msvs_tool_name, msvs_tool_settings in msvs_settings.iteritems():
+ for msvs_tool_name, msvs_tool_settings in msvs_settings.items():
if msvs_tool_name in _msvs_to_msbuild_converters:
msvs_tool = _msvs_to_msbuild_converters[msvs_tool_name]
- for msvs_setting, msvs_value in msvs_tool_settings.iteritems():
+ for msvs_setting, msvs_value in msvs_tool_settings.items():
if msvs_setting in msvs_tool:
# Invoke the translation function.
try:
msvs_tool[msvs_setting](msvs_value, msbuild_settings)
- except ValueError, e:
- print >> stderr, ('Warning: while converting %s/%s to MSBuild, '
- '%s' % (msvs_tool_name, msvs_setting, e))
+ except ValueError as e:
+ print('Warning: while converting %s/%s to MSBuild, '
+ '%s' % (msvs_tool_name, msvs_setting, e), file=stderr)
else:
_ValidateExclusionSetting(msvs_setting,
msvs_tool,
@@ -472,8 +476,8 @@ def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr):
(msvs_tool_name, msvs_setting)),
stderr)
else:
- print >> stderr, ('Warning: unrecognized tool %s while converting to '
- 'MSBuild.' % msvs_tool_name)
+ print('Warning: unrecognized tool %s while converting to '
+ 'MSBuild.' % msvs_tool_name, file=stderr)
return msbuild_settings
@@ -513,13 +517,13 @@ def _ValidateSettings(validators, settings, stderr):
for tool_name in settings:
if tool_name in validators:
tool_validators = validators[tool_name]
- for setting, value in settings[tool_name].iteritems():
+ for setting, value in settings[tool_name].items():
if setting in tool_validators:
try:
tool_validators[setting](value)
- except ValueError, e:
- print >> stderr, ('Warning: for %s/%s, %s' %
- (tool_name, setting, e))
+ except ValueError as e:
+ print('Warning: for %s/%s, %s' % (tool_name, setting, e),
+ file=stderr)
else:
_ValidateExclusionSetting(setting,
tool_validators,
@@ -528,7 +532,7 @@ def _ValidateSettings(validators, settings, stderr):
stderr)
else:
- print >> stderr, ('Warning: unrecognized tool %s' % tool_name)
+ print('Warning: unrecognized tool %s' % (tool_name), file=stderr)
# MSVS and MBuild names of the tools.
diff --git a/tools/gyp/pylib/gyp/MSVSUtil.py b/tools/gyp/pylib/gyp/MSVSUtil.py
index 96dea6c2c9..f24530b275 100644
--- a/tools/gyp/pylib/gyp/MSVSUtil.py
+++ b/tools/gyp/pylib/gyp/MSVSUtil.py
@@ -236,7 +236,7 @@ def InsertLargePdbShims(target_list, target_dicts, vars):
# Set up the shim to output its PDB to the same location as the final linker
# target.
- for config_name, config in shim_dict.get('configurations').iteritems():
+ for config_name, config in shim_dict.get('configurations').items():
pdb_path = _GetPdbPath(target_dict, config_name, vars)
# A few keys that we don't want to propagate.
diff --git a/tools/gyp/pylib/gyp/MSVSVersion.py b/tools/gyp/pylib/gyp/MSVSVersion.py
index 48a3151f81..a207abaa18 100644
--- a/tools/gyp/pylib/gyp/MSVSVersion.py
+++ b/tools/gyp/pylib/gyp/MSVSVersion.py
@@ -189,7 +189,7 @@ def _RegistryQuery(key, value=None):
text = None
try:
text = _RegistryQueryBase('Sysnative', key, value)
- except OSError, e:
+ except OSError as e:
if e.errno == errno.ENOENT:
text = _RegistryQueryBase('System32', key, value)
else:
@@ -207,12 +207,18 @@ def _RegistryGetValueUsingWinReg(key, value):
contents of the registry key's value, or None on failure. Throws
ImportError if _winreg is unavailable.
"""
- import _winreg
+ try:
+ # Python 2
+ from _winreg import HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx
+ except ImportError:
+ # Python 3
+ from winreg import HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx
+
try:
root, subkey = key.split('\\', 1)
assert root == 'HKLM' # Only need HKLM for now.
- with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey) as hkey:
- return _winreg.QueryValueEx(hkey, value)[0]
+ with OpenKey(HKEY_LOCAL_MACHINE, subkey) as hkey:
+ return QueryValueEx(hkey, value)[0]
except WindowsError:
return None
diff --git a/tools/gyp/pylib/gyp/common.py b/tools/gyp/pylib/gyp/common.py
index a1e1db5f12..cfee9d4592 100644
--- a/tools/gyp/pylib/gyp/common.py
+++ b/tools/gyp/pylib/gyp/common.py
@@ -2,8 +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 with_statement
-
import collections
import errno
import filecmp
@@ -363,7 +361,7 @@ def WriteOnDiff(filename):
same = False
try:
same = filecmp.cmp(self.tmp_path, filename, False)
- except OSError, e:
+ except OSError as e:
if e.errno != errno.ENOENT:
raise
@@ -382,9 +380,9 @@ def WriteOnDiff(filename):
#
# No way to get the umask without setting a new one? Set a safe one
# and then set it back to the old value.
- umask = os.umask(077)
+ umask = os.umask(0o77)
os.umask(umask)
- os.chmod(self.tmp_path, 0666 & ~umask)
+ os.chmod(self.tmp_path, 0o666 & ~umask)
if sys.platform == 'win32' and os.path.exists(filename):
# NOTE: on windows (but not cygwin) rename will not replace an
# existing file, so it must be preceded with a remove. Sadly there
@@ -467,7 +465,7 @@ def CopyTool(flavor, out_path, generator_flags={}):
''.join([source[0], header] + source[1:]))
# Make file executable.
- os.chmod(tool_path, 0755)
+ os.chmod(tool_path, 0o755)
# From Alex Martelli,
diff --git a/tools/gyp/pylib/gyp/easy_xml.py b/tools/gyp/pylib/gyp/easy_xml.py
index 2522efb244..acccb47b75 100644
--- a/tools/gyp/pylib/gyp/easy_xml.py
+++ b/tools/gyp/pylib/gyp/easy_xml.py
@@ -5,6 +5,7 @@
import re
import os
import locale
+from functools import reduce
def XmlToString(content, encoding='utf-8', pretty=False):
@@ -80,7 +81,7 @@ def _ConstructContentList(xml_parts, specification, pretty, level=0):
# Optionally in second position is a dictionary of the attributes.
rest = specification[1:]
if rest and isinstance(rest[0], dict):
- for at, val in sorted(rest[0].iteritems()):
+ for at, val in sorted(rest[0].items()):
xml_parts.append(' %s="%s"' % (at, _XmlEscape(val, attr=True)))
rest = rest[1:]
if rest:
diff --git a/tools/gyp/pylib/gyp/generator/cmake.py b/tools/gyp/pylib/gyp/generator/cmake.py
index a2b96291aa..74b0c715e3 100644
--- a/tools/gyp/pylib/gyp/generator/cmake.py
+++ b/tools/gyp/pylib/gyp/generator/cmake.py
@@ -28,6 +28,8 @@ not be able to find the header file directories described in the generated
CMakeLists.txt file.
"""
+from __future__ import print_function
+
import multiprocessing
import os
import signal
@@ -644,8 +646,8 @@ def WriteTarget(namer, qualified_target, target_dicts, build_dir, config_to_use,
cmake_target_type = cmake_target_type_from_gyp_target_type.get(target_type)
if cmake_target_type is None:
- print ('Target %s has unknown target type %s, skipping.' %
- ( target_name, target_type ) )
+ print('Target %s has unknown target type %s, skipping.' %
+ ( target_name, target_type))
return
SetVariable(output, 'TARGET', target_name)
@@ -868,8 +870,8 @@ def WriteTarget(namer, qualified_target, target_dicts, build_dir, config_to_use,
default_product_ext = generator_default_variables['SHARED_LIB_SUFFIX']
elif target_type != 'executable':
- print ('ERROR: What output file should be generated?',
- 'type', target_type, 'target', target_name)
+ print('ERROR: What output file should be generated?',
+ 'type', target_type, 'target', target_name)
product_prefix = spec.get('product_prefix', default_product_prefix)
product_name = spec.get('product_name', default_product_name)
@@ -1207,11 +1209,11 @@ def PerformBuild(data, configurations, params):
output_dir,
config_name))
arguments = ['cmake', '-G', 'Ninja']
- print 'Generating [%s]: %s' % (config_name, arguments)
+ print('Generating [%s]: %s' % (config_name, arguments))
subprocess.check_call(arguments, cwd=build_dir)
arguments = ['ninja', '-C', build_dir]
- print 'Building [%s]: %s' % (config_name, arguments)
+ print('Building [%s]: %s' % (config_name, arguments))
subprocess.check_call(arguments)
@@ -1239,7 +1241,7 @@ def GenerateOutput(target_list, target_dicts, data, params):
arglists.append((target_list, target_dicts, data,
params, config_name))
pool.map(CallGenerateOutputForConfig, arglists)
- except KeyboardInterrupt, e:
+ except KeyboardInterrupt as e:
pool.terminate()
raise e
else:
diff --git a/tools/gyp/pylib/gyp/generator/make.py b/tools/gyp/pylib/gyp/generator/make.py
index e98d93ab23..e43413c167 100644
--- a/tools/gyp/pylib/gyp/generator/make.py
+++ b/tools/gyp/pylib/gyp/generator/make.py
@@ -21,6 +21,8 @@
# 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
import sys
@@ -650,7 +652,7 @@ def _ValidateSourcesForOSX(spec, all_sources):
basenames.setdefault(basename, []).append(source)
error = ''
- for basename, files in basenames.iteritems():
+ for basename, files in basenames.items():
if len(files) > 1:
error += ' %s: %s\n' % (basename, ' '.join(files))
@@ -1202,16 +1204,16 @@ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD
cflags_c = config.get('cflags_c')
cflags_cc = config.get('cflags_cc')
- self.WriteLn("# Flags passed to all source files.");
+ self.WriteLn("# Flags passed to all source files.")
self.WriteList(cflags, 'CFLAGS_%s' % configname)
- self.WriteLn("# Flags passed to only C files.");
+ self.WriteLn("# Flags passed to only C files.")
self.WriteList(cflags_c, 'CFLAGS_C_%s' % configname)
- self.WriteLn("# Flags passed to only C++ files.");
+ self.WriteLn("# Flags passed to only C++ files.")
self.WriteList(cflags_cc, 'CFLAGS_CC_%s' % configname)
if self.flavor == 'mac':
- self.WriteLn("# Flags passed to only ObjC files.");
+ self.WriteLn("# Flags passed to only ObjC files.")
self.WriteList(cflags_objc, 'CFLAGS_OBJC_%s' % configname)
- self.WriteLn("# Flags passed to only ObjC++ files.");
+ self.WriteLn("# Flags passed to only ObjC++ files.")
self.WriteList(cflags_objcc, 'CFLAGS_OBJCC_%s' % configname)
includes = config.get('include_dirs')
if includes:
@@ -1359,8 +1361,8 @@ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD
elif self.type == 'none':
target = '%s.stamp' % target
elif self.type != 'executable':
- print ("ERROR: What output file should be generated?",
- "type", self.type, "target", target)
+ print("ERROR: What output file should be generated?",
+ "type", self.type, "target", target)
target_prefix = spec.get('product_prefix', target_prefix)
target = spec.get('product_name', target)
@@ -1524,7 +1526,7 @@ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD
# Postbuilds expect to be run in the gyp file's directory, so insert an
# implicit postbuild to cd to there.
postbuilds.insert(0, gyp.common.EncodePOSIXShellList(['cd', self.path]))
- for i in xrange(len(postbuilds)):
+ for i in range(len(postbuilds)):
if not postbuilds[i].startswith('$'):
postbuilds[i] = EscapeShellArgument(postbuilds[i])
self.WriteLn('%s: builddir := $(abs_builddir)' % QuoteSpaces(self.output))
@@ -1616,7 +1618,7 @@ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD
self.WriteDoCmd([self.output_binary], deps, 'touch', part_of_all,
postbuilds=postbuilds)
else:
- print "WARNING: no output for", self.type, target
+ print("WARNING: no output for", self.type, self.target)
# Add an alias for each target (if there are any outputs).
# Installable target aliases are created below.
@@ -1968,7 +1970,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('Building [%s]: %s' % (config, arguments))
subprocess.check_call(arguments)
diff --git a/tools/gyp/pylib/gyp/generator/msvs.py b/tools/gyp/pylib/gyp/generator/msvs.py
index dbde9e279e..3a9e6a7aa5 100644
--- a/tools/gyp/pylib/gyp/generator/msvs.py
+++ b/tools/gyp/pylib/gyp/generator/msvs.py
@@ -2,6 +2,8 @@
# 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 ntpath
import os
@@ -315,10 +317,8 @@ def _ConfigWindowsTargetPlatformVersion(config_data, version):
if names:
return names[0]
else:
- print >> sys.stdout, (
- 'Warning: No include files found for '
- 'detected Windows SDK version %s' % (version)
- )
+ print('Warning: No include files found for detected '
+ 'Windows SDK version %s' % (version), file=sys.stdout)
def _BuildCommandLineForRuleRaw(spec, cmd, cygwin_shell, has_input_path,
@@ -469,7 +469,7 @@ def _AddCustomBuildToolForMSVS(p, spec, primary_input,
'CommandLine': cmd,
})
# Add to the properties of primary input for each config.
- for config_name, c_data in spec['configurations'].iteritems():
+ for config_name, c_data in spec['configurations'].items():
p.AddFileConfig(_FixPath(primary_input),
_ConfigFullName(config_name, c_data), tools=[tool])
@@ -775,8 +775,8 @@ def _EscapeVCProjCommandLineArgListItem(s):
# the VCProj but cause the same problem on the final command-line. Moving
# the item to the end of the list does works, but that's only possible if
# there's only one such item. Let's just warn the user.
- print >> sys.stderr, ('Warning: MSVS may misinterpret the odd number of ' +
- 'quotes in ' + s)
+ print('Warning: MSVS may misinterpret the odd number of '
+ 'quotes in ' + s, file=sys.stderr)
return s
@@ -991,7 +991,7 @@ def _ValidateSourcesForMSVSProject(spec, version):
basenames.setdefault(basename, []).append(source)
error = ''
- for basename, files in basenames.iteritems():
+ for basename, files in basenames.items():
if len(files) > 1:
error += ' %s: %s\n' % (basename, ' '.join(files))
@@ -1023,7 +1023,7 @@ def _GenerateMSVSProject(project, options, version, generator_flags):
relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir)
config_type = _GetMSVSConfigurationType(spec, project.build_file)
- for config_name, config in spec['configurations'].iteritems():
+ for config_name, config in spec['configurations'].items():
_AddConfigurationToMSVSProject(p, spec, config_type, config_name, config)
# MSVC08 and prior version cannot handle duplicate basenames in the same
@@ -1392,10 +1392,10 @@ def _ConvertToolsToExpectedForm(tools):
A list of Tool objects.
"""
tool_list = []
- for tool, settings in tools.iteritems():
+ for tool, settings in tools.items():
# Collapse settings with lists.
settings_fixed = {}
- for setting, value in settings.iteritems():
+ for setting, value in settings.items():
if type(value) == list:
if ((tool == 'VCLinkerTool' and
setting == 'AdditionalDependencies') or
@@ -1570,7 +1570,7 @@ def _IdlFilesHandledNonNatively(spec, sources):
def _GetPrecompileRelatedFiles(spec):
# Gather a list of precompiled header related sources.
precompiled_related = []
- for _, config in spec['configurations'].iteritems():
+ for _, config in spec['configurations'].items():
for k in precomp_keys:
f = config.get(k)
if f:
@@ -1581,7 +1581,7 @@ def _GetPrecompileRelatedFiles(spec):
def _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl,
list_excluded):
exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl)
- for file_name, excluded_configs in exclusions.iteritems():
+ for file_name, excluded_configs in exclusions.items():
if (not list_excluded and
len(excluded_configs) == len(spec['configurations'])):
# If we're not listing excluded files, then they won't appear in the
@@ -1598,7 +1598,7 @@ def _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl):
# Exclude excluded sources from being built.
for f in excluded_sources:
excluded_configs = []
- for config_name, config in spec['configurations'].iteritems():
+ for config_name, config in spec['configurations'].items():
precomped = [_FixPath(config.get(i, '')) for i in precomp_keys]
# Don't do this for ones that are precompiled header related.
if f not in precomped:
@@ -1608,7 +1608,7 @@ def _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl):
# Exclude them now.
for f in excluded_idl:
excluded_configs = []
- for config_name, config in spec['configurations'].iteritems():
+ for config_name, config in spec['configurations'].items():
excluded_configs.append((config_name, config))
exclusions[f] = excluded_configs
return exclusions
@@ -1617,7 +1617,7 @@ def _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl):
def _AddToolFilesToMSVS(p, spec):
# Add in tool files (rules).
tool_files = OrderedSet()
- for _, config in spec['configurations'].iteritems():
+ for _, config in spec['configurations'].items():
for f in config.get('msvs_tool_files', []):
tool_files.add(f)
for f in tool_files:
@@ -1630,7 +1630,7 @@ def _HandlePreCompiledHeaders(p, sources, spec):
# kind (i.e. C vs. C++) as the precompiled header source stub needs
# to have use of precompiled headers disabled.
extensions_excluded_from_precompile = []
- for config_name, config in spec['configurations'].iteritems():
+ for config_name, config in spec['configurations'].items():
source = config.get('msvs_precompiled_source')
if source:
source = _FixPath(source)
@@ -1651,7 +1651,7 @@ def _HandlePreCompiledHeaders(p, sources, spec):
else:
basename, extension = os.path.splitext(source)
if extension in extensions_excluded_from_precompile:
- for config_name, config in spec['configurations'].iteritems():
+ for config_name, config in spec['configurations'].items():
tool = MSVSProject.Tool('VCCLCompilerTool',
{'UsePrecompiledHeader': '0',
'ForcedIncludeFiles': '$(NOINHERIT)'})
@@ -1702,7 +1702,7 @@ def _WriteMSVSUserFile(project_path, version, spec):
return # Nothing to add
# Write out the user file.
user_file = _CreateMSVSUserFile(project_path, version, spec)
- for config_name, c_data in spec['configurations'].iteritems():
+ for config_name, c_data in spec['configurations'].items():
user_file.AddDebugSettings(_ConfigFullName(config_name, c_data),
action, environment, working_directory)
user_file.WriteIfChanged()
@@ -1756,7 +1756,7 @@ def _GetPathDict(root, path):
def _DictsToFolders(base_path, bucket, flat):
# Convert to folders recursively.
children = []
- for folder, contents in bucket.iteritems():
+ for folder, contents in bucket.items():
if type(contents) == dict:
folder_children = _DictsToFolders(os.path.join(base_path, folder),
contents, flat)
@@ -1828,7 +1828,7 @@ def _GetPlatformOverridesOfProject(spec):
# Prepare a dict indicating which project configurations are used for which
# solution configurations for this target.
config_platform_overrides = {}
- for config_name, c in spec['configurations'].iteritems():
+ 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' % (
@@ -1967,7 +1967,7 @@ def PerformBuild(data, configurations, params):
msvs_version = params['msvs_version']
devenv = os.path.join(msvs_version.path, 'Common7', 'IDE', 'devenv.com')
- for build_file, build_file_dict in data.iteritems():
+ for build_file, build_file_dict in data.items():
(build_file_root, build_file_ext) = os.path.splitext(build_file)
if build_file_ext != '.gyp':
continue
@@ -1977,7 +1977,7 @@ def PerformBuild(data, configurations, params):
for config in configurations:
arguments = [devenv, sln_path, '/Build', config]
- print 'Building [%s]: %s' % (config, arguments)
+ print('Building [%s]: %s' % (config, arguments))
rtn = subprocess.check_call(arguments)
@@ -2029,7 +2029,7 @@ def GenerateOutput(target_list, target_dicts, data, params):
configs = set()
for qualified_target in target_list:
spec = target_dicts[qualified_target]
- for config_name, config in spec['configurations'].iteritems():
+ for config_name, config in spec['configurations'].items():
configs.add(_ConfigFullName(config_name, config))
configs = list(configs)
@@ -2072,7 +2072,7 @@ def GenerateOutput(target_list, target_dicts, data, params):
if generator_flags.get('msvs_error_on_missing_sources', False):
raise GypError(error_message)
else:
- print >> sys.stdout, "Warning: " + error_message
+ print("Warning: " + error_message, file=sys.stdout)
def _GenerateMSBuildFiltersFile(filters_path, source_files,
@@ -2676,7 +2676,7 @@ def _GetConfigurationCondition(name, settings):
def _GetMSBuildProjectConfigurations(configurations):
group = ['ItemGroup', {'Label': 'ProjectConfigurations'}]
- for (name, settings) in sorted(configurations.iteritems()):
+ for (name, settings) in sorted(configurations.items()):
configuration, platform = _GetConfigurationAndPlatform(name, settings)
designation = '%s|%s' % (configuration, platform)
group.append(
@@ -2749,7 +2749,7 @@ def _GetMSBuildGlobalProperties(spec, version, guid, gyp_file_name):
def _GetMSBuildConfigurationDetails(spec, build_file):
properties = {}
- for name, settings in spec['configurations'].iteritems():
+ for name, settings in spec['configurations'].items():
msbuild_attributes = _GetMSBuildAttributes(spec, settings, build_file)
condition = _GetConfigurationCondition(name, settings)
character_set = msbuild_attributes.get('CharacterSet')
@@ -2783,9 +2783,9 @@ def _GetMSBuildPropertySheets(configurations):
user_props = r'$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props'
additional_props = {}
props_specified = False
- for name, settings in sorted(configurations.iteritems()):
+ for name, settings in sorted(configurations.items()):
configuration = _GetConfigurationCondition(name, settings)
- if settings.has_key('msbuild_props'):
+ if 'msbuild_props' in settings:
additional_props[configuration] = _FixPaths(settings['msbuild_props'])
props_specified = True
else:
@@ -2805,7 +2805,7 @@ def _GetMSBuildPropertySheets(configurations):
]
else:
sheets = []
- for condition, props in additional_props.iteritems():
+ for condition, props in additional_props.items():
import_group = [
'ImportGroup',
{'Label': 'PropertySheets',
@@ -2838,7 +2838,7 @@ def _ConvertMSVSBuildAttributes(spec, config, build_file):
elif a == 'ConfigurationType':
msbuild_attributes[a] = _ConvertMSVSConfigurationType(msvs_attributes[a])
else:
- print 'Warning: Do not know how to convert MSVS attribute ' + a
+ print('Warning: Do not know how to convert MSVS attribute ' + a)
return msbuild_attributes
@@ -2934,7 +2934,7 @@ def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file):
new_paths = '$(ExecutablePath);' + ';'.join(new_paths)
properties = {}
- for (name, configuration) in sorted(configurations.iteritems()):
+ for (name, configuration) in sorted(configurations.items()):
condition = _GetConfigurationCondition(name, configuration)
attributes = _GetMSBuildAttributes(spec, configuration, build_file)
msbuild_settings = configuration['finalized_msbuild_settings']
@@ -2959,7 +2959,7 @@ def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file):
_AddConditionalProperty(properties, condition, 'ExecutablePath',
new_paths)
tool_settings = msbuild_settings.get('', {})
- for name, value in sorted(tool_settings.iteritems()):
+ for name, value in sorted(tool_settings.items()):
formatted_value = _GetValueFormattedForMSBuild('', name, value)
_AddConditionalProperty(properties, condition, name, formatted_value)
return _GetMSBuildPropertyGroup(spec, None, properties)
@@ -3028,7 +3028,7 @@ def _GetMSBuildPropertyGroup(spec, label, properties):
# NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))
for name in reversed(properties_ordered):
values = properties[name]
- for value, conditions in sorted(values.iteritems()):
+ for value, conditions in sorted(values.items()):
if len(conditions) == num_configurations:
# If the value is the same all configurations,
# just add one unconditional entry.
@@ -3041,18 +3041,18 @@ def _GetMSBuildPropertyGroup(spec, label, properties):
def _GetMSBuildToolSettingsSections(spec, configurations):
groups = []
- for (name, configuration) in sorted(configurations.iteritems()):
+ for (name, configuration) in sorted(configurations.items()):
msbuild_settings = configuration['finalized_msbuild_settings']
group = ['ItemDefinitionGroup',
{'Condition': _GetConfigurationCondition(name, configuration)}
]
- for tool_name, tool_settings in sorted(msbuild_settings.iteritems()):
+ 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.iteritems()):
+ for name, value in sorted(tool_settings.items()):
formatted_value = _GetValueFormattedForMSBuild(tool_name, name,
value)
tool.append([name, formatted_value])
@@ -3085,8 +3085,8 @@ def _FinalizeMSBuildSettings(spec, configuration):
for ignored_setting in ignored_settings:
value = configuration.get(ignored_setting)
if value:
- print ('Warning: The automatic conversion to MSBuild does not handle '
- '%s. Ignoring setting of %s' % (ignored_setting, str(value)))
+ print('Warning: The automatic conversion to MSBuild does not handle '
+ '%s. Ignoring setting of %s' % (ignored_setting, str(value)))
defines = [_EscapeCppDefineForMSBuild(d) for d in defines]
disabled_warnings = _GetDisabledWarnings(configuration)
@@ -3252,7 +3252,7 @@ def _AddSources2(spec, sources, exclusions, grouped_sources,
{'Condition': condition},
'true'])
# Add precompile if needed
- for config_name, configuration in spec['configurations'].iteritems():
+ for config_name, configuration in spec['configurations'].items():
precompiled_source = configuration.get('msvs_precompiled_source', '')
if precompiled_source != '':
precompiled_source = _FixPath(precompiled_source)
@@ -3502,7 +3502,7 @@ def _GenerateActionsForMSBuild(spec, actions_to_add):
"""
sources_handled_by_action = OrderedSet()
actions_spec = []
- for primary_input, actions in actions_to_add.iteritems():
+ for primary_input, actions in actions_to_add.items():
inputs = OrderedSet()
outputs = OrderedSet()
descriptions = []
diff --git a/tools/gyp/pylib/gyp/generator/ninja.py b/tools/gyp/pylib/gyp/generator/ninja.py
index 6140df9513..3658fb6be7 100644
--- a/tools/gyp/pylib/gyp/generator/ninja.py
+++ b/tools/gyp/pylib/gyp/generator/ninja.py
@@ -2,6 +2,8 @@
# 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
import hashlib
@@ -455,8 +457,8 @@ class NinjaWriter(object):
try:
sources = extra_sources + spec.get('sources', [])
except TypeError:
- print 'extra_sources: ', str(extra_sources)
- print 'spec.get("sources"): ', str(spec.get('sources'))
+ print('extra_sources: ', str(extra_sources))
+ print('spec.get("sources"): ', str(spec.get('sources')))
raise
if sources:
if self.flavor == 'mac' and len(self.archs) > 1:
@@ -485,8 +487,8 @@ class NinjaWriter(object):
if self.flavor != 'mac' or len(self.archs) == 1:
link_deps += [self.GypPathToNinja(o) for o in obj_outputs]
else:
- print "Warning: Actions/rules writing object files don't work with " \
- "multiarch targets, dropping. (target %s)" % spec['target_name']
+ print("Warning: Actions/rules writing object files don't work with "
+ "multiarch targets, dropping. (target %s)" % spec['target_name'])
elif self.flavor == 'mac' and len(self.archs) > 1:
link_deps = collections.defaultdict(list)
@@ -838,7 +840,7 @@ class NinjaWriter(object):
'XCASSETS_LAUNCH_IMAGE': 'launch-image',
}
settings = self.xcode_settings.xcode_settings[self.config_name]
- for settings_key, arg_name in settings_to_arg.iteritems():
+ for settings_key, arg_name in settings_to_arg.items():
value = settings.get(settings_key)
if value:
extra_arguments[arg_name] = value
@@ -1947,7 +1949,7 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params,
wrappers[key[:-len('_wrapper')]] = os.path.join(build_to_root, value)
# Support wrappers from environment variables too.
- for key, value in os.environ.iteritems():
+ for key, value in os.environ.items():
if key.lower().endswith('_wrapper'):
key_prefix = key[:-len('_wrapper')]
key_prefix = re.sub(r'\.HOST$', '.host', key_prefix)
@@ -1967,7 +1969,7 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params,
configs, generator_flags)
cl_paths = gyp.msvs_emulation.GenerateEnvironmentFiles(
toplevel_build, generator_flags, shared_system_includes, OpenOutput)
- for arch, path in sorted(cl_paths.iteritems()):
+ for arch, path in sorted(cl_paths.items()):
if clang_cl:
# If we have selected clang-cl, use that instead.
path = clang_cl
@@ -2442,7 +2444,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('Building [%s]: %s' % (config, arguments))
subprocess.check_call(arguments)
@@ -2479,7 +2481,7 @@ def GenerateOutput(target_list, target_dicts, data, params):
arglists.append(
(target_list, target_dicts, data, params, config_name))
pool.map(CallGenerateOutputForConfig, arglists)
- except KeyboardInterrupt, e:
+ except KeyboardInterrupt as e:
pool.terminate()
raise e
else:
diff --git a/tools/gyp/pylib/gyp/generator/xcode.py b/tools/gyp/pylib/gyp/generator/xcode.py
index db99d6ab81..8d65e53cca 100644
--- a/tools/gyp/pylib/gyp/generator/xcode.py
+++ b/tools/gyp/pylib/gyp/generator/xcode.py
@@ -2,6 +2,8 @@
# 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
import gyp.xcodeproj_file
@@ -129,7 +131,7 @@ class XcodeProject(object):
try:
os.makedirs(self.path)
self.created_dir = True
- except OSError, e:
+ except OSError as e:
if e.errno != errno.EEXIST:
raise
@@ -183,7 +185,7 @@ class XcodeProject(object):
# the tree tree view for UI display.
# Any values set globally are applied to all configurations, then any
# per-configuration values are applied.
- for xck, xcv in self.build_file_dict.get('xcode_settings', {}).iteritems():
+ for xck, xcv in self.build_file_dict.get('xcode_settings', {}).items():
xccl.SetBuildSetting(xck, xcv)
if 'xcode_config_file' in self.build_file_dict:
config_ref = self.project.AddOrGetFileInRootGroup(
@@ -197,7 +199,7 @@ class XcodeProject(object):
if build_file_configuration_named:
xcc = xccl.ConfigurationNamed(config_name)
for xck, xcv in build_file_configuration_named.get('xcode_settings',
- {}).iteritems():
+ {}).items():
xcc.SetBuildSetting(xck, xcv)
if 'xcode_config_file' in build_file_configuration_named:
config_ref = self.project.AddOrGetFileInRootGroup(
@@ -273,7 +275,7 @@ class XcodeProject(object):
script = script + "\n".join(
['export %s="%s"' %
(key, gyp.xcodeproj_file.ConvertVariablesToShellSyntax(val))
- for (key, val) in command.get('environment').iteritems()]) + "\n"
+ for (key, val) in command.get('environment').items()]) + "\n"
# Some test end up using sockets, files on disk, etc. and can get
# confused if more then one test runs at a time. The generator
@@ -454,7 +456,7 @@ sys.exit(subprocess.call(sys.argv[1:]))" """
same = False
try:
same = filecmp.cmp(pbxproj_path, new_pbxproj_path, False)
- except OSError, e:
+ except OSError as e:
if e.errno != errno.ENOENT:
raise
@@ -473,10 +475,10 @@ sys.exit(subprocess.call(sys.argv[1:]))" """
#
# No way to get the umask without setting a new one? Set a safe one
# and then set it back to the old value.
- umask = os.umask(077)
+ umask = os.umask(0o77)
os.umask(umask)
- os.chmod(new_pbxproj_path, 0666 & ~umask)
+ os.chmod(new_pbxproj_path, 0o666 & ~umask)
os.rename(new_pbxproj_path, pbxproj_path)
except Exception:
@@ -566,7 +568,7 @@ def EscapeXcodeDefine(s):
def PerformBuild(data, configurations, params):
options = params['options']
- for build_file, build_file_dict in data.iteritems():
+ for build_file, build_file_dict in data.items():
(build_file_root, build_file_ext) = os.path.splitext(build_file)
if build_file_ext != '.gyp':
continue
@@ -577,7 +579,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("Building [%s]: %s" % (config, arguments))
subprocess.check_call(arguments)
@@ -625,7 +627,7 @@ def GenerateOutput(target_list, target_dicts, data, params):
skip_excluded_files = \
not generator_flags.get('xcode_list_excluded_files', True)
xcode_projects = {}
- for build_file, build_file_dict in data.iteritems():
+ for build_file, build_file_dict in data.items():
(build_file_root, build_file_ext) = os.path.splitext(build_file)
if build_file_ext != '.gyp':
continue
@@ -744,7 +746,7 @@ def GenerateOutput(target_list, target_dicts, data, params):
xctarget_type = gyp.xcodeproj_file.PBXNativeTarget
try:
target_properties['productType'] = _types[type_bundle_key]
- except KeyError, e:
+ except KeyError as e:
gyp.common.ExceptionAppend(e, "-- unknown product type while "
"writing target %s" % target_name)
raise
@@ -1024,7 +1026,7 @@ def GenerateOutput(target_list, target_dicts, data, params):
# target.
makefile.write('all: \\\n')
for concrete_output_index in \
- xrange(0, len(concrete_outputs_by_rule_source)):
+ range(0, len(concrete_outputs_by_rule_source)):
# Only list the first (index [0]) concrete output of each input
# in the "all" target. Otherwise, a parallel make (-j > 1) would
# attempt to process each input multiple times simultaneously.
@@ -1047,7 +1049,7 @@ def GenerateOutput(target_list, target_dicts, data, params):
# rule source. Collect the names of the directories that are
# required.
concrete_output_dirs = []
- for concrete_output_index in xrange(0, len(concrete_outputs)):
+ for concrete_output_index in range(0, len(concrete_outputs)):
concrete_output = concrete_outputs[concrete_output_index]
if concrete_output_index == 0:
bol = ''
@@ -1066,7 +1068,7 @@ def GenerateOutput(target_list, target_dicts, data, params):
# the set of additional rule inputs, if any.
prerequisites = [rule_source]
prerequisites.extend(rule.get('inputs', []))
- for prerequisite_index in xrange(0, len(prerequisites)):
+ for prerequisite_index in range(0, len(prerequisites)):
prerequisite = prerequisites[prerequisite_index]
if prerequisite_index == len(prerequisites) - 1:
eol = ''
@@ -1288,7 +1290,7 @@ exit 1
set_define = EscapeXcodeDefine(define)
xcbc.AppendBuildSetting('GCC_PREPROCESSOR_DEFINITIONS', set_define)
if 'xcode_settings' in configuration:
- for xck, xcv in configuration['xcode_settings'].iteritems():
+ for xck, xcv in configuration['xcode_settings'].items():
xcbc.SetBuildSetting(xck, xcv)
if 'xcode_config_file' in configuration:
config_ref = pbxp.AddOrGetFileInRootGroup(
@@ -1296,7 +1298,7 @@ exit 1
xcbc.SetBaseConfiguration(config_ref)
build_files = []
- for build_file, build_file_dict in data.iteritems():
+ for build_file, build_file_dict in data.items():
if build_file.endswith('.gyp'):
build_files.append(build_file)
diff --git a/tools/gyp/pylib/gyp/mac_tool.py b/tools/gyp/pylib/gyp/mac_tool.py
index 0ad7e7a1b6..ec22d260d1 100755
--- a/tools/gyp/pylib/gyp/mac_tool.py
+++ b/tools/gyp/pylib/gyp/mac_tool.py
@@ -8,6 +8,8 @@
These functions are executed via gyp-mac-tool when using the Makefile generator.
"""
+from __future__ import print_function
+
import fcntl
import fnmatch
import glob
@@ -151,7 +153,7 @@ class MacTool(object):
fp = open(file_name, 'rb')
try:
header = fp.read(3)
- except:
+ except Exception:
fp.close()
return None
fp.close()
@@ -270,7 +272,7 @@ class MacTool(object):
_, err = libtoolout.communicate()
for line in err.splitlines():
if not libtool_re.match(line) and not libtool_re5.match(line):
- print >>sys.stderr, line
+ print(line, file=sys.stderr)
# Unconditionally touch the output .a file on the command line if present
# and the command succeeded. A bit hacky.
if not libtoolout.returncode:
@@ -385,7 +387,7 @@ class MacTool(object):
])
if keys:
keys = json.loads(keys)
- for key, value in keys.iteritems():
+ for key, value in keys.items():
arg_name = '--' + key
if isinstance(value, bool):
if value:
@@ -480,8 +482,8 @@ class MacTool(object):
profiles_dir = os.path.join(
os.environ['HOME'], 'Library', 'MobileDevice', 'Provisioning Profiles')
if not os.path.isdir(profiles_dir):
- print >>sys.stderr, (
- 'cannot find mobile provisioning for %s' % bundle_identifier)
+ print('cannot find mobile provisioning for %s' % bundle_identifier,
+ file=sys.stderr)
sys.exit(1)
provisioning_profiles = None
if profile:
@@ -502,8 +504,8 @@ class MacTool(object):
valid_provisioning_profiles[app_id_pattern] = (
profile_path, profile_data, team_identifier)
if not valid_provisioning_profiles:
- print >>sys.stderr, (
- 'cannot find mobile provisioning for %s' % bundle_identifier)
+ print('cannot find mobile provisioning for %s' % bundle_identifier,
+ file=sys.stderr)
sys.exit(1)
# If the user has multiple provisioning profiles installed that can be
# used for ${bundle_identifier}, pick the most specific one (ie. the
@@ -527,7 +529,7 @@ class MacTool(object):
def _MergePlist(self, merged_plist, plist):
"""Merge |plist| into |merged_plist|."""
- for key, value in plist.iteritems():
+ for key, value in plist.items():
if isinstance(value, dict):
merged_value = merged_plist.get(key, {})
if isinstance(merged_value, dict):
@@ -637,7 +639,7 @@ class MacTool(object):
the key was not found.
"""
if isinstance(data, str):
- for key, value in substitutions.iteritems():
+ for key, value in substitutions.items():
data = data.replace('$(%s)' % key, value)
return data
if isinstance(data, list):
diff --git a/tools/gyp/pylib/gyp/msvs_emulation.py b/tools/gyp/pylib/gyp/msvs_emulation.py
index 4acaee2446..e130b53271 100644
--- a/tools/gyp/pylib/gyp/msvs_emulation.py
+++ b/tools/gyp/pylib/gyp/msvs_emulation.py
@@ -209,7 +209,7 @@ class MsvsSettings(object):
configs = spec['configurations']
for field, default in supported_fields:
setattr(self, field, {})
- for configname, config in configs.iteritems():
+ for configname, config in configs.items():
getattr(self, field)[configname] = config.get(field, default())
self.msvs_cygwin_dirs = spec.get('msvs_cygwin_dirs', ['.'])
@@ -953,7 +953,7 @@ def ExpandMacros(string, expansions):
"""Expand $(Variable) per expansions dict. See MsvsSettings.GetVSMacroEnv
for the canonical way to retrieve a suitable dict."""
if '$' in string:
- for old, new in expansions.iteritems():
+ for old, new in expansions.items():
assert '$(' not in new, new
string = string.replace(old, new)
return string
@@ -1001,7 +1001,7 @@ def _FormatAsEnvironmentBlock(envvar_dict):
CreateProcess documentation for more details."""
block = ''
nul = '\0'
- for key, value in envvar_dict.iteritems():
+ for key, value in envvar_dict.items():
block += key + '=' + value + nul
block += nul
return block
diff --git a/tools/gyp/pylib/gyp/win_tool.py b/tools/gyp/pylib/gyp/win_tool.py
index 1c843a0b6c..ab6db1c4e0 100755
--- a/tools/gyp/pylib/gyp/win_tool.py
+++ b/tools/gyp/pylib/gyp/win_tool.py
@@ -9,6 +9,8 @@
These functions are executed via gyp-win-tool when using the ninja generator.
"""
+from __future__ import print_function
+
import os
import re
import shutil
@@ -134,7 +136,7 @@ class WinTool(object):
if (not line.startswith(' Creating library ') and
not line.startswith('Generating code') and
not line.startswith('Finished generating code')):
- print line
+ print(line)
return link.returncode
def ExecLinkWithManifests(self, arch, embed_manifest, out, ldcmd, resname,
@@ -223,7 +225,7 @@ class WinTool(object):
out, _ = popen.communicate()
for line in out.splitlines():
if line and 'manifest authoring warning 81010002' not in line:
- print line
+ print(line)
return popen.returncode
def ExecManifestToRc(self, arch, *args):
@@ -263,7 +265,7 @@ class WinTool(object):
for x in lines if x.startswith(prefixes))
for line in lines:
if not line.startswith(prefixes) and line not in processing:
- print line
+ print(line)
return popen.returncode
def ExecAsmWrapper(self, arch, *args):
@@ -277,7 +279,7 @@ class WinTool(object):
not line.startswith('Microsoft (R) Macro Assembler') and
not line.startswith(' Assembling: ') and
line):
- print line
+ print(line)
return popen.returncode
def ExecRcWrapper(self, arch, *args):
@@ -291,7 +293,7 @@ class WinTool(object):
if (not line.startswith('Microsoft (R) Windows (R) Resource Compiler') and
not line.startswith('Copyright (C) Microsoft Corporation') and
line):
- print line
+ print(line)
return popen.returncode
def ExecActionWrapper(self, arch, rspfile, *dir):
@@ -300,7 +302,7 @@ class WinTool(object):
env = self._GetEnv(arch)
# TODO(scottmg): This is a temporary hack to get some specific variables
# through to actions that are set after gyp-time. http://crbug.com/333738.
- for k, v in os.environ.iteritems():
+ for k, v in os.environ.items():
if k not in env:
env[k] = v
args = open(rspfile).read()
diff --git a/tools/gyp/pylib/gyp/xcode_emulation.py b/tools/gyp/pylib/gyp/xcode_emulation.py
index 9481423228..b083984677 100644
--- a/tools/gyp/pylib/gyp/xcode_emulation.py
+++ b/tools/gyp/pylib/gyp/xcode_emulation.py
@@ -7,6 +7,8 @@ This module contains classes that help to emulate xcodebuild behavior on top of
other build systems, such as make and ninja.
"""
+from __future__ import print_function
+
import copy
import gyp.common
import os
@@ -73,7 +75,7 @@ class XcodeArchsDefault(object):
if arch not in expanded_archs:
expanded_archs.append(arch)
except KeyError as e:
- print 'Warning: Ignoring unsupported variable "%s".' % variable
+ print('Warning: Ignoring unsupported variable "%s".' % variable)
elif arch not in expanded_archs:
expanded_archs.append(arch)
return expanded_archs
@@ -171,7 +173,7 @@ class XcodeSettings(object):
# the same for all configs are implicitly per-target settings.
self.xcode_settings = {}
configs = spec['configurations']
- for configname, config in configs.iteritems():
+ for configname, config in configs.items():
self.xcode_settings[configname] = config.get('xcode_settings', {})
self._ConvertConditionalKeys(configname)
if self.xcode_settings[configname].get('IPHONEOS_DEPLOYMENT_TARGET',
@@ -197,8 +199,8 @@ class XcodeSettings(object):
new_key = key.split("[")[0]
settings[new_key] = settings[key]
else:
- print 'Warning: Conditional keys not implemented, ignoring:', \
- ' '.join(conditional_keys)
+ print('Warning: Conditional keys not implemented, ignoring:',
+ ' '.join(conditional_keys))
del settings[key]
def _Settings(self):
@@ -216,7 +218,7 @@ class XcodeSettings(object):
def _WarnUnimplemented(self, test_key):
if test_key in self._Settings():
- print 'Warning: Ignoring not yet implemented key "%s".' % test_key
+ print('Warning: Ignoring not yet implemented key "%s".' % test_key)
def IsBinaryOutputFormat(self, configname):
default = "binary" if self.isIOS else "xml"
@@ -646,9 +648,9 @@ class XcodeSettings(object):
cflags += self._Settings().get('WARNING_CFLAGS', [])
if self._IsXCTest():
- platform_root = self._XcodePlatformPath(configname)
- if platform_root:
- cflags.append('-F' + platform_root + '/Developer/Library/Frameworks/')
+ platform_root = self._XcodePlatformPath(configname)
+ if platform_root:
+ cflags.append('-F' + platform_root + '/Developer/Library/Frameworks/')
if sdk_root:
framework_root = sdk_root
@@ -915,10 +917,10 @@ class XcodeSettings(object):
ldflags.append('-F' + directory.replace('$(SDKROOT)', sdk_root))
if self._IsXCTest():
- platform_root = self._XcodePlatformPath(configname)
- if sdk_root and platform_root:
- ldflags.append('-F' + platform_root + '/Developer/Library/Frameworks/')
- ldflags.append('-framework XCTest')
+ platform_root = self._XcodePlatformPath(configname)
+ if sdk_root and platform_root:
+ ldflags.append('-F' + platform_root + '/Developer/Library/Frameworks/')
+ ldflags.append('-framework XCTest')
is_extension = self._IsIosAppExtension() or self._IsIosWatchKitExtension()
if sdk_root and is_extension:
@@ -965,7 +967,7 @@ class XcodeSettings(object):
result = dict(self.xcode_settings[configname])
first_pass = False
else:
- for key, value in self.xcode_settings[configname].iteritems():
+ for key, value in self.xcode_settings[configname].items():
if key not in result:
continue
elif result[key] != value:
@@ -1086,8 +1088,8 @@ class XcodeSettings(object):
unimpl = ['OTHER_CODE_SIGN_FLAGS']
unimpl = set(unimpl) & set(self.xcode_settings[configname].keys())
if unimpl:
- print 'Warning: Some codesign keys not implemented, ignoring: %s' % (
- ', '.join(sorted(unimpl)))
+ print('Warning: Some codesign keys not implemented, ignoring: %s' %
+ ', '.join(sorted(unimpl)))
if self._IsXCTest():
# For device xctests, Xcode copies two extra frameworks into $TEST_HOST.
@@ -1753,7 +1755,7 @@ def _TopologicallySortedEnvVarKeys(env):
order = gyp.common.TopologicallySorted(env.keys(), GetEdges)
order.reverse()
return order
- except gyp.common.CycleError, e:
+ except gyp.common.CycleError as e:
raise GypError(
'Xcode environment variables are cyclically dependent: ' + str(e.nodes))
@@ -1793,7 +1795,7 @@ def _AddIOSDeviceConfigurations(targets):
for target_dict in targets.itervalues():
toolset = target_dict['toolset']
configs = target_dict['configurations']
- for config_name, simulator_config_dict in dict(configs).iteritems():
+ for config_name, simulator_config_dict in dict(configs).items():
iphoneos_config_dict = copy.deepcopy(simulator_config_dict)
configs[config_name + '-iphoneos'] = iphoneos_config_dict
configs[config_name + '-iphonesimulator'] = simulator_config_dict
diff --git a/tools/gyp/pylib/gyp/xcode_ninja.py b/tools/gyp/pylib/gyp/xcode_ninja.py
index bc76ffff4e..5bf6b9cfb5 100644
--- a/tools/gyp/pylib/gyp/xcode_ninja.py
+++ b/tools/gyp/pylib/gyp/xcode_ninja.py
@@ -28,7 +28,7 @@ def _WriteWorkspace(main_gyp, sources_gyp, params):
workspace_path = os.path.join(options.generator_output, workspace_path)
try:
os.makedirs(workspace_path)
- except OSError, e:
+ except OSError as e:
if e.errno != errno.EEXIST:
raise
output_string = '<?xml version="1.0" encoding="UTF-8"?>\n' + \
@@ -167,7 +167,7 @@ def CreateWrapper(target_list, target_dicts, data, params):
params: Dict of global options for gyp.
"""
orig_gyp = params['build_files'][0]
- for gyp_name, gyp_dict in data.iteritems():
+ for gyp_name, gyp_dict in data.items():
if gyp_name == orig_gyp:
depth = gyp_dict['_DEPTH']
@@ -238,7 +238,7 @@ def CreateWrapper(target_list, target_dicts, data, params):
not generator_flags.get('xcode_ninja_list_excluded_files', True)
sources = []
- for target, target_dict in target_dicts.iteritems():
+ for target, target_dict in target_dicts.items():
base = os.path.dirname(target)
files = target_dict.get('sources', []) + \
target_dict.get('mac_bundle_resources', [])
diff --git a/tools/gyp/pylib/gyp/xcodeproj_file.py b/tools/gyp/pylib/gyp/xcodeproj_file.py
index e69235f724..021ed4309d 100644
--- a/tools/gyp/pylib/gyp/xcodeproj_file.py
+++ b/tools/gyp/pylib/gyp/xcodeproj_file.py
@@ -138,21 +138,18 @@ a project file is output.
"""
import gyp.common
+import hashlib
import posixpath
import re
import struct
import sys
-# hashlib is supplied as of Python 2.5 as the replacement interface for sha
-# and other secure hashes. In 2.6, sha is deprecated. Import hashlib if
-# available, avoiding a deprecation warning under 2.6. Import sha otherwise,
-# preserving 2.4 compatibility.
try:
- import hashlib
- _new_sha1 = hashlib.sha1
-except ImportError:
- import sha
- _new_sha1 = sha.new
+ basestring, cmp, unicode
+except NameError: # Python 3
+ basestring = unicode = str
+ def cmp(x, y):
+ return (x > y) - (x < y)
# See XCObject._EncodeString. This pattern is used to determine when a string
@@ -314,7 +311,7 @@ class XCObject(object):
"""
that = self.__class__(id=self.id, parent=self.parent)
- for key, value in self._properties.iteritems():
+ for key, value in self._properties.items():
is_strong = self._schema[key][2]
if isinstance(value, XCObject):
@@ -324,8 +321,7 @@ class XCObject(object):
that._properties[key] = new_value
else:
that._properties[key] = value
- elif isinstance(value, str) or isinstance(value, unicode) or \
- isinstance(value, int):
+ elif isinstance(value, (basestring, int)):
that._properties[key] = value
elif isinstance(value, list):
if is_strong:
@@ -422,7 +418,7 @@ class XCObject(object):
hash.update(data)
if seed_hash is None:
- seed_hash = _new_sha1()
+ seed_hash = hashlib.sha1()
hash = seed_hash.copy()
@@ -452,7 +448,7 @@ class XCObject(object):
digest_int_count = hash.digest_size / 4
digest_ints = struct.unpack('>' + 'I' * digest_int_count, hash.digest())
id_ints = [0, 0, 0]
- for index in xrange(0, digest_int_count):
+ for index in range(0, digest_int_count):
id_ints[index % 3] ^= digest_ints[index]
self.id = '%08X%08X%08X' % tuple(id_ints)
@@ -475,7 +471,7 @@ class XCObject(object):
"""Returns a list of all of this object's owned (strong) children."""
children = []
- for property, attributes in self._schema.iteritems():
+ for property, attributes in self._schema.items():
(is_list, property_type, is_strong) = attributes[0:3]
if is_strong and property in self._properties:
if not is_list:
@@ -622,7 +618,7 @@ class XCObject(object):
printable += end_tabs + ')'
elif isinstance(value, dict):
printable = '{' + sep
- for item_key, item_value in sorted(value.iteritems()):
+ for item_key, item_value in sorted(value.items()):
printable += element_tabs + \
self._XCPrintableValue(tabs + 1, item_key, flatten_list) + ' = ' + \
self._XCPrintableValue(tabs + 1, item_value, flatten_list) + ';' + \
@@ -691,7 +687,7 @@ class XCObject(object):
printable_value[0] == '"' and printable_value[-1] == '"':
printable_value = printable_value[1:-1]
printable += printable_key + ' = ' + printable_value + ';' + after_kv
- except TypeError, e:
+ except TypeError as e:
gyp.common.ExceptionAppend(e,
'while printing key "%s"' % key)
raise
@@ -730,7 +726,7 @@ class XCObject(object):
self._XCKVPrint(file, 3, 'isa', self.__class__.__name__)
# The remaining elements of an object dictionary are sorted alphabetically.
- for property, value in sorted(self._properties.iteritems()):
+ for property, value in sorted(self._properties.items()):
self._XCKVPrint(file, 3, property, value)
# End the object.
@@ -752,7 +748,7 @@ class XCObject(object):
if properties is None:
return
- for property, value in properties.iteritems():
+ for property, value in properties.items():
# Make sure the property is in the schema.
if not property in self._schema:
raise KeyError(property + ' not in ' + self.__class__.__name__)
@@ -788,8 +784,7 @@ class XCObject(object):
self._properties[property] = value.Copy()
else:
self._properties[property] = value
- elif isinstance(value, str) or isinstance(value, unicode) or \
- isinstance(value, int):
+ elif isinstance(value, (basestring, int)):
self._properties[property] = value
elif isinstance(value, list):
if is_strong:
@@ -865,7 +860,7 @@ class XCObject(object):
# TODO(mark): A stronger verification mechanism is needed. Some
# subclasses need to perform validation beyond what the schema can enforce.
- for property, attributes in self._schema.iteritems():
+ for property, attributes in self._schema.items():
(is_list, property_type, is_strong, is_required) = attributes[0:4]
if is_required and not property in self._properties:
raise KeyError(self.__class__.__name__ + ' requires ' + property)
@@ -875,7 +870,7 @@ class XCObject(object):
overwrite properties that have already been set."""
defaults = {}
- for property, attributes in self._schema.iteritems():
+ for property, attributes in self._schema.items():
(is_list, property_type, is_strong, is_required) = attributes[0:4]
if is_required and len(attributes) >= 5 and \
not property in self._properties:
@@ -1426,7 +1421,7 @@ class XCFileLikeElement(XCHierarchicalElement):
xche = self
while xche != None and isinstance(xche, XCHierarchicalElement):
xche_hashables = xche.Hashables()
- for index in xrange(0, len(xche_hashables)):
+ for index in range(0, len(xche_hashables)):
hashables.insert(index, xche_hashables[index])
xche = xche.parent
return hashables
@@ -2468,7 +2463,7 @@ class PBXNativeTarget(XCTarget):
# The headers phase should come before the resources, sources, and
# frameworks phases, if any.
insert_at = len(self._properties['buildPhases'])
- for index in xrange(0, len(self._properties['buildPhases'])):
+ for index in range(0, len(self._properties['buildPhases'])):
phase = self._properties['buildPhases'][index]
if isinstance(phase, PBXResourcesBuildPhase) or \
isinstance(phase, PBXSourcesBuildPhase) or \
@@ -2489,7 +2484,7 @@ class PBXNativeTarget(XCTarget):
# The resources phase should come before the sources and frameworks
# phases, if any.
insert_at = len(self._properties['buildPhases'])
- for index in xrange(0, len(self._properties['buildPhases'])):
+ for index in range(0, len(self._properties['buildPhases'])):
phase = self._properties['buildPhases'][index]
if isinstance(phase, PBXSourcesBuildPhase) or \
isinstance(phase, PBXFrameworksBuildPhase):
@@ -2911,7 +2906,7 @@ class PBXProject(XCContainerPortal):
# determine the sort order.
return cmp(x_index, y_index)
- for other_pbxproject, ref_dict in self._other_pbxprojects.iteritems():
+ for other_pbxproject, ref_dict in self._other_pbxprojects.items():
# Build up a list of products in the remote project file, ordered the
# same as the targets that produce them.
remote_products = []
@@ -2956,7 +2951,7 @@ class XCProjectFile(XCObject):
self._XCPrint(file, 0, '{ ')
else:
self._XCPrint(file, 0, '{\n')
- for property, value in sorted(self._properties.iteritems(),
+ for property, value in sorted(self._properties.items(),
cmp=lambda x, y: cmp(x, y)):
if property == 'objects':
self._PrintObjects(file)