//build: Convert print statements to Python 3 style

Ran "2to3 -w -n -f print ./base" and manually added imports.
There are no intended behaviour changes.

Bug: 941669
Change-Id: Ie2830e213eae3a5d7753ce503020e02811b726d1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1585890
Commit-Queue: Raul Tambre <raul@tambre.ee>
Reviewed-by: Nico Weber <thakis@chromium.org>
Reviewed-by: Dirk Pranke <dpranke@chromium.org>
Auto-Submit: Raul Tambre <raul@tambre.ee>
Cr-Original-Commit-Position: refs/heads/master@{#658917}
Cr-Mirrored-From: https://chromium.googlesource.com/chromium/src
Cr-Mirrored-Commit: 9e24293bf2459779641201495baa3b2ae9d13cd9
This commit is contained in:
Raul Tambre 2019-05-12 06:11:07 +00:00 коммит произвёл Commit Bot
Родитель ebd17ddb44
Коммит 0fdfe6341a
74 изменённых файлов: 475 добавлений и 326 удалений

Просмотреть файл

@ -5,6 +5,8 @@
"""Utility for reading / writing command-line flag files on device(s)."""
from __future__ import print_function
import argparse
import logging
import sys
@ -80,14 +82,14 @@ Otherwise: Writes command-line file.
updated_values = all_devices.pMap(update_flags).pGet(None)
print '%sCurrent flags (in %s):' % (action, args.name)
print('%sCurrent flags (in %s):' % (action, args.name))
for d, desc, flags in updated_values:
if flags:
# Shell-quote flags for easy copy/paste as new args on the terminal.
quoted_flags = ' '.join(cmd_helper.SingleQuote(f) for f in sorted(flags))
else:
quoted_flags = '( empty )'
print ' %s (%s): %s' % (d, desc, quoted_flags)
print(' %s (%s): %s' % (d, desc, quoted_flags))
return 0

Просмотреть файл

@ -16,6 +16,8 @@ resilient across phone disconnects and reconnects and start the logcat
early enough to not miss anything.
"""
from __future__ import print_function
import logging
import os
import re
@ -98,7 +100,7 @@ def main(base_dir, adb_cmd='adb'):
"""Monitor adb forever. Expects a SIGINT (Ctrl-C) to kill."""
# We create the directory to ensure 'run once' semantics
if os.path.exists(base_dir):
print 'adb_logcat_monitor: %s already exists? Cleaning' % base_dir
print('adb_logcat_monitor: %s already exists? Cleaning' % base_dir)
shutil.rmtree(base_dir, ignore_errors=True)
os.makedirs(base_dir)
@ -150,7 +152,7 @@ def main(base_dir, adb_cmd='adb'):
if __name__ == '__main__':
if 2 <= len(sys.argv) <= 3:
print 'adb_logcat_monitor: Initializing'
print('adb_logcat_monitor: Initializing')
sys.exit(main(*sys.argv[1:3]))
print 'Usage: %s <base_dir> [<adb_binary_path>]' % sys.argv[0]
print('Usage: %s <base_dir> [<adb_binary_path>]' % sys.argv[0])

Просмотреть файл

@ -6,6 +6,8 @@
# Using colorama.Fore/Back/Style members
# pylint: disable=no-member
from __future__ import print_function
import argparse
import collections
import json
@ -222,7 +224,7 @@ def _InstallBundle(devices, bundle_apks, package_name, command_line_flags_file,
if ShouldWarnFakeFeatureModuleInstallFlag(device):
msg = ('Command line has no %s: Fake modules will be ignored.' %
FAKE_FEATURE_MODULE_INSTALL)
print _Colorize(msg, colorama.Fore.YELLOW + colorama.Style.BRIGHT)
print(_Colorize(msg, colorama.Fore.YELLOW + colorama.Style.BRIGHT))
InstallFakeModules(device)
@ -346,8 +348,8 @@ def _LaunchUrl(devices, package_name, argv=None, command_line_flags_file=None,
device.StartActivity(launch_intent)
device_utils.DeviceUtils.parallel(devices).pMap(launch)
if wait_for_java_debugger:
print ('Waiting for debugger to attach to process: ' +
_Colorize(debug_process_name, colorama.Fore.YELLOW))
print('Waiting for debugger to attach to process: ' +
_Colorize(debug_process_name, colorama.Fore.YELLOW))
def _ChangeFlags(devices, argv, command_line_flags_file):
@ -399,8 +401,8 @@ def _RunGdb(device, package_name, debug_process_name, pid, output_directory,
if target_cpu:
cmd.append('--target-arch=%s' % _TargetCpuToTargetArch(target_cpu))
logging.warning('Running: %s', ' '.join(pipes.quote(x) for x in cmd))
print _Colorize(
'All subsequent output is from adb_gdb script.', colorama.Fore.YELLOW)
print(_Colorize('All subsequent output is from adb_gdb script.',
colorama.Fore.YELLOW))
os.execv(gdb_script_path, cmd)
@ -431,13 +433,12 @@ def _RunMemUsage(devices, package_name, query_app=False):
all_results = parallel_devices.pMap(mem_usage_helper).pGet(None)
for result in _PrintPerDeviceOutput(devices, all_results):
if not result:
print 'No processes found.'
print('No processes found.')
else:
for name, usage in sorted(result):
print _Colorize(
'==== Output of "dumpsys meminfo %s" ====' % name,
colorama.Fore.GREEN)
print usage
print(_Colorize('==== Output of "dumpsys meminfo %s" ====' % name,
colorama.Fore.GREEN))
print(usage)
def _DuHelper(device, path_spec, run_as=None):
@ -609,15 +610,15 @@ def _RunDiskUsage(devices, package_name):
compilation_filter)
def print_sizes(desc, sizes):
print '%s: %d KiB' % (desc, sum(sizes.itervalues()))
print('%s: %d KiB' % (desc, sum(sizes.itervalues())))
for path, size in sorted(sizes.iteritems()):
print ' %s: %s KiB' % (path, size)
print(' %s: %s KiB' % (path, size))
parallel_devices = device_utils.DeviceUtils.parallel(devices)
all_results = parallel_devices.pMap(disk_usage_helper).pGet(None)
for result in _PrintPerDeviceOutput(devices, all_results):
if not result:
print 'APK is not installed.'
print('APK is not installed.')
continue
(data_dir_sizes, code_cache_sizes, apk_sizes, lib_sizes, odex_sizes,
@ -634,7 +635,7 @@ def _RunDiskUsage(devices, package_name):
if show_warning:
logging.warning('For a more realistic odex size, run:')
logging.warning(' %s compile-dex [speed|speed-profile]', sys.argv[0])
print 'Total: %s KiB (%.1f MiB)' % (total, total / 1024.0)
print('Total: %s KiB (%.1f MiB)' % (total, total / 1024.0))
class _LogcatProcessor(object):
@ -801,13 +802,13 @@ def _RunPs(devices, package_name):
lambda d: _GetPackageProcesses(d, package_name)).pGet(None)
for processes in _PrintPerDeviceOutput(devices, all_processes):
if not processes:
print 'No processes found.'
print('No processes found.')
else:
proc_map = collections.defaultdict(list)
for p in processes:
proc_map[p.name].append(str(p.pid))
for name, pids in sorted(proc_map.items()):
print name, ','.join(pids)
print(name, ','.join(pids))
def _RunShell(devices, package_name, cmd):
@ -817,7 +818,7 @@ def _RunShell(devices, package_name, cmd):
cmd, run_as=package_name).pGet(None)
for output in _PrintPerDeviceOutput(devices, outputs):
for line in output:
print line
print(line)
else:
adb_path = adb_wrapper.AdbWrapper.GetAdbPath()
cmd = [adb_path, '-s', devices[0].serial, 'shell']
@ -825,9 +826,9 @@ def _RunShell(devices, package_name, cmd):
if devices[0].build_version_sdk >= version_codes.NOUGAT:
cmd += ['-t', 'run-as', package_name]
else:
print 'Upon entering the shell, run:'
print 'run-as', package_name
print
print('Upon entering the shell, run:')
print('run-as', package_name)
print()
os.execv(adb_path, cmd)
@ -838,7 +839,7 @@ def _RunCompileDex(devices, package_name, compilation_filter):
outputs = parallel_devices.RunShellCommand(cmd, timeout=120).pGet(None)
for output in _PrintPerDeviceOutput(devices, outputs):
for line in output:
print line
print(line)
def _RunProfile(device, package_name, host_build_directory, pprof_out_path,
@ -858,7 +859,7 @@ def _RunProfile(device, package_name, host_build_directory, pprof_out_path,
simpleperf.ConvertSimpleperfToPprof(host_simpleperf_out_path,
host_build_directory, pprof_out_path)
print textwrap.dedent("""
print(textwrap.dedent("""
Profile data written to %(s)s.
To view profile as a call graph in browser:
@ -868,7 +869,7 @@ def _RunProfile(device, package_name, host_build_directory, pprof_out_path,
pprof -top %(s)s
pprof has many useful customization options; `pprof --help` for details.
""" % {'s': pprof_out_path})
""" % {'s': pprof_out_path}))
def _GenerateAvailableDevicesMessage(devices):
@ -894,11 +895,11 @@ def _DisplayArgs(devices, command_line_flags_file):
parallel_devices = device_utils.DeviceUtils.parallel(devices)
outputs = parallel_devices.pMap(flags_helper).pGet(None)
print 'Existing flags per-device (via /data/local/tmp/{}):'.format(
command_line_flags_file)
print('Existing flags per-device (via /data/local/tmp/{}):'.format(
command_line_flags_file))
for flags in _PrintPerDeviceOutput(devices, outputs, single_line=True):
quoted_flags = ' '.join(pipes.quote(f) for f in flags)
print quoted_flags or 'No flags set.'
print(quoted_flags or 'No flags set.')
def _DeviceCachePath(device, output_directory):
@ -1134,7 +1135,7 @@ class _DevicesCommand(_Command):
all_devices_by_default = True
def Run(self):
print _GenerateAvailableDevicesMessage(self.devices)
print(_GenerateAvailableDevicesMessage(self.devices))
class _PackageInfoCommand(_Command):
@ -1148,12 +1149,12 @@ class _PackageInfoCommand(_Command):
def Run(self):
# Format all (even ints) as strings, to handle cases where APIs return None
print 'Package name: "%s"' % self.args.package_name
print 'versionCode: %s' % self.apk_helper.GetVersionCode()
print 'versionName: "%s"' % self.apk_helper.GetVersionName()
print 'minSdkVersion: %s' % self.apk_helper.GetMinSdkVersion()
print 'targetSdkVersion: %s' % self.apk_helper.GetTargetSdkVersion()
print 'Supported ABIs: %r' % self.apk_helper.GetAbis()
print('Package name: "%s"' % self.args.package_name)
print('versionCode: %s' % self.apk_helper.GetVersionCode())
print('versionName: "%s"' % self.apk_helper.GetVersionName())
print('minSdkVersion: %s' % self.apk_helper.GetMinSdkVersion())
print('targetSdkVersion: %s' % self.apk_helper.GetTargetSdkVersion())
print('Supported ABIs: %r' % self.apk_helper.GetAbis())
class _InstallCommand(_Command):

Просмотреть файл

@ -4,6 +4,7 @@
# 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 optparse
@ -105,9 +106,9 @@ def _PrintSymbolized(asan_input, arch):
# that usually one wants to display the last list item, not the first.
# The code below takes the first, is this the best choice here?
s = all_symbols[m.library][m.rel_address][0]
print '%s%s %s %s' % (m.prefix, m.pos, s[0], s[1])
print('%s%s %s %s' % (m.prefix, m.pos, s[0], s[1]))
else:
print log_line.raw
print(log_line.raw)
def main():

Просмотреть файл

@ -3,6 +3,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 argparse
import os
import sys
@ -38,10 +40,10 @@ def MaybeDownloadApk(builder, milestone, apk, download_path, bucket):
sha1_path = apk_path + '.sha1'
base_url = os.path.join(bucket, builder, milestone)
if os.path.exists(apk_path):
print '%s already exists' % apk_path
print('%s already exists' % apk_path)
return apk_path
elif not os.path.exists(sha1_path):
print 'Skipping %s, file not found' % sha1_path
print('Skipping %s, file not found' % sha1_path)
return None
else:
download_from_google_storage.download_from_google_storage(

Просмотреть файл

@ -5,6 +5,8 @@
"""Runs resource_sizes.py on two apks and outputs the diff."""
from __future__ import print_function
import argparse
import json
import logging
@ -152,7 +154,7 @@ def main():
try:
subprocess.check_output(base_args, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print e.output
print(e.output)
raise
diff_args = shared_args + ['--output-dir', diff_dir, args.diff_apk]
@ -161,7 +163,7 @@ def main():
try:
subprocess.check_output(diff_args, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print e.output
print(e.output)
raise
# Combine the separate results

Просмотреть файл

@ -6,6 +6,8 @@
"""A script to parse and dump localized strings in resource.arsc files."""
from __future__ import print_function
import argparse
import collections
import contextlib
@ -207,13 +209,13 @@ class ResourceStringValues(object):
else:
# Sanity check: the resource name should be the same for all chunks.
# Resource ID is redefined with a different name!!
print 'WARNING: Resource key ignored (%s, should be %s)' % (
res_name, self.res_name)
print('WARNING: Resource key ignored (%s, should be %s)' %
(res_name, self.res_name))
if self.res_values.setdefault(res_config, res_value) is not res_value:
print 'WARNING: Duplicate value definition for [config %s]: %s ' \
print('WARNING: Duplicate value definition for [config %s]: %s ' \
'(already has %s)' % (
res_config, res_value, self.res_values[res_config])
res_config, res_value, self.res_values[res_config]))
def ToStringList(self, res_id):
"""Convert entry to string list for human-friendly output."""

Просмотреть файл

@ -6,6 +6,8 @@
"""Aggregates EMMA coverage files to produce html output."""
from __future__ import print_function
import fnmatch
import json
import optparse
@ -61,8 +63,8 @@ def main():
# Filter out zero-length files. These are created by emma_instr.py when a
# target has no classes matching the coverage filter.
metadata_files = [f for f in metadata_files if os.path.getsize(f)]
print 'Found coverage files: %s' % str(coverage_files)
print 'Found metadata files: %s' % str(metadata_files)
print('Found coverage files: %s' % str(coverage_files))
print('Found metadata files: %s' % str(metadata_files))
sources = []
for f in metadata_files:

Просмотреть файл

@ -16,6 +16,8 @@ python gn/gn_to_cmake.py out/config/project.json
The first is recommended, as it will auto-update.
"""
from __future__ import print_function
import functools
import json
import posixpath
@ -513,8 +515,8 @@ def WriteTarget(out, target, project):
out.write('\n')
if target.cmake_type is None:
print 'Target {} has unknown target type {}, skipping.'.format(
target.gn_name, target.gn_type)
print('Target {} has unknown target type {}, skipping.'.format(
target.gn_name, target.gn_type))
return
SetVariable(out, 'target', target.cmake_name)
@ -672,7 +674,7 @@ def WriteProject(project):
def main():
if len(sys.argv) != 2:
print 'Usage: ' + sys.argv[0] + ' <json_file_name>'
print('Usage: ' + sys.argv[0] + ' <json_file_name>')
exit(1)
json_path = sys.argv[1]

Просмотреть файл

@ -5,6 +5,8 @@
"""Checks the number of static initializers in an APK's library."""
from __future__ import print_function
import argparse
import os
import re
@ -54,7 +56,7 @@ def _PrintDumpSIsCount(apk_so_name, unzipped_so, out_dir, tool_prefix):
_VerifyLibBuildIdsMatch(tool_prefix, unzipped_so, so_with_symbols_path)
sis, _ = _GetStaticInitializers(so_with_symbols_path, tool_prefix)
for si in sis:
print si
print(si)
# Mostly copied from //infra/scripts/legacy/scripts/slave/chromium/sizes.py.
@ -132,24 +134,24 @@ def main():
si_count = _AnalyzeStaticInitializers(args.apk, args.tool_prefix, False, '.',
ignored_libs)
if si_count != args.expected_count:
print 'Expected {} static initializers, but found {}.'.format(
args.expected_count, si_count)
print('Expected {} static initializers, but found {}.'.format(
args.expected_count, si_count))
if args.expected_count > si_count:
print 'You have removed one or more static initializers. Thanks!'
print 'To fix the build, update the expectation in:'
print ' //chrome/android/static_initializers.gni'
print('You have removed one or more static initializers. Thanks!')
print('To fix the build, update the expectation in:')
print(' //chrome/android/static_initializers.gni')
else:
print 'Dumping static initializers via dump-static-initializers.py:'
print('Dumping static initializers via dump-static-initializers.py:')
sys.stdout.flush()
_AnalyzeStaticInitializers(args.apk, args.tool_prefix, True, '.',
ignored_libs)
print
print 'If the above list is not useful, consider listing them with:'
print ' //tools/binary_size/diagnose_bloat.py'
print
print 'For more information:'
print (' https://chromium.googlesource.com/chromium/src/+/master/docs/'
'static_initializers.md')
print()
print('If the above list is not useful, consider listing them with:')
print(' //tools/binary_size/diagnose_bloat.py')
print()
print('For more information:')
print(' https://chromium.googlesource.com/chromium/src/+/master/docs/'
'static_initializers.md')
sys.exit(1)
if args.touch:

Просмотреть файл

@ -6,6 +6,8 @@
"""Copies files to a directory."""
from __future__ import print_function
import filecmp
import itertools
import optparse
@ -53,8 +55,8 @@ def DoCopy(options, deps):
for f in files:
if os.path.isdir(f) and not options.clear:
print ('To avoid stale files you must use --clear when copying '
'directories')
print('To avoid stale files you must use --clear when copying '
'directories')
sys.exit(-1)
CopyFile(f, options.dest, deps)
@ -74,7 +76,7 @@ def DoRenaming(options, deps):
for src, dest in itertools.izip(src_files, dest_files):
if os.path.isdir(src):
print ('renaming diretory is not supported.')
print('renaming diretory is not supported.')
sys.exit(-1)
else:
CopyFile(src, os.path.join(options.dest, dest), deps)

Просмотреть файл

@ -17,6 +17,8 @@ SCRIPT_TEMPLATE = textwrap.dedent(
#
# This file was generated by build/android/gyp/create_stack_script.py
from __future__ import print_function
import os
import sys
@ -29,7 +31,7 @@ SCRIPT_TEMPLATE = textwrap.dedent(
for arg, path in script_path_args:
script_args.extend([arg, resolve(path)])
script_cmd = [script_path] + script_args + argv
print ' '.join(script_cmd)
print(' '.join(script_cmd))
os.execv(script_path, script_cmd)
if __name__ == '__main__':

Просмотреть файл

@ -17,6 +17,8 @@ Possible commands are:
Also removes any stale coverage files.
"""
from __future__ import print_function
import collections
import json
import optparse
@ -121,8 +123,8 @@ def _CreateSourcesListFile(source_dirs, sources_list_file, src_root):
for s in source_dirs:
abs_source = os.path.abspath(s)
if abs_source[:len(src_root)] != src_root:
print ('Error: found source directory not under repository root: %s %s'
% (abs_source, src_root))
print('Error: found source directory not under repository root: %s %s' %
(abs_source, src_root))
return 1
rel_source = os.path.relpath(abs_source, src_root)

Просмотреть файл

@ -7,6 +7,8 @@
"""Finds files in directories.
"""
from __future__ import print_function
import fnmatch
import optparse
import os
@ -20,11 +22,12 @@ def main(argv):
for d in directories:
if not os.path.exists(d):
print >> sys.stderr, '%s does not exist' % d
print('%s does not exist' % d, file=sys.stderr)
return 1
for root, _, filenames in os.walk(d):
for f in fnmatch.filter(filenames, options.pattern):
print os.path.join(root, f)
print(os.path.join(root, f))
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))

Просмотреть файл

@ -6,6 +6,7 @@
"""Runs Android's lint tool."""
from __future__ import print_function
import argparse
import os
@ -61,7 +62,7 @@ def _OnStaleMd5(lint_path, config_path, processed_config_path,
dom = minidom.parse(result_path)
issues = dom.getElementsByTagName('issue')
if not silent:
print >> sys.stderr
print(file=sys.stderr)
for issue in issues:
issue_id = issue.attributes['id'].value
message = issue.attributes['message'].value
@ -73,11 +74,11 @@ def _OnStaleMd5(lint_path, config_path, processed_config_path,
else:
# Issues in class files don't have a line number.
error = '%s %s: %s [warning]' % (path, message, issue_id)
print >> sys.stderr, error.encode('utf-8')
print(error.encode('utf-8'), file=sys.stderr)
for attr in ['errorLine1', 'errorLine2']:
error_line = issue.getAttribute(attr)
if error_line:
print >> sys.stderr, error_line.encode('utf-8')
print(error_line.encode('utf-8'), file=sys.stderr)
return len(issues)
with build_utils.TempDir() as temp_dir:
@ -166,7 +167,7 @@ def _OnStaleMd5(lint_path, config_path, processed_config_path,
# classpath is necessary for most source-level checks.
with open(os.path.join(project_dir, 'project.properties'), 'w') \
as propfile:
print >> propfile, 'target=android-{}'.format(android_sdk_version)
print('target=android-{}'.format(android_sdk_version), file=propfile)
# Put the manifest in a temporary directory in order to avoid lint detecting
# sibling res/ and src/ directories (which should be pass explicitly if they
@ -222,10 +223,10 @@ def _OnStaleMd5(lint_path, config_path, processed_config_path,
num_issues = _ParseAndShowResultFile()
except Exception: # pylint: disable=broad-except
if not silent:
print 'Lint created unparseable xml file...'
print 'File contents:'
print('Lint created unparseable xml file...')
print('File contents:')
with open(result_path) as f:
print f.read()
print(f.read())
if can_fail_build:
traceback.print_exc()
if can_fail_build:
@ -243,7 +244,7 @@ def _OnStaleMd5(lint_path, config_path, processed_config_path,
' please refer to %s\n' %
(num_issues, _RebasePath(result_path), _LINT_MD_URL))
if not silent:
print >> sys.stderr, msg
print(msg, file=sys.stderr)
if can_fail_build:
raise Exception('Lint failed.')

Просмотреть файл

@ -552,6 +552,8 @@ This type corresponds to an Android app bundle (`.aab` file).
--------------- END_MARKDOWN ---------------------------------------------------
"""
from __future__ import print_function
import collections
import itertools
import json

Просмотреть файл

@ -10,6 +10,8 @@ Usage:
lighttpd_server PATH_TO_DOC_ROOT
"""
from __future__ import print_function
import codecs
import contextlib
import httplib
@ -105,8 +107,8 @@ class LighttpdServer(object):
self.process.close()
if self.fixed_port or 'in use' not in server_error:
print 'Client error:', client_error
print 'Server error:', server_error
print('Client error:', client_error)
print('Server error:', server_error)
return False
self.port = self._GetRandomPort()
return True
@ -249,7 +251,7 @@ def main(argv):
raw_input('Server running at http://127.0.0.1:%s -'
' press Enter to exit it.' % server.port)
else:
print 'Server exit code:', server.process.exitstatus
print('Server exit code:', server.process.exitstatus)
finally:
server.ShutdownHttpServer()

Просмотреть файл

@ -8,6 +8,7 @@
# pylint: disable=no-member
from __future__ import print_function
import argparse
import collections
@ -49,7 +50,7 @@ _Issue = collections.namedtuple('Issue', ['severity', 'paths', 'regexps'])
def _ParseConfigFile(config_path):
print 'Parsing %s' % config_path
print('Parsing %s' % config_path)
issues_dict = {}
dom = minidom.parse(config_path)
for issue in dom.getElementsByTagName('issue'):
@ -71,7 +72,7 @@ def _ParseConfigFile(config_path):
def _ParseAndMergeResultFile(result_path, issues_dict):
print 'Parsing and merging %s' % result_path
print('Parsing and merging %s' % result_path)
dom = minidom.parse(result_path)
for issue in dom.getElementsByTagName('issue'):
issue_id = issue.attributes['id'].value
@ -98,7 +99,7 @@ def _WriteConfigFile(config_path, issues_dict):
if issue.severity:
issue_element.attributes['severity'] = issue.severity
if issue.severity == 'ignore':
print 'Warning: [%s] is suppressed globally.' % issue_id
print('Warning: [%s] is suppressed globally.' % issue_id)
else:
for path in sorted(issue.paths):
ignore_element = new_dom.createElement('ignore')
@ -112,7 +113,7 @@ def _WriteConfigFile(config_path, issues_dict):
with open(config_path, 'w') as f:
f.write(new_dom.toprettyxml(indent=' ', encoding='utf-8'))
print 'Updated %s' % config_path
print('Updated %s' % config_path)
def _Suppress(config_path, result_path):

Просмотреть файл

@ -39,11 +39,11 @@ class InstrumentationParser(object):
for code, bundle in parser.IterStatus():
# do something with each instrumentation status
print 'status:', code, bundle
print('status:', code, bundle)
# do something with the final instrumentation result
code, bundle = parser.GetResult()
print 'result:', code, bundle
print('result:', code, bundle)
Args:
stream: a sequence of lines as produced by the raw output of an

Просмотреть файл

@ -35,6 +35,8 @@
"""
# pylint: disable=R0201
from __future__ import print_function
import logging
import re
@ -158,7 +160,7 @@ class LinkerTestCaseBase(object):
A base_test_result.TestRunResult() instance.
"""
margin = 8
print '[ %-*s ] %s' % (margin, 'RUN', self.tagged_name)
print('[ %-*s ] %s' % (margin, 'RUN', self.tagged_name))
logging.info('Running linker test: %s', self.tagged_name)
command_line_flags = ''
@ -174,7 +176,7 @@ class LinkerTestCaseBase(object):
result_text = 'FAILED'
elif status == ResultType.TIMEOUT:
result_text = 'TIMEOUT'
print '[ %*s ] %s' % (margin, result_text, self.tagged_name)
print('[ %*s ] %s' % (margin, result_text, self.tagged_name))
return base_test_result.BaseTestResult(self.tagged_name, status, log=logs)

Просмотреть файл

@ -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 json
import logging
import os
@ -134,7 +136,7 @@ class PerfTestInstance(test_instance.TestInstance):
for i in xrange(len(persisted_outputs)):
output_formatted += '\n\nOutput from run #%d:\n\n%s' % (
i, persisted_outputs[i])
print output_formatted
print(output_formatted)
if self.output_chartjson_data:
with file(self.output_chartjson_data, 'w') as f:

Просмотреть файл

@ -4,6 +4,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 argparse
import json
import os
@ -42,16 +44,17 @@ def merge_shard_results(summary_json, jsons_to_merge):
# name form, not in the number form.
state = result.get('state')
if state == u'BOT_DIED':
print >> sys.stderr, 'Shard #%d had a Swarming internal failure' % index
print(
'Shard #%d had a Swarming internal failure' % index, file=sys.stderr)
elif state == u'EXPIRED':
print >> sys.stderr, 'There wasn\'t enough capacity to run your test'
print('There wasn\'t enough capacity to run your test', file=sys.stderr)
elif state == u'TIMED_OUT':
print >> sys.stderr, (
'Test runtime exceeded allocated time'
'Either it ran for too long (hard timeout) or it didn\'t produce '
'I/O for an extended period of time (I/O timeout)')
print('Test runtime exceeded allocated time'
'Either it ran for too long (hard timeout) or it didn\'t produce '
'I/O for an extended period of time (I/O timeout)',
file=sys.stderr)
elif state != u'COMPLETED':
print >> sys.stderr, 'Invalid Swarming task state: %s' % state
print('Invalid Swarming task state: %s' % state, file=sys.stderr)
json_data, err_msg = load_shard_json(index, result.get('task_id'),
jsons_to_merge)
@ -66,14 +69,14 @@ def merge_shard_results(summary_json, jsons_to_merge):
merged['per_iteration_data'], json_data.get('per_iteration_data', []))
else:
merged['missing_shards'].append(index)
print >> sys.stderr, 'No result was found: %s' % err_msg
print('No result was found: %s' % err_msg, file=sys.stderr)
# If some shards are missing, make it known. Continue parsing anyway. Step
# should be red anyway, since swarming.py return non-zero exit code in that
# case.
if merged['missing_shards']:
as_str = ', '.join([str(shard) for shard in merged['missing_shards']])
print >> sys.stderr, ('some shards did not complete: %s' % as_str)
print('some shards did not complete: %s' % as_str, file=sys.stderr)
# Not all tests run, combined JSON summary can not be trusted.
merged['global_tags'].add('UNRELIABLE_RESULTS')
@ -106,10 +109,10 @@ def load_shard_json(index, task_id, jsons_to_merge):
os.path.basename(os.path.dirname(j)) == task_id))]
if not matching_json_files:
print >> sys.stderr, 'shard %s test output missing' % index
print('shard %s test output missing' % index, file=sys.stderr)
return (None, 'shard %s test output was missing' % index)
elif len(matching_json_files) > 1:
print >> sys.stderr, 'duplicate test output for shard %s' % index
print('duplicate test output for shard %s' % index, file=sys.stderr)
return (None, 'shard %s test output was duplicated' % index)
path = matching_json_files[0]
@ -117,15 +120,17 @@ def load_shard_json(index, task_id, jsons_to_merge):
try:
filesize = os.stat(path).st_size
if filesize > OUTPUT_JSON_SIZE_LIMIT:
print >> sys.stderr, 'output.json is %d bytes. Max size is %d' % (
filesize, OUTPUT_JSON_SIZE_LIMIT)
print(
'output.json is %d bytes. Max size is %d' % (filesize,
OUTPUT_JSON_SIZE_LIMIT),
file=sys.stderr)
return (None, 'shard %s test output exceeded the size limit' % index)
with open(path) as f:
return (json.load(f), None)
except (IOError, ValueError, OSError) as e:
print >> sys.stderr, 'Missing or invalid gtest JSON file: %s' % path
print >> sys.stderr, '%s: %s' % (type(e).__name__, e)
print('Missing or invalid gtest JSON file: %s' % path, file=sys.stderr)
print('%s: %s' % (type(e).__name__, e), file=sys.stderr)
return (None, 'shard %s test output was missing or invalid' % index)

Просмотреть файл

@ -4,6 +4,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 argparse
import collections
import contextlib
@ -463,8 +465,8 @@ def main():
if len(args.positional) == 0 and args.json_file is None:
if args.output_json:
with open(args.output_json, 'w') as f:
json.dump({}, f)
with open(args.output_json, 'w') as f:
json.dump({}, f)
return
elif len(args.positional) != 0 and args.json_file:
raise parser.error('Exactly one of args.positional and '
@ -533,10 +535,10 @@ def main():
with open(args.output_json, 'w') as f:
json.dump(json_object, f)
else:
print 'Result Details: %s' % result_details_link
print('Result Details: %s' % result_details_link)
if ui_screenshot_set_link:
print 'UI Screenshots %s' % ui_screenshot_link
print('UI Screenshots %s' % ui_screenshot_link)
if __name__ == '__main__':

Просмотреть файл

@ -4,6 +4,8 @@
"""Module containing utility functions for reporting results."""
from __future__ import print_function
import logging
import os
import re
@ -22,16 +24,19 @@ def _LogToFile(results, test_type, suite_name):
log_file_path, re.sub(r'\W', '_', test_type).lower() + '.log')
if not os.path.exists(full_file_name):
with open(full_file_name, 'w') as log_file:
print >> log_file, '\n%s results for %s build %s:' % (
test_type, os.environ.get('BUILDBOT_BUILDERNAME'),
os.environ.get('BUILDBOT_BUILDNUMBER'))
print(
'\n%s results for %s build %s:' %
(test_type, os.environ.get('BUILDBOT_BUILDERNAME'),
os.environ.get('BUILDBOT_BUILDNUMBER')),
file=log_file)
logging.info('Writing results to %s.', full_file_name)
logging.info('Writing results to %s.', full_file_name)
with open(full_file_name, 'a') as log_file:
shortened_suite_name = suite_name[:25] + (suite_name[25:] and '...')
print >> log_file, '%s%s' % (shortened_suite_name.ljust(30),
results.GetShortForm())
print(
'%s%s' % (shortened_suite_name.ljust(30), results.GetShortForm()),
file=log_file)
def _LogToFlakinessDashboard(results, test_type, test_package,

Просмотреть файл

@ -22,6 +22,8 @@ easy to use in a Python script, e.g. with a line like:
(0x<start-offset>, 0x<end-offset>, 0x<file-size>, <file-path>),
"""
from __future__ import print_function
import argparse
import os
import sys
@ -46,11 +48,11 @@ def main():
lib_map = apk_native_libs.ApkNativeLibraries(apk_reader)
for lib_path, file_offset, file_size in lib_map.GetDumpList():
if args.format == 'python':
print '(0x%08x, 0x%08x, 0x%08x, \'%s\'),' % (
file_offset, file_offset + file_size, file_size, lib_path)
print('(0x%08x, 0x%08x, 0x%08x, \'%s\'),' %
(file_offset, file_offset + file_size, file_size, lib_path))
else:
print '0x%08x 0x%08x 0x%08x %s' % (
file_offset, file_offset + file_size, file_size, lib_path)
print('0x%08x 0x%08x 0x%08x %s' % (file_offset, file_offset + file_size,
file_size, lib_path))
return 0

Просмотреть файл

@ -9,6 +9,8 @@ Outputs mock symbol information, with each symbol being a function of the
original address (so it is easy to double-check consistency in unittests).
"""
from __future__ import print_function
import optparse
import os
import posixpath
@ -36,8 +38,8 @@ def main(argv):
# An empty line should generate '??,??:0' (is used as marker for inlines).
if line == '\n':
print '??'
print '??:0'
print('??')
print('??:0')
sys.stdout.flush()
continue
@ -50,27 +52,27 @@ def main(argv):
# Addresses < 1M will return good mock symbol information.
if addr < 1024 * 1024:
print 'mock_sym_for_addr_%d' % addr
print 'mock_src/%s.c:%d' % (lib_file_name, addr)
print('mock_sym_for_addr_%d' % addr)
print('mock_src/%s.c:%d' % (lib_file_name, addr))
# Addresses 1M <= x < 2M will return symbols with a name but a missing path.
elif addr < 2 * 1024 * 1024:
print 'mock_sym_for_addr_%d' % addr
print '??:0'
print('mock_sym_for_addr_%d' % addr)
print('??:0')
# Addresses 2M <= x < 3M will return unknown symbol information.
elif addr < 3 * 1024 * 1024:
print '??'
print '??'
print('??')
print('??')
# Addresses 3M <= x < 4M will return inlines.
elif addr < 4 * 1024 * 1024:
print 'mock_sym_for_addr_%d_inner' % addr
print 'mock_src/%s.c:%d' % (lib_file_name, addr)
print 'mock_sym_for_addr_%d_middle' % addr
print 'mock_src/%s.c:%d' % (lib_file_name, addr)
print 'mock_sym_for_addr_%d_outer' % addr
print 'mock_src/%s.c:%d' % (lib_file_name, addr)
print('mock_sym_for_addr_%d_inner' % addr)
print('mock_src/%s.c:%d' % (lib_file_name, addr))
print('mock_sym_for_addr_%d_middle' % addr)
print('mock_src/%s.c:%d' % (lib_file_name, addr))
print('mock_sym_for_addr_%d_outer' % addr)
print('mock_src/%s.c:%d' % (lib_file_name, addr))
sys.stdout.flush()

Просмотреть файл

@ -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 bisect
import collections
import logging
@ -516,12 +518,12 @@ class MemoryMap(object):
def Dump(self):
"""Print memory map for debugging."""
print 'MEMORY MAP ['
print('MEMORY MAP [')
for t in self._addr_map:
print '[%08x-%08x %08x %08x %s]' % (
t.addr_start, t.addr_start + t.file_size, t.file_size, t.file_offset,
t.file_path)
print '] MEMORY MAP'
print('[%08x-%08x %08x %08x %s]' %
(t.addr_start, t.addr_start + t.file_size, t.file_size,
t.file_offset, t.file_path))
print('] MEMORY MAP')
def FindSectionForAddress(self, addr):
"""Find the map section corresponding to a specific memory address.

Просмотреть файл

@ -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 argparse
@ -42,7 +44,7 @@ class CustomHelpAction(argparse.Action):
self._help_text = custom_help_text
def __call__(self, parser, namespace, values, option_string=None):
print self._help_text
print(self._help_text)
parser.exit()
@staticmethod

Просмотреть файл

@ -4,6 +4,8 @@
# pylint: disable=R0201
from __future__ import print_function
import glob
import logging
import os.path
@ -106,8 +108,8 @@ def CreateTool(tool_name, device):
if ctor:
return ctor(device)
else:
print 'Unknown tool %s, available tools: %s' % (
tool_name, ', '.join(sorted(TOOL_REGISTRY.keys())))
print('Unknown tool %s, available tools: %s' % (tool_name, ', '.join(
sorted(TOOL_REGISTRY.keys()))))
sys.exit(1)
def PushFilesForTool(tool_name, device):
@ -124,6 +126,6 @@ def PushFilesForTool(tool_name, device):
if clazz:
clazz.CopyFiles(device)
else:
print 'Unknown tool %s, available tools: %s' % (
tool_name, ', '.join(sorted(TOOL_REGISTRY.keys())))
print('Unknown tool %s, available tools: %s' % (tool_name, ', '.join(
sorted(TOOL_REGISTRY.keys()))))
sys.exit(1)

Просмотреть файл

@ -4,6 +4,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 argparse
import os
import re
@ -95,7 +97,7 @@ def AddArguments(parser):
def _PrintAndLog(line, fp):
if fp:
fp.write('%s\n' % line)
print line
print(line)
def main():
@ -105,7 +107,7 @@ def main():
micro_dumps = GetMicroDumps(args.stack_trace_path)
if not micro_dumps:
print 'No microdump found. Exiting.'
print('No microdump found. Exiting.')
return 0
symbolized_dumps = []

Просмотреть файл

@ -5,6 +5,8 @@
# TODO: remove this script when GYP has for loops
from __future__ import print_function
import sys
import optparse
@ -20,7 +22,7 @@ def main(argv):
(options, arglist) = parser.parse_args(argv)
if len(arglist) < 3:
print 'ERROR: need string and list of locales'
print('ERROR: need string and list of locales')
return 1
str_template = arglist[1]
@ -39,7 +41,8 @@ def main(argv):
# Quote each element so filename spaces don't mess up GYP's attempt to parse
# it into a list.
print ' '.join(["'%s'" % x for x in results])
print(' '.join(["'%s'" % x for x in results]))
if __name__ == '__main__':
sys.exit(main(sys.argv))

Просмотреть файл

@ -9,6 +9,8 @@ This script gets all the header files from ninja_deps, which is from the true
dependency generated by the compiler, and report if they don't exist in GN.
"""
from __future__ import print_function
import argparse
import json
import os
@ -152,7 +154,7 @@ def IsBuildClean(out_dir):
out = subprocess.check_output(cmd)
return 'no work to do.' in out
except Exception as e:
print e
print(e)
return False
def ParseWhiteList(whitelist):
@ -211,7 +213,7 @@ def main():
# Assume running on the bots. Silently skip this step.
# This is possible because "analyze" step can be wrong due to
# underspecified header files. See crbug.com/725877
print dirty_msg
print(dirty_msg)
DumpJson([])
return 0
else:
@ -250,7 +252,7 @@ def main():
if deps_err:
PrintError(deps_err)
if len(GetNonExistingFiles(d)) > 0:
print 'Non-existing files in ninja deps:', GetNonExistingFiles(d)
print('Non-existing files in ninja deps:', GetNonExistingFiles(d))
PrintError('Found non-existing files in ninja deps. You should ' +
'build all in OUT_DIR.')
if len(d) == 0:
@ -272,30 +274,30 @@ def main():
return 0
if len(missing) > 0:
print '\nThe following files should be included in gn files:'
print('\nThe following files should be included in gn files:')
for i in missing:
print i
print(i)
if len(nonexisting) > 0:
print '\nThe following non-existing files should be removed from gn files:'
print('\nThe following non-existing files should be removed from gn files:')
for i in nonexisting:
print i
print(i)
if args.verbose:
# Only get detailed obj dependency here since it is slower.
GetHeadersFromNinja(args.out_dir, False, d_q)
d, d_err = d_q.get()
print '\nDetailed dependency info:'
print('\nDetailed dependency info:')
for f in missing:
print f
print(f)
for cc in d[f]:
print ' ', cc
print(' ', cc)
print '\nMissing headers sorted by number of affected object files:'
print('\nMissing headers sorted by number of affected object files:')
count = {k: len(v) for (k, v) in d.iteritems()}
for f in sorted(count, key=count.get, reverse=True):
if f in missing:
print count[f], f
print(count[f], f)
if args.json:
# Assume running on the bots. Temporarily return 0 before

Просмотреть файл

@ -6,12 +6,14 @@
"""This program wraps an arbitrary command and prints "1" if the command ran
successfully."""
from __future__ import print_function
import os
import subprocess
import sys
devnull = open(os.devnull, 'wb')
if not subprocess.call(sys.argv[1:], stdout=devnull, stderr=devnull):
print 1
print(1)
else:
print 0
print(0)

Просмотреть файл

@ -5,7 +5,8 @@
"""Get Byteorder of host architecture"""
from __future__ import print_function
import sys
print sys.byteorder
print(sys.byteorder)

Просмотреть файл

@ -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 argparse
import os
import subprocess
@ -44,4 +46,4 @@ if __name__ == '__main__':
os.environ['DEVELOPER_DIR'] = args.developer_dir
for identity in FindValidIdentity(args.identity_description):
print identity
print(identity)

Просмотреть файл

@ -2,14 +2,17 @@
# 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 struct
import sys
def Main(args):
if len(args) < 4:
print >> sys.stderr, "Usage: %s output.hmap Foo.framework header1.h..." %\
(args[0])
print(
"Usage: %s output.hmap Foo.framework header1.h..." % args[0],
file=sys.stderr)
return 1
(out, framework, all_headers) = args[1], args[2], args[3:]

Просмотреть файл

@ -3,6 +3,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 json
import os
import subprocess
@ -54,7 +56,7 @@ def SetConfigPath(options):
# Compute the library path name based on the architecture.
arch = options.arch
if sysroot and not arch:
print "You must specify an architecture via -a if using a sysroot."
print("You must specify an architecture via -a if using a sysroot.")
sys.exit(1)
libdir = sysroot + '/usr/' + options.system_libdir + '/pkgconfig'
@ -108,7 +110,7 @@ def main():
# success. This allows us to "kind of emulate" a Linux build from other
# platforms.
if "linux" not in sys.platform:
print "[[],[],[],[],[]]"
print("[[],[],[],[],[]]")
return 0
parser = OptionParser()
@ -148,9 +150,9 @@ def main():
if not subprocess.call([options.pkg_config,
"--atleast-version=" + options.atleast_version] +
args):
print "true"
print("true")
else:
print "false"
print("false")
return 0
if options.version_as_components:
@ -160,7 +162,7 @@ def main():
except:
sys.stderr.write('Error from pkg-config.\n')
return 1
print json.dumps(list(map(int, version_string.strip().split("."))))
print(json.dumps(list(map(int, version_string.strip().split(".")))))
return 0
@ -171,7 +173,7 @@ def main():
try:
libdir = subprocess.check_output(cmd)
except:
print "Error from pkg-config."
print("Error from pkg-config.")
return 1
sys.stdout.write(libdir.strip())
return 0
@ -183,7 +185,7 @@ def main():
try:
dridriverdir = subprocess.check_output(cmd)
except:
print "Error from pkg-config."
print("Error from pkg-config.")
return 1
sys.stdout.write(dridriverdir.strip())
return
@ -238,7 +240,7 @@ def main():
# Output a GN array, the first one is the cflags, the second are the libs. The
# JSON formatter prints GN compatible lists when everything is a list of
# strings.
print json.dumps([includes, cflags, libs, lib_dirs])
print(json.dumps([includes, cflags, libs, lib_dirs]))
return 0

Просмотреть файл

@ -2,6 +2,7 @@
# 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 argparse
import logging

Просмотреть файл

@ -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 argparse
import doctest
import itertools
@ -94,4 +96,4 @@ if __name__ == '__main__':
value = settings[key]
if isinstance(value, str):
value = '"%s"' % value
print '%s=%s' % (key, value)
print('%s=%s' % (key, value))

Просмотреть файл

@ -8,14 +8,16 @@
# TODO(brettw) the build/linux/sysroot_ld_path.sh script should be rewritten in
# Python in this file.
from __future__ import print_function
import subprocess
import sys
if len(sys.argv) != 3:
print "Need two arguments"
print("Need two arguments")
sys.exit(1)
result = subprocess.check_output([sys.argv[1], sys.argv[2]]).strip()
result = result.replace(" ", "\n")
if result != "":
print result
print(result)

Просмотреть файл

@ -5,6 +5,8 @@
"""Copies test data files or directories into a given output directory."""
from __future__ import print_function
import optparse
import os
import shutil
@ -95,10 +97,10 @@ def main(argv):
try:
result = DoMain(argv[1:])
except WrongNumberOfArgumentsException, e:
print >>sys.stderr, e
print(e, file=sys.stderr)
return 1
if result:
print result
print(result)
return 0
if __name__ == '__main__':

Просмотреть файл

@ -5,6 +5,8 @@
"""Outputs host CPU architecture in format recognized by gyp."""
from __future__ import print_function
import platform
import re
import sys
@ -50,4 +52,4 @@ def DoMain(_):
return HostArch()
if __name__ == '__main__':
print DoMain([])
print(DoMain([]))

Просмотреть файл

@ -5,6 +5,8 @@
"""Extracts a single file from a CAB archive."""
from __future__ import print_function
import os
import shutil
import subprocess
@ -17,12 +19,12 @@ def run_quiet(*args):
out, _ = popen.communicate()
if popen.returncode:
# expand emits errors to stdout, so if we fail, then print that out.
print out
print(out)
return popen.returncode
def main():
if len(sys.argv) != 4:
print 'Usage: extract_from_cab.py cab_path archived_file output_dir'
print('Usage: extract_from_cab.py cab_path archived_file output_dir')
return 1
[cab_path, archived_file, output_dir] = sys.argv[1:]

Просмотреть файл

@ -11,6 +11,8 @@ This can also be used as a standalone script to print out the depot_tools
directory location.
"""
from __future__ import print_function
import os
import sys
@ -53,7 +55,7 @@ def add_depot_tools_to_path():
return i
previous_dir = root_dir
root_dir = os.path.dirname(root_dir)
print >> sys.stderr, 'Failed to find depot_tools'
print('Failed to find depot_tools', file=sys.stderr)
return None
DEPOT_TOOLS_PATH = add_depot_tools_to_path()
@ -65,7 +67,7 @@ import breakpad
def main():
if DEPOT_TOOLS_PATH is None:
return 1
print DEPOT_TOOLS_PATH
print(DEPOT_TOOLS_PATH)
return 0

Просмотреть файл

@ -10,6 +10,8 @@ try to fix them by adding them to the GN files.
Manual cleaning up is likely required afterwards.
"""
from __future__ import print_function
import argparse
import os
import re
@ -39,7 +41,7 @@ def ValidMatches(basename, cc, grep_lines):
continue
if lines[linenr - 2] == new:
continue
print ' ', gnfile, linenr, new
print(' ', gnfile, linenr, new)
matches.append((gnfile, linenr, new))
return matches
@ -59,7 +61,7 @@ def AddHeadersNextToCC(headers, skip_ambiguous=True):
if not (filename.endswith('.h') or filename.endswith('.hh')):
continue
basename = os.path.basename(filename)
print filename
print(filename)
cc = r'\b' + os.path.splitext(basename)[0] + r'\.(cc|cpp|mm)\b'
out, returncode = GitGrep('(/|")' + cc + '"')
if returncode != 0 or not out:
@ -71,10 +73,10 @@ def AddHeadersNextToCC(headers, skip_ambiguous=True):
if len(matches) == 0:
continue
if len(matches) > 1:
print '\n[WARNING] Ambiguous matching for', filename
print('\n[WARNING] Ambiguous matching for', filename)
for i in enumerate(matches, 1):
print '%d: %s' % (i[0], i[1])
print
print('%d: %s' % (i[0], i[1]))
print()
if skip_ambiguous:
continue
@ -86,7 +88,7 @@ def AddHeadersNextToCC(headers, skip_ambiguous=True):
for match in matches:
gnfile, linenr, new = match
print ' ', gnfile, linenr, new
print(' ', gnfile, linenr, new)
edits.setdefault(gnfile, {})[linenr] = new
for gnfile in edits:
@ -111,7 +113,7 @@ def AddHeadersToSources(headers, skip_ambiguous=True):
"""
for filename in headers:
filename = filename.strip()
print filename
print(filename)
dirname = os.path.dirname(filename)
while not os.path.exists(os.path.join(dirname, 'BUILD.gn')):
dirname = os.path.dirname(dirname)
@ -121,12 +123,12 @@ def AddHeadersToSources(headers, skip_ambiguous=True):
lines = open(gnfile).read().splitlines()
matched = [i for i, l in enumerate(lines) if ' sources = [' in l]
if skip_ambiguous and len(matched) > 1:
print '[WARNING] Multiple sources in', gnfile
print('[WARNING] Multiple sources in', gnfile)
continue
if len(matched) < 1:
continue
print ' ', gnfile, rel
print(' ', gnfile, rel)
index = matched[0]
lines.insert(index + 1, '"%s",' % rel)
open(gnfile, 'w').write('\n'.join(lines) + '\n')
@ -144,18 +146,18 @@ def RemoveHeader(headers, skip_ambiguous=True):
if not (filename.endswith('.h') or filename.endswith('.hh')):
continue
basename = os.path.basename(filename)
print filename
print(filename)
out, returncode = GitGrep('(/|")' + basename + '"')
if returncode != 0 or not out:
unhandled.append(filename)
print ' Not found'
print(' Not found')
continue
grep_lines = out.splitlines()
matches = []
for line in grep_lines:
gnfile, linenr, contents = line.split(':')
print ' ', gnfile, linenr, contents
print(' ', gnfile, linenr, contents)
linenr = int(linenr)
lines = open(gnfile).read().splitlines()
assert contents in lines[linenr - 1]
@ -164,10 +166,10 @@ def RemoveHeader(headers, skip_ambiguous=True):
if len(matches) == 0:
continue
if len(matches) > 1:
print '\n[WARNING] Ambiguous matching for', filename
print('\n[WARNING] Ambiguous matching for', filename)
for i in enumerate(matches, 1):
print '%d: %s' % (i[0], i[1])
print
print('%d: %s' % (i[0], i[1]))
print()
if skip_ambiguous:
continue
@ -179,7 +181,7 @@ def RemoveHeader(headers, skip_ambiguous=True):
for match in matches:
gnfile, linenr, contents = match
print ' ', gnfile, linenr, contents
print(' ', gnfile, linenr, contents)
edits.setdefault(gnfile, set()).add(linenr)
for gnfile in edits:

Просмотреть файл

@ -4,6 +4,8 @@
"""Implements commands for running and interacting with Fuchsia on devices."""
from __future__ import print_function
import boot_data
import filecmp
import logging
@ -165,12 +167,12 @@ class DeviceTarget(target.Target):
# Handle the output of "dev_finder list".
if len(name_host_pairs) > 1:
print 'More than one device was discovered on the network.'
print 'Use --node-name <name> to specify the device to use.'
print '\nList of devices:'
print('More than one device was discovered on the network.')
print('Use --node-name <name> to specify the device to use.')
print('\nList of devices:')
for pair in name_host_pairs:
print ' ' + pair[1]
print
print(' ' + pair[1])
print()
raise Exception('Ambiguous target device specification.')
assert len(name_host_pairs) == 1

Просмотреть файл

@ -5,6 +5,8 @@
"""Contains a helper function for deploying and executing a packaged
executable on a Target."""
from __future__ import print_function
import common
import hashlib
import logging
@ -146,7 +148,7 @@ def _DrainStreamToStdout(stream, quit_event):
line = rlist[0].readline()
if not line:
return
print line.rstrip()
print(line.rstrip())
def RunPackage(output_dir, target, package_path, package_name,
@ -207,7 +209,7 @@ def RunPackage(output_dir, target, package_path, package_name,
output_stream = SymbolizerFilter(output_stream, build_ids_paths)
for next_line in output_stream:
print next_line.rstrip()
print(next_line.rstrip())
process.wait()
if process.returncode == 0:

Просмотреть файл

@ -6,6 +6,8 @@
"""Updates the Fuchsia SDK to the given revision. Should be used in a 'hooks_os'
entry so that it only runs when .gclient's target_os includes 'fuchsia'."""
from __future__ import print_function
import os
import re
import shutil
@ -59,8 +61,9 @@ def GetSdkHashForPlatform():
# If both files are empty, return an error.
if not sdk_hash and not extra_sdk_hash:
print >>sys.stderr, 'No SHA1 found in {} or {}'.format(
hash_file, extra_hash_file)
print(
'No SHA1 found in {} or {}'.format(hash_file, extra_hash_file),
file=sys.stderr)
return 1
# Return the newer SDK based on the generation number.
@ -77,7 +80,7 @@ def GetBucketForPlatform():
def EnsureDirExists(path):
if not os.path.exists(path):
print 'Creating directory %s' % path
print('Creating directory %s' % path)
os.makedirs(path)
@ -85,7 +88,7 @@ def EnsureDirExists(path):
def Cleanup(path):
hash_file = os.path.join(path, '.hash')
if os.path.exists(hash_file):
print 'Removing old SDK from %s.' % path
print('Removing old SDK from %s.' % path)
for d in SDK_SUBDIRS:
to_remove = os.path.join(path, d)
if os.path.isdir(to_remove):
@ -105,7 +108,7 @@ def UpdateTimestampsRecursive(path):
def main():
if len(sys.argv) != 1:
print >>sys.stderr, 'usage: %s' % sys.argv[0]
print('usage: %s' % sys.argv[0], file=sys.stderr)
return 1
# Quietly exit if there's no SDK support for this platform.
@ -135,7 +138,7 @@ def main():
subprocess.check_call([os.path.join(sdk_root, 'gen_build_defs.py')])
return 0
print 'Downloading SDK %s...' % sdk_hash
print('Downloading SDK %s...' % sdk_hash)
if os.path.isdir(output_dir):
shutil.rmtree(output_dir)

Просмотреть файл

@ -8,6 +8,8 @@ Run with:
python gn_run_binary.py <binary_name> [args ...]
"""
from __future__ import print_function
import os
import subprocess
import sys
@ -28,7 +30,7 @@ if ret != 0:
# Windows error codes such as 0xC0000005 and 0xC0000409 are much easier to
# recognize and differentiate in hex. In order to print them as unsigned
# hex we need to add 4 Gig to them.
print '%s failed with exit code 0x%08X' % (sys.argv[1], ret + (1 << 32))
print('%s failed with exit code 0x%08X' % (sys.argv[1], ret + (1 << 32)))
else:
print '%s failed with exit code %d' % (sys.argv[1], ret)
print('%s failed with exit code %d' % (sys.argv[1], ret))
sys.exit(ret)

Просмотреть файл

@ -34,13 +34,14 @@ build_apt_package_list() {
echo "Building apt package list." >&2
apt-cache dumpavail | \
python -c '\
from __future__ import print_function; \
import re,sys; \
o = sys.stdin.read(); \
p = {"i386": ":i386"}; \
f = re.M | re.S; \
r = re.compile(r"^Package: (.+?)$.+?^Architecture: (.+?)$", f); \
m = ["%s%s" % (x, p.get(y, "")) for x, y in re.findall(r, o)]; \
print "\n".join(m)'
print("\n".join(m))'
}
# Checks whether a particular package is available in the repos.

Просмотреть файл

@ -5,13 +5,15 @@
# Helper script to run dump_syms on Chrome Linux executables and strip
# them if needed.
from __future__ import print_function
import os
import subprocess
import sys
if len(sys.argv) != 5:
print "dump_app_syms.py <dump_syms_exe> <strip_binary>"
print " <binary_with_symbols> <symbols_output>"
print("dump_app_syms.py <dump_syms_exe> <strip_binary>")
print(" <binary_with_symbols> <symbols_output>")
sys.exit(1)
dumpsyms = sys.argv[1]

Просмотреть файл

@ -7,6 +7,8 @@
# This script can be run manually (as root), but is also run as part
# install-build-deps.sh.
from __future__ import print_function
import os
import shutil
import subprocess
@ -34,15 +36,15 @@ FONTS_DIR = '/usr/local/share/fonts'
def main(args):
if not sys.platform.startswith('linux'):
print "Error: %s must be run on Linux." % __file__
print("Error: %s must be run on Linux." % __file__)
return 1
if os.getuid() != 0:
print "Error: %s must be run as root." % __file__
print("Error: %s must be run as root." % __file__)
return 1
if not os.path.isdir(FONTS_DIR):
print "Error: Destination directory does not exist: %s" % FONTS_DIR
print("Error: Destination directory does not exist: %s" % FONTS_DIR)
return 1
dest_dir = os.path.join(FONTS_DIR, 'chromeos')
@ -51,7 +53,7 @@ def main(args):
if os.path.exists(stamp):
with open(stamp) as s:
if s.read() == '\n'.join(URLS):
print "Chrome OS fonts already up to date in %s." % dest_dir
print("Chrome OS fonts already up to date in %s." % dest_dir)
return 0
if os.path.isdir(dest_dir):
@ -59,7 +61,7 @@ def main(args):
os.mkdir(dest_dir)
os.chmod(dest_dir, 0755)
print "Installing Chrome OS fonts to %s." % dest_dir
print("Installing Chrome OS fonts to %s." % dest_dir)
for url in URLS:
tarball = os.path.join(dest_dir, os.path.basename(url))
subprocess.check_call(['curl', '-L', url, '-o', tarball])
@ -82,7 +84,7 @@ def main(args):
for file in files:
os.chmod(os.path.join(base, file), 0644)
print """\
print("""\
Chrome OS font rendering settings are specified using Fontconfig. If your
system's configuration doesn't match Chrome OS's (which vary for different
@ -110,7 +112,7 @@ To load additional per-font configs (and assuming you have Chrome OS checked
out), add the following immediately before the "</fontconfig>" line:
<include ignore_missing="yes">/path/to/src/third_party/chromiumos-overlay/media-libs/fontconfig/files/local.conf</include>
"""
""")
return 0

Просмотреть файл

@ -5,6 +5,8 @@
"""Rewrites paths in -I, -L and other option to be relative to a sysroot."""
from __future__ import print_function
import sys
import os
import optparse
@ -63,7 +65,7 @@ def main(argv):
for line in sys.stdin.readlines():
line = RewriteLine(line.strip(), opts)
print line
print(line)
return 0

Просмотреть файл

@ -7,6 +7,8 @@
UploadSysroot for each supported arch of each sysroot creator.
"""
from __future__ import print_function
import glob
import hashlib
import json
@ -87,13 +89,13 @@ def main():
for _, proc in procs:
proc.join()
print "SYSROOT CREATION SUMMARY"
print("SYSROOT CREATION SUMMARY")
failures = 0
for name, proc in procs:
if proc.exitcode:
failures += 1
status = "FAILURE" if proc.exitcode else "SUCCESS"
print "%s sysroot creation\t%s" % (name, status)
print("%s sysroot creation\t%s" % (name, status))
return failures

Просмотреть файл

@ -6,6 +6,8 @@
"""Find incompatible symbols in glibc and output a list of replacements.
"""
from __future__ import print_function
import re
import sys
@ -55,4 +57,4 @@ if __name__ == '__main__':
print('// Chromium-specific hack.')
print('// See explanation in sysroot-creator.sh.')
for replacement in replacements:
print replacement
print(replacement)

Просмотреть файл

@ -18,6 +18,8 @@
# time chrome's build dependencies are changed but should also be updated
# periodically to include upstream security fixes from Debian.
from __future__ import print_function
import hashlib
import json
import platform
@ -76,8 +78,8 @@ def main(args):
if options.print_hash:
arch = options.print_hash
print GetSysrootDict(DEFAULT_TARGET_PLATFORM,
ARCH_TRANSLATIONS.get(arch, arch))['Sha1Sum']
print(GetSysrootDict(DEFAULT_TARGET_PLATFORM,
ARCH_TRANSLATIONS.get(arch, arch))['Sha1Sum'])
return 0
if options.arch:
InstallSysroot(DEFAULT_TARGET_PLATFORM,
@ -86,7 +88,7 @@ def main(args):
for arch in VALID_ARCHS:
InstallSysroot(DEFAULT_TARGET_PLATFORM, arch)
else:
print 'You much specify one of the options.'
print('You much specify one of the options.')
return 1
return 0
@ -122,13 +124,13 @@ def InstallSysroot(target_platform, target_arch):
if s.read() == url:
return
print 'Installing Debian %s %s root image: %s' % \
(target_platform, target_arch, sysroot)
print('Installing Debian %s %s root image: %s' % \
(target_platform, target_arch, sysroot))
if os.path.isdir(sysroot):
shutil.rmtree(sysroot)
os.mkdir(sysroot)
tarball = os.path.join(sysroot, tarball_filename)
print 'Downloading %s' % url
print('Downloading %s' % url)
sys.stdout.flush()
sys.stderr.flush()
for _ in range(3):

Просмотреть файл

@ -9,6 +9,7 @@ Removes bundled libraries to make sure they are not used.
See README for more details.
"""
from __future__ import print_function
import optparse
import os.path
@ -21,8 +22,8 @@ def DoMain(argv):
os.path.join(my_dirname, '..', '..', '..'))
if os.path.join(source_tree_root, 'build', 'linux', 'unbundle') != my_dirname:
print ('Sanity check failed: please run this script from ' +
'build/linux/unbundle directory.')
print('Sanity check failed: please run this script from '
'build/linux/unbundle directory.')
return 1
parser = optparse.OptionParser()
@ -84,7 +85,7 @@ def DoMain(argv):
os.remove(path)
else:
# By default just print paths that would be removed.
print path
print(path)
exit_code = 0
@ -92,12 +93,12 @@ def DoMain(argv):
# up to date.
for exclusion, used in exclusion_used.iteritems():
if not used:
print '%s does not exist' % exclusion
print('%s does not exist' % exclusion)
exit_code = 1
if not options.do_remove:
print ('To actually remove files printed above, please pass ' +
'--do-remove flag.')
print('To actually remove files printed above, please pass '
'--do-remove flag.')
return exit_code

Просмотреть файл

@ -27,6 +27,9 @@ remoting/resources/remoting_strings.grd contains an in-line comment element
inside its <outputs> section that breaks the script. The check will fail, and
trying to fix it too, but at least the file will not be modified.
"""
from __future__ import print_function
import argparse
import json
import os
@ -103,9 +106,9 @@ def _CompareLocaleLists(list_a, list_expected, list_name):
errors.append('Unexpected locales: %s' % extra_locales)
if errors:
print 'Errors in %s definition:' % list_name
print('Errors in %s definition:' % list_name)
for error in errors:
print ' %s\n' % error
print(' %s\n' % error)
return True
return False
@ -202,22 +205,22 @@ def _ProcessFile(input_file, locales, check_func, fix_func):
Returns:
True at the moment.
"""
print '%sProcessing %s...' % (_CONSOLE_START_LINE, input_file),
print('%sProcessing %s...' % (_CONSOLE_START_LINE, input_file), end=' ')
sys.stdout.flush()
with open(input_file) as f:
input_lines = f.readlines()
errors = check_func(input_file, input_lines, locales)
if errors:
print '\n%s%s' % (_CONSOLE_START_LINE, '\n'.join(errors))
print('\n%s%s' % (_CONSOLE_START_LINE, '\n'.join(errors)))
if fix_func:
try:
input_lines = fix_func(input_file, input_lines, locales)
output = ''.join(input_lines)
with open(input_file, 'wt') as f:
f.write(output)
print 'Fixed %s.' % input_file
print('Fixed %s.' % input_file)
except Exception as e: # pylint: disable=broad-except
print 'Skipped %s: %s' % (input_file, e)
print('Skipped %s: %s' % (input_file, e))
return True
@ -1308,9 +1311,9 @@ instead of the default format (which is a space-separated list of locale names).
def Run(self):
locale_list = self.TYPE_MAP[self.args.type]()
if self.args.as_json:
print '[%s]' % ", ".join("'%s'" % loc for loc in locale_list)
print('[%s]' % ", ".join("'%s'" % loc for loc in locale_list))
else:
print ' '.join(locale_list)
print(' '.join(locale_list))
class _CheckInputFileBaseCommand(_Command):
@ -1368,7 +1371,7 @@ class _CheckInputFileBaseCommand(_Command):
locales,
self.check_func.__func__,
self.fix_func.__func__ if args.fix_inplace else None)
print '%sDone.' % (_CONSOLE_START_LINE)
print('%sDone.' % (_CONSOLE_START_LINE))
class _CheckGrdAndroidOutputsCommand(_CheckInputFileBaseCommand):

Просмотреть файл

@ -11,6 +11,8 @@ Usage:
python find_sdk.py [--developer_dir DEVELOPER_DIR] 10.6 # Ignores SDKs < 10.6
"""
from __future__ import print_function
import os
import re
import subprocess
@ -56,8 +58,8 @@ def main():
stderr=subprocess.STDOUT)
out, err = job.communicate()
if job.returncode != 0:
print >> sys.stderr, out
print >> sys.stderr, err
print(out, file=sys.stderr)
print(err, file=sys.stderr)
raise Exception('Error %d running xcode-select' % job.returncode)
sdk_dir = os.path.join(
out.rstrip(), 'Platforms/MacOSX.platform/Developer/SDKs')
@ -78,22 +80,22 @@ def main():
best_sdk = sorted(sdks, key=parse_version)[0]
if options.verify and best_sdk != min_sdk_version and not options.sdk_path:
print >> sys.stderr, ''
print >> sys.stderr, ' vvvvvvv'
print >> sys.stderr, ''
print >> sys.stderr, \
'This build requires the %s SDK, but it was not found on your system.' \
% min_sdk_version
print >> sys.stderr, \
'Either install it, or explicitly set mac_sdk in your GYP_DEFINES.'
print >> sys.stderr, ''
print >> sys.stderr, ' ^^^^^^^'
print >> sys.stderr, ''
print('', file=sys.stderr)
print(' vvvvvvv', file=sys.stderr)
print('', file=sys.stderr)
print('This build requires the %s SDK, but it was not found on your system.' \
% min_sdk_version, file=sys.stderr)
print(
'Either install it, or explicitly set mac_sdk in your GYP_DEFINES.',
file=sys.stderr)
print('', file=sys.stderr)
print(' ^^^^^^^', file=sys.stderr)
print('', file=sys.stderr)
sys.exit(1)
if options.print_sdk_path:
print subprocess.check_output(
['xcrun', '-sdk', 'macosx' + best_sdk, '--show-sdk-path']).strip()
print(subprocess.check_output(
['xcrun', '-sdk', 'macosx' + best_sdk, '--show-sdk-path']).strip())
return best_sdk
@ -101,5 +103,5 @@ def main():
if __name__ == '__main__':
if sys.platform != 'darwin':
raise Exception("This script only runs on Mac")
print main()
print(main())
sys.exit(0)

Просмотреть файл

@ -14,6 +14,8 @@ Usage:
python should_use_hermetic_xcode.py <target_os>
"""
from __future__ import print_function
import os
import sys
@ -42,5 +44,5 @@ def main():
if __name__ == '__main__':
print main()
print(main())
sys.exit(0)

Просмотреть файл

@ -20,6 +20,8 @@
# by the time the app target is done, the info.plist is correct.
#
from __future__ import print_function
import optparse
import os
import plistlib
@ -123,7 +125,7 @@ def _AddVersionKeys(
# True if the string is composed only of digits (and thus match \d+ regexp).
groups = version.split('.')
if len(groups) != 4 or not all(element.isdigit() for element in groups):
print >>sys.stderr, 'Invalid version string specified: "%s"' % version
print('Invalid version string specified: "%s"' % version, file=sys.stderr)
return False
values = dict(zip(('MAJOR', 'MINOR', 'BUILD', 'PATCH'), groups))
@ -153,7 +155,7 @@ def _DoSCMKeys(plist, add_keys):
if scm_revision != None:
plist['SCMRevision'] = scm_revision
elif add_keys:
print >>sys.stderr, 'Could not determine SCM revision. This may be OK.'
print('Could not determine SCM revision. This may be OK.', file=sys.stderr)
return True
@ -265,11 +267,11 @@ def Main(argv):
(options, args) = parser.parse_args(argv)
if len(args) > 0:
print >>sys.stderr, parser.get_usage()
print(parser.get_usage(), file=sys.stderr)
return 1
if not options.plist_path:
print >>sys.stderr, 'No --plist specified.'
print('No --plist specified.', file=sys.stderr)
return 1
# Read the plist into its parsed format. Convert the file to 'xml1' as
@ -285,12 +287,12 @@ def Main(argv):
if options.version_overrides:
for pair in options.version_overrides:
if not '=' in pair:
print >>sys.stderr, 'Invalid value for --version-overrides:', pair
print('Invalid value for --version-overrides:', pair, file=sys.stderr)
return 1
key, value = pair.split('=', 1)
overrides[key] = value
if key not in ('MAJOR', 'MINOR', 'BUILD', 'PATCH'):
print >>sys.stderr, 'Unsupported key for --version-overrides:', key
print('Unsupported key for --version-overrides:', key, file=sys.stderr)
return 1
if options.platform == 'mac':
@ -326,7 +328,7 @@ def Main(argv):
# Add Breakpad if configured to do so.
if options.use_breakpad:
if options.branding is None:
print >>sys.stderr, 'Use of Breakpad requires branding.'
print('Use of Breakpad requires branding.', file=sys.stderr)
return 1
# Map "target_os" passed from gn via the --platform parameter
# to the platform as known by breakpad.
@ -339,7 +341,7 @@ def Main(argv):
# Add Keystone if configured to do so.
if options.use_keystone:
if options.bundle_identifier is None:
print >>sys.stderr, 'Use of Keystone requires the bundle id.'
print('Use of Keystone requires the bundle id.', file=sys.stderr)
return 1
_AddKeystoneKeys(plist, options.bundle_identifier)
else:

Просмотреть файл

@ -16,6 +16,8 @@ The toolchain version can be overridden by setting MAC_TOOLCHAIN_REVISION with
the full revision, e.g. 9A235.
"""
from __future__ import print_function
import os
import platform
import shutil
@ -61,22 +63,22 @@ def _UseHermeticToolchain():
def RequestCipdAuthentication():
"""Requests that the user authenticate to access Xcode CIPD packages."""
print 'Access to Xcode CIPD package requires authentication.'
print '-----------------------------------------------------------------'
print
print 'You appear to be a Googler.'
print
print 'I\'m sorry for the hassle, but you may need to do a one-time manual'
print 'authentication. Please run:'
print
print ' cipd auth-login'
print
print 'and follow the instructions.'
print
print 'NOTE: Use your google.com credentials, not chromium.org.'
print
print '-----------------------------------------------------------------'
print
print('Access to Xcode CIPD package requires authentication.')
print('-----------------------------------------------------------------')
print()
print('You appear to be a Googler.')
print()
print('I\'m sorry for the hassle, but you may need to do a one-time manual')
print('authentication. Please run:')
print()
print(' cipd auth-login')
print()
print('and follow the instructions.')
print()
print('NOTE: Use your google.com credentials, not chromium.org.')
print()
print('-----------------------------------------------------------------')
print()
sys.stdout.flush()
@ -132,11 +134,11 @@ def main():
return 0
if not _UseHermeticToolchain():
print 'Skipping Mac toolchain installation for mac'
print('Skipping Mac toolchain installation for mac')
return 0
if not PlatformMeetsHermeticXcodeRequirements():
print 'OS version does not support toolchain.'
print('OS version does not support toolchain.')
return 0
toolchain_version = os.environ.get('MAC_TOOLCHAIN_REVISION',
@ -156,8 +158,8 @@ def main():
# TODO(crbug.com/797051): remove this once the old "hermetic" solution is no
# longer in use.
if os.path.exists(stamp_file):
print 'Detected old hermetic installation at %s. Deleting.' % (
toolchain_root)
print(
'Detected old hermetic installation at %s. Deleting.' % toolchain_root)
shutil.rmtree(toolchain_root)
success = InstallXcode(toolchain_version, installer_cmd, xcode_app_path)

Просмотреть файл

@ -8,6 +8,8 @@
Stored in in https://pantheon.corp.google.com/storage/browser/chrome-mac-sdk/.
"""
from __future__ import print_function
import argparse
import glob
import os
@ -92,7 +94,7 @@ def main():
try:
info = plistlib.readPlist(plist_file)
except:
print "Invalid Xcode dir."
print("Invalid Xcode dir.")
return 0
build_version = info['ProductBuildVersion']
@ -113,14 +115,14 @@ def main():
% (build_version, next_count - 1))
if raw_input().lower() not in set(['yes','y', 'ye']):
print "Skipping duplicate upload."
print("Skipping duplicate upload.")
return 0
os.chdir(parser_args.target_dir)
toolchain_file_name = "%s-%s-%s" % (fname, build_version, next_count)
toolchain_name = tempfile.mktemp(suffix='toolchain.tgz')
print "Creating %s (%s)." % (toolchain_file_name, toolchain_name)
print("Creating %s (%s)." % (toolchain_file_name, toolchain_name))
os.environ["COPYFILE_DISABLE"] = "1"
os.environ["GZ_OPT"] = "-8"
args = ['tar', '-cvzf', toolchain_name]
@ -133,12 +135,12 @@ def main():
args.extend(['.'])
subprocess.check_call(args)
print "Uploading %s toolchain." % toolchain_file_name
print("Uploading %s toolchain." % toolchain_file_name)
destination_path = '%s/%s.tgz' % (TOOLCHAIN_URL, toolchain_file_name)
subprocess.check_call(['gsutil.py', 'cp', '-n', toolchain_name,
destination_path])
print "Done with %s upload." % toolchain_file_name
print("Done with %s upload." % toolchain_file_name)
return 0
if __name__ == '__main__':

Просмотреть файл

@ -15,6 +15,8 @@ It performs the following steps:
4. Creates a new stamp file.
"""
from __future__ import print_function
import os
import optparse
import shutil
@ -41,11 +43,11 @@ def main(argv):
build_utils.CheckOptions(options, parser, ['protoc', 'proto_path'])
if not options.java_out_dir and not options.srcjar:
print 'One of --java-out-dir or --srcjar must be specified.'
print('One of --java-out-dir or --srcjar must be specified.')
return 1
if not options.nano and not options.protoc_javalite_plugin_dir:
print 'One of --nano or --protoc-javalite-plugin-dir must be specified.'
print('One of --nano or --protoc-javalite-plugin-dir must be specified.')
return 1
with build_utils.TempDir() as temp_dir:

Просмотреть файл

@ -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 subprocess
import sys
@ -12,7 +14,7 @@ import sys
if __name__ == '__main__':
if len(sys.argv) < 2:
print >> sys.stderr, "Usage: %s output_file command..." % (sys.argv[0])
print("Usage: %s output_file command..." % sys.argv[0], file=sys.stderr)
sys.exit(1)
with open(sys.argv[1], 'w') as fp:

4
rm.py
Просмотреть файл

@ -8,6 +8,8 @@
This module works much like the rm posix command.
"""
from __future__ import print_function
import argparse
import os
import sys
@ -25,7 +27,7 @@ def Main():
os.remove(f)
except OSError:
if not args.force:
print >>sys.stderr, "'%s' does not exist" % f
print("'%s' does not exist" % f, file=sys.stderr)
return 1
with open(args.stamp, 'w'):

Просмотреть файл

@ -15,6 +15,8 @@ Example usage:
--isolate-server touch-isolate.appspot.com
"""
from __future__ import print_function
import argparse
import os
import shutil
@ -39,7 +41,7 @@ def main():
script_dir = os.path.dirname(os.path.abspath(__file__))
tmp_dir = tempfile.mkdtemp(prefix='swarming_xcode')
try:
print 'Making isolate.'
print('Making isolate.')
shutil.copyfile(os.path.join(script_dir, 'swarming_xcode_install.py'),
os.path.join(tmp_dir, 'swarming_xcode_install.py'))
shutil.copyfile(os.path.join(script_dir, 'mac_toolchain.py'),
@ -52,7 +54,7 @@ def main():
]
isolate_hash = subprocess.check_output(cmd).split()[0]
print 'Running swarming_xcode_install.'
print('Running swarming_xcode_install.')
# TODO(crbug.com/765361): The dimensions below should be updated once
# swarming for iOS is fleshed out, likely removing xcode_version 9 and
# adding different dimensions.
@ -70,7 +72,7 @@ def main():
'python', 'swarming_xcode_install.py',
]
subprocess.check_call(cmd)
print 'All tasks completed.'
print('All tasks completed.')
finally:
shutil.rmtree(tmp_dir)

Просмотреть файл

@ -7,6 +7,8 @@
Script used to install Xcode on the swarming bots.
"""
from __future__ import print_function
import os
import shutil
import subprocess
@ -30,12 +32,12 @@ def main():
found_version = \
subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE).communicate()[0]
if VERSION in found_version:
print "Xcode %s already installed" % VERSION
print("Xcode %s already installed" % VERSION)
sys.exit(0)
# Confirm old dir is there first.
if not os.path.exists(REMOVE_DIR):
print "Failing early since %s isn't there." % REMOVE_DIR
print("Failing early since %s isn't there." % REMOVE_DIR)
sys.exit(1)
# Download Xcode.
@ -61,4 +63,3 @@ def main():
if __name__ == '__main__':
sys.exit(main())

Просмотреть файл

@ -39,6 +39,8 @@ Example usage:
--files-to-instrument=coverage_instrumentation_input.txt
"""
from __future__ import print_function
import argparse
import os
import subprocess
@ -124,7 +126,7 @@ def main():
# obj/base/base/file_path.o
index_dash_c = compile_command.index('-c')
except ValueError:
print '-c argument is not found in the compile command.'
print('-c argument is not found in the compile command.')
raise
if index_dash_c + 1 >= len(compile_command):

Просмотреть файл

@ -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 os
import re
import subprocess
@ -39,7 +41,7 @@ def Main(cmd_list):
_, err = libtoolout.communicate()
for line in err.splitlines():
if not IsBlacklistedLine(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:

Просмотреть файл

@ -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 os
import sys
@ -14,4 +16,4 @@ import sys
if __name__ == '__main__':
for f in sys.argv[1:]:
variable = os.path.splitext(os.path.basename(f))[0]
print '%s = %d' % (variable, os.path.getmtime(f))
print('%s = %d' % (variable, os.path.getmtime(f)))

Просмотреть файл

@ -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 array
import difflib
import distutils.dir_util
@ -205,7 +207,7 @@ def main(arch, outdir, dynamic_guid, tlb, h, dlldata, iid, proxy, idl, *flags):
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)
if popen.returncode != 0:
return popen.returncode
@ -215,18 +217,19 @@ def main(arch, outdir, dynamic_guid, tlb, h, dlldata, iid, proxy, idl, *flags):
# Now compare the output in tmp_dir to the copied-over outputs.
diff = filecmp.dircmp(tmp_dir, outdir)
if diff.diff_files:
print 'midl.exe output different from files in %s, see %s' \
% (outdir, tmp_dir)
print('midl.exe output different from files in %s, see %s' % (outdir,
tmp_dir))
for f in diff.diff_files:
if f.endswith('.tlb'): continue
fromfile = os.path.join(outdir, f)
tofile = os.path.join(tmp_dir, f)
print ''.join(difflib.unified_diff(open(fromfile, 'U').readlines(),
open(tofile, 'U').readlines(),
fromfile, tofile))
print(''.join(
difflib.unified_diff(
open(fromfile, 'U').readlines(),
open(tofile, 'U').readlines(), fromfile, tofile)))
delete_tmp_dir = False
print 'To rebaseline:'
print ' copy /y %s\* %s' % (tmp_dir, source)
print('To rebaseline:')
print(' copy /y %s\* %s' % (tmp_dir, source))
sys.exit(1)
return 0
finally:

Просмотреть файл

@ -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 re
import sys
@ -90,7 +92,7 @@ def _MeanAndStdDevFromList(values):
def PrintPages(page_list):
"""Prints list of pages to stdout in the format required by perf tests."""
print 'Pages: [%s]' % ','.join([_EscapePerfResult(p) for p in page_list])
print('Pages: [%s]' % ','.join([_EscapePerfResult(p) for p in page_list]))
def PrintPerfResult(measurement, trace, values, units,
@ -161,7 +163,7 @@ def PrintPerfResult(measurement, trace, values, units,
if sd:
output += '\nSd %s: %f%s' % (measurement, sd, units)
if print_to_stdout:
print output
print(output)
sys.stdout.flush()
return output

Просмотреть файл

@ -6,6 +6,8 @@
# Helper utility to combine GN-generated Visual Studio projects into
# a single meta-solution.
from __future__ import print_function
import os
import glob
import re