Skip to content

Commit 54fcb14

Browse files
cclaussTrott
authored andcommitted
gyp: cherrypick more Python3 changes from node-gyp
PR-URL: #28563 Reviewed-By: Richard Lau <riclau@uk.ibm.com> Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl> Reviewed-By: Rich Trott <rtrott@gmail.com>
1 parent 7032e59 commit 54fcb14

16 files changed

+198
-180
lines changed

tools/gyp/pylib/gyp/MSVSSettings.py

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@
1414
MSBuild install directory, e.g. c:\Program Files (x86)\MSBuild
1515
"""
1616

17+
from __future__ import print_function
18+
19+
from gyp import string_types
20+
1721
import sys
1822
import re
1923

@@ -106,11 +110,11 @@ class _String(_Type):
106110
"""A setting that's just a string."""
107111

108112
def ValidateMSVS(self, value):
109-
if not isinstance(value, basestring):
113+
if not isinstance(value, string_types):
110114
raise ValueError('expected string; got %r' % value)
111115

112116
def ValidateMSBuild(self, value):
113-
if not isinstance(value, basestring):
117+
if not isinstance(value, string_types):
114118
raise ValueError('expected string; got %r' % value)
115119

116120
def ConvertToMSBuild(self, value):
@@ -122,11 +126,11 @@ class _StringList(_Type):
122126
"""A settings that's a list of strings."""
123127

124128
def ValidateMSVS(self, value):
125-
if not isinstance(value, basestring) and not isinstance(value, list):
129+
if not isinstance(value, string_types) and not isinstance(value, list):
126130
raise ValueError('expected string list; got %r' % value)
127131

128132
def ValidateMSBuild(self, value):
129-
if not isinstance(value, basestring) and not isinstance(value, list):
133+
if not isinstance(value, string_types) and not isinstance(value, list):
130134
raise ValueError('expected string list; got %r' % value)
131135

132136
def ConvertToMSBuild(self, value):
@@ -400,7 +404,7 @@ def _ValidateExclusionSetting(setting, settings, error_msg, stderr=sys.stderr):
400404

401405
if unrecognized:
402406
# We don't know this setting. Give a warning.
403-
print >> stderr, error_msg
407+
print(error_msg, file=stderr)
404408

405409

406410
def FixVCMacroSlashes(s):
@@ -433,7 +437,7 @@ def ConvertVCMacrosToMSBuild(s):
433437
'$(PlatformName)': '$(Platform)',
434438
'$(SafeInputName)': '%(Filename)',
435439
}
436-
for old, new in replace_map.iteritems():
440+
for old, new in replace_map.items():
437441
s = s.replace(old, new)
438442
s = FixVCMacroSlashes(s)
439443
return s
@@ -453,17 +457,17 @@ def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr):
453457
dictionaries of settings and their values.
454458
"""
455459
msbuild_settings = {}
456-
for msvs_tool_name, msvs_tool_settings in msvs_settings.iteritems():
460+
for msvs_tool_name, msvs_tool_settings in msvs_settings.items():
457461
if msvs_tool_name in _msvs_to_msbuild_converters:
458462
msvs_tool = _msvs_to_msbuild_converters[msvs_tool_name]
459-
for msvs_setting, msvs_value in msvs_tool_settings.iteritems():
463+
for msvs_setting, msvs_value in msvs_tool_settings.items():
460464
if msvs_setting in msvs_tool:
461465
# Invoke the translation function.
462466
try:
463467
msvs_tool[msvs_setting](msvs_value, msbuild_settings)
464-
except ValueError, e:
465-
print >> stderr, ('Warning: while converting %s/%s to MSBuild, '
466-
'%s' % (msvs_tool_name, msvs_setting, e))
468+
except ValueError as e:
469+
print('Warning: while converting %s/%s to MSBuild, '
470+
'%s' % (msvs_tool_name, msvs_setting, e), file=stderr)
467471
else:
468472
_ValidateExclusionSetting(msvs_setting,
469473
msvs_tool,
@@ -472,8 +476,8 @@ def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr):
472476
(msvs_tool_name, msvs_setting)),
473477
stderr)
474478
else:
475-
print >> stderr, ('Warning: unrecognized tool %s while converting to '
476-
'MSBuild.' % msvs_tool_name)
479+
print('Warning: unrecognized tool %s while converting to '
480+
'MSBuild.' % msvs_tool_name, file=stderr)
477481
return msbuild_settings
478482

479483

@@ -513,13 +517,13 @@ def _ValidateSettings(validators, settings, stderr):
513517
for tool_name in settings:
514518
if tool_name in validators:
515519
tool_validators = validators[tool_name]
516-
for setting, value in settings[tool_name].iteritems():
520+
for setting, value in settings[tool_name].items():
517521
if setting in tool_validators:
518522
try:
519523
tool_validators[setting](value)
520-
except ValueError, e:
521-
print >> stderr, ('Warning: for %s/%s, %s' %
522-
(tool_name, setting, e))
524+
except ValueError as e:
525+
print('Warning: for %s/%s, %s' % (tool_name, setting, e),
526+
file=stderr)
523527
else:
524528
_ValidateExclusionSetting(setting,
525529
tool_validators,
@@ -528,7 +532,7 @@ def _ValidateSettings(validators, settings, stderr):
528532
stderr)
529533

530534
else:
531-
print >> stderr, ('Warning: unrecognized tool %s' % tool_name)
535+
print('Warning: unrecognized tool %s' % (tool_name), file=stderr)
532536

533537

534538
# MSVS and MBuild names of the tools.

tools/gyp/pylib/gyp/MSVSUtil.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ def InsertLargePdbShims(target_list, target_dicts, vars):
236236

237237
# Set up the shim to output its PDB to the same location as the final linker
238238
# target.
239-
for config_name, config in shim_dict.get('configurations').iteritems():
239+
for config_name, config in shim_dict.get('configurations').items():
240240
pdb_path = _GetPdbPath(target_dict, config_name, vars)
241241

242242
# A few keys that we don't want to propagate.

tools/gyp/pylib/gyp/MSVSVersion.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ def _RegistryQuery(key, value=None):
189189
text = None
190190
try:
191191
text = _RegistryQueryBase('Sysnative', key, value)
192-
except OSError, e:
192+
except OSError as e:
193193
if e.errno == errno.ENOENT:
194194
text = _RegistryQueryBase('System32', key, value)
195195
else:
@@ -207,12 +207,18 @@ def _RegistryGetValueUsingWinReg(key, value):
207207
contents of the registry key's value, or None on failure. Throws
208208
ImportError if _winreg is unavailable.
209209
"""
210-
import _winreg
210+
try:
211+
# Python 2
212+
from _winreg import HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx
213+
except ImportError:
214+
# Python 3
215+
from winreg import HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx
216+
211217
try:
212218
root, subkey = key.split('\\', 1)
213219
assert root == 'HKLM' # Only need HKLM for now.
214-
with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey) as hkey:
215-
return _winreg.QueryValueEx(hkey, value)[0]
220+
with OpenKey(HKEY_LOCAL_MACHINE, subkey) as hkey:
221+
return QueryValueEx(hkey, value)[0]
216222
except WindowsError:
217223
return None
218224

tools/gyp/pylib/gyp/common.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
# Use of this source code is governed by a BSD-style license that can be
33
# found in the LICENSE file.
44

5-
from __future__ import with_statement
6-
75
import collections
86
import errno
97
import filecmp
@@ -363,7 +361,7 @@ def close(self):
363361
same = False
364362
try:
365363
same = filecmp.cmp(self.tmp_path, filename, False)
366-
except OSError, e:
364+
except OSError as e:
367365
if e.errno != errno.ENOENT:
368366
raise
369367

@@ -382,9 +380,9 @@ def close(self):
382380
#
383381
# No way to get the umask without setting a new one? Set a safe one
384382
# and then set it back to the old value.
385-
umask = os.umask(077)
383+
umask = os.umask(0o77)
386384
os.umask(umask)
387-
os.chmod(self.tmp_path, 0666 & ~umask)
385+
os.chmod(self.tmp_path, 0o666 & ~umask)
388386
if sys.platform == 'win32' and os.path.exists(filename):
389387
# NOTE: on windows (but not cygwin) rename will not replace an
390388
# existing file, so it must be preceded with a remove. Sadly there
@@ -467,7 +465,7 @@ def CopyTool(flavor, out_path, generator_flags={}):
467465
''.join([source[0], header] + source[1:]))
468466

469467
# Make file executable.
470-
os.chmod(tool_path, 0755)
468+
os.chmod(tool_path, 0o755)
471469

472470

473471
# From Alex Martelli,

tools/gyp/pylib/gyp/easy_xml.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import re
66
import os
77
import locale
8+
from functools import reduce
89

910

1011
def XmlToString(content, encoding='utf-8', pretty=False):
@@ -80,7 +81,7 @@ def _ConstructContentList(xml_parts, specification, pretty, level=0):
8081
# Optionally in second position is a dictionary of the attributes.
8182
rest = specification[1:]
8283
if rest and isinstance(rest[0], dict):
83-
for at, val in sorted(rest[0].iteritems()):
84+
for at, val in sorted(rest[0].items()):
8485
xml_parts.append(' %s="%s"' % (at, _XmlEscape(val, attr=True)))
8586
rest = rest[1:]
8687
if rest:

tools/gyp/pylib/gyp/generator/cmake.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
CMakeLists.txt file.
2929
"""
3030

31+
from __future__ import print_function
32+
3133
import multiprocessing
3234
import os
3335
import signal
@@ -644,8 +646,8 @@ def WriteTarget(namer, qualified_target, target_dicts, build_dir, config_to_use,
644646

645647
cmake_target_type = cmake_target_type_from_gyp_target_type.get(target_type)
646648
if cmake_target_type is None:
647-
print ('Target %s has unknown target type %s, skipping.' %
648-
( target_name, target_type ) )
649+
print('Target %s has unknown target type %s, skipping.' %
650+
( target_name, target_type))
649651
return
650652

651653
SetVariable(output, 'TARGET', target_name)
@@ -868,8 +870,8 @@ def WriteTarget(namer, qualified_target, target_dicts, build_dir, config_to_use,
868870
default_product_ext = generator_default_variables['SHARED_LIB_SUFFIX']
869871

870872
elif target_type != 'executable':
871-
print ('ERROR: What output file should be generated?',
872-
'type', target_type, 'target', target_name)
873+
print('ERROR: What output file should be generated?',
874+
'type', target_type, 'target', target_name)
873875

874876
product_prefix = spec.get('product_prefix', default_product_prefix)
875877
product_name = spec.get('product_name', default_product_name)
@@ -1207,11 +1209,11 @@ def PerformBuild(data, configurations, params):
12071209
output_dir,
12081210
config_name))
12091211
arguments = ['cmake', '-G', 'Ninja']
1210-
print 'Generating [%s]: %s' % (config_name, arguments)
1212+
print('Generating [%s]: %s' % (config_name, arguments))
12111213
subprocess.check_call(arguments, cwd=build_dir)
12121214

12131215
arguments = ['ninja', '-C', build_dir]
1214-
print 'Building [%s]: %s' % (config_name, arguments)
1216+
print('Building [%s]: %s' % (config_name, arguments))
12151217
subprocess.check_call(arguments)
12161218

12171219

@@ -1239,7 +1241,7 @@ def GenerateOutput(target_list, target_dicts, data, params):
12391241
arglists.append((target_list, target_dicts, data,
12401242
params, config_name))
12411243
pool.map(CallGenerateOutputForConfig, arglists)
1242-
except KeyboardInterrupt, e:
1244+
except KeyboardInterrupt as e:
12431245
pool.terminate()
12441246
raise e
12451247
else:

tools/gyp/pylib/gyp/generator/make.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
# toplevel Makefile. It may make sense to generate some .mk files on
2222
# the side to keep the files readable.
2323

24+
from __future__ import print_function
25+
2426
import os
2527
import re
2628
import sys
@@ -650,7 +652,7 @@ def _ValidateSourcesForOSX(spec, all_sources):
650652
basenames.setdefault(basename, []).append(source)
651653

652654
error = ''
653-
for basename, files in basenames.iteritems():
655+
for basename, files in basenames.items():
654656
if len(files) > 1:
655657
error += ' %s: %s\n' % (basename, ' '.join(files))
656658

@@ -1202,16 +1204,16 @@ def WriteSources(self, configs, deps, sources,
12021204
cflags_c = config.get('cflags_c')
12031205
cflags_cc = config.get('cflags_cc')
12041206

1205-
self.WriteLn("# Flags passed to all source files.");
1207+
self.WriteLn("# Flags passed to all source files.")
12061208
self.WriteList(cflags, 'CFLAGS_%s' % configname)
1207-
self.WriteLn("# Flags passed to only C files.");
1209+
self.WriteLn("# Flags passed to only C files.")
12081210
self.WriteList(cflags_c, 'CFLAGS_C_%s' % configname)
1209-
self.WriteLn("# Flags passed to only C++ files.");
1211+
self.WriteLn("# Flags passed to only C++ files.")
12101212
self.WriteList(cflags_cc, 'CFLAGS_CC_%s' % configname)
12111213
if self.flavor == 'mac':
1212-
self.WriteLn("# Flags passed to only ObjC files.");
1214+
self.WriteLn("# Flags passed to only ObjC files.")
12131215
self.WriteList(cflags_objc, 'CFLAGS_OBJC_%s' % configname)
1214-
self.WriteLn("# Flags passed to only ObjC++ files.");
1216+
self.WriteLn("# Flags passed to only ObjC++ files.")
12151217
self.WriteList(cflags_objcc, 'CFLAGS_OBJCC_%s' % configname)
12161218
includes = config.get('include_dirs')
12171219
if includes:
@@ -1359,8 +1361,8 @@ def ComputeOutputBasename(self, spec):
13591361
elif self.type == 'none':
13601362
target = '%s.stamp' % target
13611363
elif self.type != 'executable':
1362-
print ("ERROR: What output file should be generated?",
1363-
"type", self.type, "target", target)
1364+
print("ERROR: What output file should be generated?",
1365+
"type", self.type, "target", target)
13641366

13651367
target_prefix = spec.get('product_prefix', target_prefix)
13661368
target = spec.get('product_name', target)
@@ -1524,7 +1526,7 @@ def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps,
15241526
# Postbuilds expect to be run in the gyp file's directory, so insert an
15251527
# implicit postbuild to cd to there.
15261528
postbuilds.insert(0, gyp.common.EncodePOSIXShellList(['cd', self.path]))
1527-
for i in xrange(len(postbuilds)):
1529+
for i in range(len(postbuilds)):
15281530
if not postbuilds[i].startswith('$'):
15291531
postbuilds[i] = EscapeShellArgument(postbuilds[i])
15301532
self.WriteLn('%s: builddir := $(abs_builddir)' % QuoteSpaces(self.output))
@@ -1616,7 +1618,7 @@ def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps,
16161618
self.WriteDoCmd([self.output_binary], deps, 'touch', part_of_all,
16171619
postbuilds=postbuilds)
16181620
else:
1619-
print "WARNING: no output for", self.type, target
1621+
print("WARNING: no output for", self.type, self.target)
16201622

16211623
# Add an alias for each target (if there are any outputs).
16221624
# Installable target aliases are created below.
@@ -1968,7 +1970,7 @@ def PerformBuild(data, configurations, params):
19681970
if options.toplevel_dir and options.toplevel_dir != '.':
19691971
arguments += '-C', options.toplevel_dir
19701972
arguments.append('BUILDTYPE=' + config)
1971-
print 'Building [%s]: %s' % (config, arguments)
1973+
print('Building [%s]: %s' % (config, arguments))
19721974
subprocess.check_call(arguments)
19731975

19741976

0 commit comments

Comments
 (0)