Commit 66e754dd authored by Raul Tambre's avatar Raul Tambre Committed by Commit Bot

tools: Use Python 3 style print statements [6/9]

Initial conversion performed using '2to3 -f print .'.
Imports added and duplicate parentheses removed manually.
Manually converted files, comments and inline code that 2to3 missed.
Afterwards ran "git cl format --python" and cherry-picked the formatting changes.

There are no intended behavioural changes.

Bug: 941669
Change-Id: I4a423a71375fd4d8cfc8283dd2703855781ece6b
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1818519
Commit-Queue: Nico Weber <thakis@chromium.org>
Reviewed-by: default avatarBrian White <bcwhite@chromium.org>
Reviewed-by: default avatarNico Weber <thakis@chromium.org>
Auto-Submit: Raul Tambre <raul@tambre.ee>
Cr-Commit-Position: refs/heads/master@{#699709}
parent fe8fa95b
...@@ -21,6 +21,8 @@ changed, a window will be prompted asking for user's consent. The old version ...@@ -21,6 +21,8 @@ changed, a window will be prompted asking for user's consent. The old version
will also be saved in a backup file. will also be saved in a backup file.
""" """
from __future__ import print_function
__author__ = 'evanm (Evan Martin)' __author__ = 'evanm (Evan Martin)'
from HTMLParser import HTMLParser from HTMLParser import HTMLParser
...@@ -438,7 +440,7 @@ def GrepForWebUIActions(path, actions): ...@@ -438,7 +440,7 @@ def GrepForWebUIActions(path, actions):
close_called = True close_called = True
parser.close() parser.close()
except Exception, e: except Exception, e:
print "Error encountered for path %s" % path print("Error encountered for path %s" % path)
raise e raise e
finally: finally:
if not close_called: if not close_called:
...@@ -771,8 +773,8 @@ def UpdateXml(original_xml): ...@@ -771,8 +773,8 @@ def UpdateXml(original_xml):
AddLiteralActions(actions) AddLiteralActions(actions)
# print "Scanned {0} number of files".format(number_of_files_total) # print("Scanned {0} number of files".format(number_of_files_total))
# print "Found {0} entries".format(len(actions)) # print("Found {0} entries".format(len(actions)))
AddAutomaticResetBannerActions(actions) AddAutomaticResetBannerActions(actions)
AddBookmarkManagerActions(actions) AddBookmarkManagerActions(actions)
......
...@@ -6,6 +6,8 @@ ...@@ -6,6 +6,8 @@
user-managed files are correct. user-managed files are correct.
""" """
from __future__ import print_function
import logging import logging
import os import os
import webbrowser import webbrowser
...@@ -39,7 +41,7 @@ def PromptUserToAcceptDiff(old_text, new_text, prompt): ...@@ -39,7 +41,7 @@ def PromptUserToAcceptDiff(old_text, new_text, prompt):
temp.write(html_diff) temp.write(html_diff)
temp.close() # Close the file so the browser process can access it. temp.close() # Close the file so the browser process can access it.
webbrowser.open('file://' + temp.name) webbrowser.open('file://' + temp.name)
print prompt print(prompt)
response = raw_input('(Y/n): ').strip().lower() response = raw_input('(Y/n): ').strip().lower()
finally: finally:
temp.close() # May be called on already closed file. temp.close() # May be called on already closed file.
......
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
from __future__ import print_function
import difflib import difflib
import logging import logging
import os import os
...@@ -85,7 +87,7 @@ def DoPresubmit(argv, original_filename, backup_filename, script_name, ...@@ -85,7 +87,7 @@ def DoPresubmit(argv, original_filename, backup_filename, script_name,
if diff: if diff:
for line in difflib.unified_diff(original_xml.splitlines(), for line in difflib.unified_diff(original_xml.splitlines(),
pretty.splitlines()): pretty.splitlines()):
print line print(line)
return 0 return 0
logging.info('Creating backup file: %s', backup_filename) logging.info('Creating backup file: %s', backup_filename)
......
...@@ -10,6 +10,8 @@ trials are entirely ignored by this script. ...@@ -10,6 +10,8 @@ trials are entirely ignored by this script.
""" """
from __future__ import print_function
import hashlib import hashlib
import logging import logging
import optparse import optparse
...@@ -315,8 +317,8 @@ def output_csv(unmapped_histograms, location_map): ...@@ -315,8 +317,8 @@ def output_csv(unmapped_histograms, location_map):
parts = location_map[histogram].split(':') parts = location_map[histogram].split(':')
assert len(parts) == 2 assert len(parts) == 2
(filename, line_number) = parts (filename, line_number) = parts
print '%s,%s,%s,%s' % (filename, line_number, histogram, print('%s,%s,%s,%s' % (filename, line_number, histogram,
hashHistogramName(histogram)) hashHistogramName(histogram)))
def output_log(unmapped_histograms, location_map, verbose): def output_log(unmapped_histograms, location_map, verbose):
......
...@@ -7,6 +7,8 @@ ...@@ -7,6 +7,8 @@
histograms. histograms.
""" """
from __future__ import print_function
import extract_histograms import extract_histograms
import os import os
import sys import sys
...@@ -48,9 +50,10 @@ def main(): ...@@ -48,9 +50,10 @@ def main():
if not obsolete: if not obsolete:
if owners: if owners:
print name, ' '.join(owners) print(name, ' '.join(owners))
else: else:
print name, 'NO_OWNER' print(name, 'NO_OWNER')
if __name__ == '__main__': if __name__ == '__main__':
main() main()
...@@ -5,6 +5,8 @@ ...@@ -5,6 +5,8 @@
"""Prints all histogram names.""" """Prints all histogram names."""
from __future__ import print_function
import os import os
import sys import sys
...@@ -22,8 +24,8 @@ def main(): ...@@ -22,8 +24,8 @@ def main():
raise Error("Error parsing inputs.") raise Error("Error parsing inputs.")
names = extract_histograms.ExtractNames(histograms) names = extract_histograms.ExtractNames(histograms)
for name in names: for name in names:
print name print(name)
if __name__ == '__main__': if __name__ == '__main__':
main() main()
...@@ -8,13 +8,15 @@ from the corresponding bad_message.h files. ...@@ -8,13 +8,15 @@ from the corresponding bad_message.h files.
If the file was pretty-printed, the updated version is pretty-printed too. If the file was pretty-printed, the updated version is pretty-printed too.
""" """
from __future__ import print_function
import sys import sys
from update_histogram_enum import UpdateHistogramEnum from update_histogram_enum import UpdateHistogramEnum
if __name__ == '__main__': if __name__ == '__main__':
if len(sys.argv) > 1: if len(sys.argv) > 1:
print >>sys.stderr, 'No arguments expected!' print('No arguments expected!', file=sys.stderr)
sys.stderr.write(__doc__) sys.stderr.write(__doc__)
sys.exit(1) sys.exit(1)
......
...@@ -8,6 +8,8 @@ ...@@ -8,6 +8,8 @@
If the file was pretty-printed, the updated version is pretty-printed too. If the file was pretty-printed, the updated version is pretty-printed too.
""" """
from __future__ import print_function
import logging import logging
import os import os
import re import re
...@@ -60,7 +62,7 @@ def ReadHistogramValues(filename): ...@@ -60,7 +62,7 @@ def ReadHistogramValues(filename):
if re.match(ENUM_END_MARKER, line): if re.match(ENUM_END_MARKER, line):
inside_enum = False inside_enum = False
else: else:
# Inside enum: generate new xml entry # Inside enum: generate new xml entry
m = re.match("^{ \"([\w]+)\", \{([\w]+)", line.strip()) m = re.match("^{ \"([\w]+)\", \{([\w]+)", line.strip())
if m: if m:
result.append((m.group(1), int(m.group(2)))) result.append((m.group(1), int(m.group(2))))
...@@ -86,8 +88,8 @@ def UpdateHistogramDefinitions(histogram_values, document): ...@@ -86,8 +88,8 @@ def UpdateHistogramDefinitions(histogram_values, document):
# Find ExtensionFunctions enum. # Find ExtensionFunctions enum.
for enum_node in document.getElementsByTagName('enum'): for enum_node in document.getElementsByTagName('enum'):
if enum_node.attributes['name'].value == ENUM_NAME: if enum_node.attributes['name'].value == ENUM_NAME:
extension_functions_enum_node = enum_node extension_functions_enum_node = enum_node
break break
else: else:
raise UserError('No policy enum node found') raise UserError('No policy enum node found')
...@@ -114,7 +116,7 @@ def Log(message): ...@@ -114,7 +116,7 @@ def Log(message):
def main(): def main():
if len(sys.argv) > 1: if len(sys.argv) > 1:
print >>sys.stderr, 'No arguments expected!' print('No arguments expected!', file=sys.stderr)
sys.stderr.write(__doc__) sys.stderr.write(__doc__)
sys.exit(1) sys.exit(1)
......
...@@ -9,6 +9,8 @@ extension_function_histogram_value.h. ...@@ -9,6 +9,8 @@ extension_function_histogram_value.h.
If the file was pretty-printed, the updated version is pretty-printed too. If the file was pretty-printed, the updated version is pretty-printed too.
""" """
from __future__ import print_function
import os import os
import sys import sys
...@@ -16,7 +18,7 @@ from update_histogram_enum import UpdateHistogramEnum ...@@ -16,7 +18,7 @@ from update_histogram_enum import UpdateHistogramEnum
if __name__ == '__main__': if __name__ == '__main__':
if len(sys.argv) > 1: if len(sys.argv) > 1:
print >>sys.stderr, 'No arguments expected!' print('No arguments expected!', file=sys.stderr)
sys.stderr.write(__doc__) sys.stderr.write(__doc__)
sys.exit(1) sys.exit(1)
......
...@@ -8,6 +8,8 @@ read from api_permission.h. ...@@ -8,6 +8,8 @@ read from api_permission.h.
If the file was pretty-printed, the updated version is pretty-printed too. If the file was pretty-printed, the updated version is pretty-printed too.
""" """
from __future__ import print_function
import os import os
import sys import sys
...@@ -15,7 +17,7 @@ from update_histogram_enum import UpdateHistogramEnum ...@@ -15,7 +17,7 @@ from update_histogram_enum import UpdateHistogramEnum
if __name__ == '__main__': if __name__ == '__main__':
if len(sys.argv) > 1: if len(sys.argv) > 1:
print >>sys.stderr, 'No arguments expected!' print('No arguments expected!', file=sys.stderr)
sys.stderr.write(__doc__) sys.stderr.write(__doc__)
sys.exit(1) sys.exit(1)
......
...@@ -9,6 +9,8 @@ values read from feature_policy.mojom. ...@@ -9,6 +9,8 @@ values read from feature_policy.mojom.
If the file was pretty-printed, the updated version is pretty-printed too. If the file was pretty-printed, the updated version is pretty-printed too.
""" """
from __future__ import print_function
import os import os
import sys import sys
...@@ -16,7 +18,7 @@ from update_histogram_enum import UpdateHistogramEnum ...@@ -16,7 +18,7 @@ from update_histogram_enum import UpdateHistogramEnum
if __name__ == '__main__': if __name__ == '__main__':
if len(sys.argv) > 1: if len(sys.argv) > 1:
print >>sys.stderr, 'No arguments expected!' print('No arguments expected!', file=sys.stderr)
sys.stderr.write(__doc__) sys.stderr.write(__doc__)
sys.exit(1) sys.exit(1)
......
...@@ -9,6 +9,8 @@ ...@@ -9,6 +9,8 @@
If the file was pretty-printed, the updated version is pretty-printed too. If the file was pretty-printed, the updated version is pretty-printed too.
""" """
from __future__ import print_function
import os.path import os.path
import re import re
import sys import sys
...@@ -40,7 +42,7 @@ def ReadGpuDriverBugEntries(filename): ...@@ -40,7 +42,7 @@ def ReadGpuDriverBugEntries(filename):
def main(): def main():
if len(sys.argv) > 1: if len(sys.argv) > 1:
print >>sys.stderr, 'No arguments expected!' print('No arguments expected!', file=sys.stderr)
sys.stderr.write(__doc__) sys.stderr.write(__doc__)
sys.exit(1) sys.exit(1)
......
...@@ -9,6 +9,8 @@ ...@@ -9,6 +9,8 @@
If the file was pretty-printed, the updated version is pretty-printed too. If the file was pretty-printed, the updated version is pretty-printed too.
""" """
from __future__ import print_function
import os.path import os.path
import re import re
import sys import sys
...@@ -42,7 +44,7 @@ def ReadNetErrorCodes(filename, error_regex): ...@@ -42,7 +44,7 @@ def ReadNetErrorCodes(filename, error_regex):
# CERT_END is not a real NET_ERROR and does not have a stable value. # CERT_END is not a real NET_ERROR and does not have a stable value.
# Don't include it. # Don't include it.
if name == 'CERT_END': if name == 'CERT_END':
continue continue
errors[code] = name errors[code] = name
...@@ -51,7 +53,7 @@ def ReadNetErrorCodes(filename, error_regex): ...@@ -51,7 +53,7 @@ def ReadNetErrorCodes(filename, error_regex):
def main(): def main():
if len(sys.argv) > 1: if len(sys.argv) > 1:
print >>sys.stderr, 'No arguments expected!' print('No arguments expected!', file=sys.stderr)
sys.stderr.write(__doc__) sys.stderr.write(__doc__)
sys.exit(1) sys.exit(1)
......
...@@ -9,6 +9,8 @@ ...@@ -9,6 +9,8 @@
If the file was pretty-printed, the updated version is pretty-printed too. If the file was pretty-printed, the updated version is pretty-printed too.
""" """
from __future__ import print_function
import json import json
import os.path import os.path
import sys import sys
...@@ -22,7 +24,7 @@ NET_ROOT_CERTS_PATH = 'net/data/ssl/root_stores/root_stores.json' ...@@ -22,7 +24,7 @@ NET_ROOT_CERTS_PATH = 'net/data/ssl/root_stores/root_stores.json'
def main(): def main():
if len(sys.argv) > 1: if len(sys.argv) > 1:
print >>sys.stderr, 'No arguments expected!' print('No arguments expected!', file=sys.stderr)
sys.stderr.write(__doc__) sys.stderr.write(__doc__)
sys.exit(1) sys.exit(1)
......
...@@ -8,6 +8,8 @@ definitions read from policy_templates.json. ...@@ -8,6 +8,8 @@ definitions read from policy_templates.json.
If the file was pretty-printed, the updated version is pretty-printed too. If the file was pretty-printed, the updated version is pretty-printed too.
""" """
from __future__ import print_function
import os import os
import re import re
import sys import sys
...@@ -51,8 +53,8 @@ def UpdatePoliciesHistogramDefinitions(policy_templates, doc): ...@@ -51,8 +53,8 @@ def UpdatePoliciesHistogramDefinitions(policy_templates, doc):
# Find EnterprisePolicies enum. # Find EnterprisePolicies enum.
for enum_node in doc.getElementsByTagName('enum'): for enum_node in doc.getElementsByTagName('enum'):
if enum_node.attributes['name'].value == POLICIES_ENUM_NAME: if enum_node.attributes['name'].value == POLICIES_ENUM_NAME:
policy_enum_node = enum_node policy_enum_node = enum_node
break break
else: else:
raise UserError('No policy enum node found') raise UserError('No policy enum node found')
...@@ -89,8 +91,8 @@ def UpdateAtomicGroupsHistogramDefinitions(policy_templates, doc): ...@@ -89,8 +91,8 @@ def UpdateAtomicGroupsHistogramDefinitions(policy_templates, doc):
# Find EnterprisePolicies enum. # Find EnterprisePolicies enum.
for enum_node in doc.getElementsByTagName('enum'): for enum_node in doc.getElementsByTagName('enum'):
if enum_node.attributes['name'].value == POLICY_ATOMIC_GROUPS_ENUM_NAME: if enum_node.attributes['name'].value == POLICY_ATOMIC_GROUPS_ENUM_NAME:
atomic_group_enum_node = enum_node atomic_group_enum_node = enum_node
break break
else: else:
raise UserError('No policy atomic group enum node found') raise UserError('No policy atomic group enum node found')
...@@ -115,7 +117,7 @@ def UpdateAtomicGroupsHistogramDefinitions(policy_templates, doc): ...@@ -115,7 +117,7 @@ def UpdateAtomicGroupsHistogramDefinitions(policy_templates, doc):
def main(): def main():
if len(sys.argv) > 1: if len(sys.argv) > 1:
print >>sys.stderr, 'No arguments expected!' print('No arguments expected!', file=sys.stderr)
sys.stderr.write(__doc__) sys.stderr.write(__doc__)
sys.exit(1) sys.exit(1)
...@@ -140,5 +142,5 @@ if __name__ == '__main__': ...@@ -140,5 +142,5 @@ if __name__ == '__main__':
try: try:
main() main()
except UserError as e: except UserError as e:
print >>sys.stderr, e.message print(e.message, file=sys.stderr)
sys.exit(1) sys.exit(1)
...@@ -9,6 +9,8 @@ snippet to put in uma.py of Chromium Dashboard. Make sure that you review the ...@@ -9,6 +9,8 @@ snippet to put in uma.py of Chromium Dashboard. Make sure that you review the
output for correctness. output for correctness.
""" """
from __future__ import print_function
import optparse import optparse
import os import os
import sys import sys
...@@ -20,7 +22,7 @@ from update_histogram_enum import UpdateHistogramEnum ...@@ -20,7 +22,7 @@ from update_histogram_enum import UpdateHistogramEnum
def PrintEnumForDashboard(enum_dict): def PrintEnumForDashboard(enum_dict):
"""Prints enum_items formatted for use in uma.py of Chromium dashboard.""" """Prints enum_items formatted for use in uma.py of Chromium dashboard."""
for key in sorted(enum_dict.iterkeys()): for key in sorted(enum_dict.iterkeys()):
print ' %d: \'%s\',' % (key, enum_dict[key]) print(' %d: \'%s\',' % (key, enum_dict[key]))
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -16,6 +16,8 @@ tail -f perry.log ...@@ -16,6 +16,8 @@ tail -f perry.log
You might want to run it in `screen` as it'll take a while. You might want to run it in `screen` as it'll take a while.
""" """
from __future__ import print_function
import argparse import argparse
import os import os
import multiprocessing import multiprocessing
...@@ -69,7 +71,7 @@ def _CheckForFailure(data): ...@@ -69,7 +71,7 @@ def _CheckForFailure(data):
def _PrintStatus(i, total, failed): def _PrintStatus(i, total, failed):
status = '%d of %d tested (%d failures)' % (i+1, total, failed) status = '%d of %d tested (%d failures)' % (i+1, total, failed)
print '\r%s%s' % (status, '\x1B[K'), print('\r%s%s' % (status, '\x1B[K'), end=' ')
sys.stdout.flush() sys.stdout.flush()
...@@ -77,7 +79,7 @@ def main(): ...@@ -77,7 +79,7 @@ def main():
parser = argparse.ArgumentParser(description="Find failing pairs of tests.") parser = argparse.ArgumentParser(description="Find failing pairs of tests.")
parser.add_argument('binary', help='Path to gtest binary or wrapper script.') parser.add_argument('binary', help='Path to gtest binary or wrapper script.')
args = parser.parse_args() args = parser.parse_args()
print 'Getting test list...' print('Getting test list...')
all_tests = _GetTestList(args.binary) all_tests = _GetTestList(args.binary)
permuted = [(args.binary, x, y) for x in all_tests for y in all_tests] permuted = [(args.binary, x, y) for x in all_tests for y in all_tests]
...@@ -87,8 +89,8 @@ def main(): ...@@ -87,8 +89,8 @@ def main():
for i, result in enumerate(pool.imap_unordered( for i, result in enumerate(pool.imap_unordered(
_CheckForFailure, permuted, 1)): _CheckForFailure, permuted, 1)):
if result: if result:
print '\n--gtest_filter=%s:%s failed\n\n%s\n\n' % ( print('\n--gtest_filter=%s:%s failed\n\n%s\n\n' % (result[0], result[1],
result[0], result[1], result[2]) result[2]))
failed.append(result) failed.append(result)
_PrintStatus(i, total_count, len(failed)) _PrintStatus(i, total_count, len(failed))
...@@ -96,9 +98,9 @@ def main(): ...@@ -96,9 +98,9 @@ def main():
pool.join() pool.join()
if failed: if failed:
print 'Failed pairs:' print('Failed pairs:')
for f in failed: for f in failed:
print f[0], f[1] print(f[0], f[1])
return 0 return 0
......
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
from __future__ import print_function
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from datetime import date from datetime import date
import os.path as path import os.path as path
...@@ -84,8 +86,8 @@ def main(created_by, html_files): ...@@ -84,8 +86,8 @@ def main(created_by, html_files):
if targets: if targets:
current_year = date.today().year current_year = date.today().year
print _COMPILED_RESOURCES_TEMPLATE % (current_year, created_by, print(_COMPILED_RESOURCES_TEMPLATE % (current_year, created_by,
_COMPILE_JS, targets) _COMPILE_JS, targets))
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
from __future__ import print_function
from datetime import date from datetime import date
import json import json
import os.path as path import os.path as path
...@@ -76,8 +78,8 @@ def main(created_by, input_files): ...@@ -76,8 +78,8 @@ def main(created_by, input_files):
if targets: if targets:
current_year = date.today().year current_year = date.today().year
print _COMPILED_RESOURCES_TEMPLATE % (current_year, created_by, print(_COMPILED_RESOURCES_TEMPLATE % (current_year, created_by,
_COMPILE_JS, targets) _COMPILE_JS, targets))
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
from __future__ import print_function
import argparse import argparse
import sys import sys
import xml.sax import xml.sax
...@@ -35,7 +37,7 @@ def main(argv): ...@@ -35,7 +37,7 @@ def main(argv):
xml_handler = PathsExtractor(args.polymer_version) xml_handler = PathsExtractor(args.polymer_version)
xml.sax.parse(args.input, xml_handler) xml.sax.parse(args.input, xml_handler)
print '\n'.join(sorted(xml_handler.paths)) print('\n'.join(sorted(xml_handler.paths)))
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
# found in the LICENSE file. # found in the LICENSE file.
from __future__ import with_statement from __future__ import with_statement
from __future__ import print_function
import argparse import argparse
import os import os
import string import string
...@@ -100,11 +102,15 @@ def main(argv): ...@@ -100,11 +102,15 @@ def main(argv):
'name': PathToGritId(polymer_version, path), 'name': PathToGritId(polymer_version, path),
'path': path}) 'path': path})
print FILE_TEMPLATE % { print(FILE_TEMPLATE % {
'contents': '\n'.join(lines), 'contents':
'web_animations': '' if polymer_version == '3' else '\n'.join(lines),
DEFINITION_TEMPLATE_WEB_ANIMATIONS, 'web_animations':
'version' : polymer_version } '' if polymer_version == '3' else DEFINITION_TEMPLATE_WEB_ANIMATIONS,
'version':
polymer_version
})
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(main(sys.argv[1:])) sys.exit(main(sys.argv[1:]))
...@@ -16,6 +16,8 @@ ...@@ -16,6 +16,8 @@
# In future it might be possible to extend this to other kinds of differences, # In future it might be possible to extend this to other kinds of differences,
# e.g. page load times. # e.g. page load times.
from __future__ import print_function
import argparse import argparse
from argparse import RawTextHelpFormatter from argparse import RawTextHelpFormatter
from contextlib import closing from contextlib import closing
...@@ -96,15 +98,15 @@ def SetupPathsAndOut(): ...@@ -96,15 +98,15 @@ def SetupPathsAndOut():
def CheckPrerequisites(): def CheckPrerequisites():
if not find_executable("wget"): if not find_executable("wget"):
print "wget not found! Install wget and re-run this." print("wget not found! Install wget and re-run this.")
return False return False
if not os.path.exists(image_diff): if not os.path.exists(image_diff):
print "image_diff not found (%s)!" % image_diff print("image_diff not found (%s)!" % image_diff)
print "Build the image_diff target and re-run this." print("Build the image_diff target and re-run this.")
return False return False
if not os.path.exists(content_shell): if not os.path.exists(content_shell):
print "Content shell not found (%s)!" % content_shell print("Content shell not found (%s)!" % content_shell)
print "Build Release/content_shell and re-run this." print("Build Release/content_shell and re-run this.")
return False return False
return True return True
...@@ -118,7 +120,7 @@ def PickSampleUrls(): ...@@ -118,7 +120,7 @@ def PickSampleUrls():
# TODO(johnme): Should probably update this when it gets too stale... # TODO(johnme): Should probably update this when it gets too stale...
csv_path = os.path.join(data_dir, "top-1m.csv") csv_path = os.path.join(data_dir, "top-1m.csv")
if not os.path.exists(csv_path): if not os.path.exists(csv_path):
print "Downloading list of top 1,000,000 sites from Alexa..." print("Downloading list of top 1,000,000 sites from Alexa...")
csv_url = "http://s3.amazonaws.com/alexa-static/top-1m.csv.zip" csv_url = "http://s3.amazonaws.com/alexa-static/top-1m.csv.zip"
with closing(urlopen(csv_url)) as stream: with closing(urlopen(csv_url)) as stream:
ZipFile(StringIO(stream.read())).extract("top-1m.csv", data_dir) ZipFile(StringIO(stream.read())).extract("top-1m.csv", data_dir)
...@@ -136,10 +138,10 @@ def PickSampleUrls(): ...@@ -136,10 +138,10 @@ def PickSampleUrls():
urls_path = os.path.join(data_dir, "%06d_urls.txt" % num_sites) urls_path = os.path.join(data_dir, "%06d_urls.txt" % num_sites)
if not os.path.exists(urls_path): if not os.path.exists(urls_path):
if action == 'compare': if action == 'compare':
print ("Error: you must run 'before %d' and 'after %d' before " print("Error: you must run 'before %d' and 'after %d' before "
"running 'compare %d'") % (num_sites, num_sites, num_sites) "running 'compare %d'" % (num_sites, num_sites, num_sites))
return False return False
print "Picking %d sample urls..." % num_sites print("Picking %d sample urls..." % num_sites)
# TODO(johnme): For now this just gets the top num_sites entries. In future # TODO(johnme): For now this just gets the top num_sites entries. In future
# this should pick a weighted random sample. For example, it could fit a # this should pick a weighted random sample. For example, it could fit a
...@@ -177,7 +179,7 @@ def PrintElapsedTime(elapsed, detail=""): ...@@ -177,7 +179,7 @@ def PrintElapsedTime(elapsed, detail=""):
elapsed = round(elapsed * 10) / 10.0 elapsed = round(elapsed * 10) / 10.0
m = elapsed / 60 m = elapsed / 60
s = elapsed % 60 s = elapsed % 60
print "Took %dm%.1fs" % (m, s), detail print("Took %dm%.1fs" % (m, s), detail)
def DownloadStaticCopyTask(url): def DownloadStaticCopyTask(url):
...@@ -216,10 +218,10 @@ def DownloadStaticCopyTask(url): ...@@ -216,10 +218,10 @@ def DownloadStaticCopyTask(url):
success = False success = False
else: else:
with print_lock: with print_lock:
print "Downloaded:", url print("Downloaded:", url)
if not success: if not success:
with print_lock: with print_lock:
print "Failed to download:", url print("Failed to download:", url)
return False return False
return True return True
...@@ -235,7 +237,7 @@ def DownloadStaticCopies(): ...@@ -235,7 +237,7 @@ def DownloadStaticCopies():
new_urls.append(url) new_urls.append(url)
if new_urls: if new_urls:
print "Downloading static copies of %d sites..." % len(new_urls) print("Downloading static copies of %d sites..." % len(new_urls))
start_time = time.time() start_time = time.time()
results = multiprocessing.Pool(20).map(DownloadStaticCopyTask, new_urls) results = multiprocessing.Pool(20).map(DownloadStaticCopyTask, new_urls)
...@@ -303,7 +305,7 @@ def RunDrtTask(url): ...@@ -303,7 +305,7 @@ def RunDrtTask(url):
def RunDrt(): def RunDrt():
print "Taking screenshots of %d pages..." % len(urls) print("Taking screenshots of %d pages..." % len(urls))
start_time = time.time() start_time = time.time()
results = multiprocessing.Pool().map(RunDrtTask, urls, 1) results = multiprocessing.Pool().map(RunDrtTask, urls, 1)
...@@ -355,7 +357,7 @@ def CompareResultsTask(url): ...@@ -355,7 +357,7 @@ def CompareResultsTask(url):
def CompareResults(): def CompareResults():
print "Running image_diff on %d pages..." % len(urls) print("Running image_diff on %d pages..." % len(urls))
start_time = time.time() start_time = time.time()
results = multiprocessing.Pool().map(CompareResultsTask, urls) results = multiprocessing.Pool().map(CompareResultsTask, urls)
......
...@@ -11,6 +11,8 @@ run. ...@@ -11,6 +11,8 @@ run.
Usage: remove_duplicate_includes.py --dry-run components/foo components/bar Usage: remove_duplicate_includes.py --dry-run components/foo components/bar
""" """
from __future__ import print_function
import argparse import argparse
import collections import collections
import logging import logging
...@@ -45,8 +47,8 @@ def FindIncludeSet(input_lines, h_path_to_include_set, cc_file_name): ...@@ -45,8 +47,8 @@ def FindIncludeSet(input_lines, h_path_to_include_set, cc_file_name):
if match: if match:
h_file_path = os.path.join(os.getcwd(), match.group(2)) h_file_path = os.path.join(os.getcwd(), match.group(2))
if h_file_path not in h_path_to_include_set: if h_file_path not in h_path_to_include_set:
print 'First include did not match to a known .h file, skipping ' + \ print('First include did not match to a known .h file, skipping ' + \
cc_file_name + ', line: ' + match.group(1) cc_file_name + ', line: ' + match.group(1))
return None return None
return h_path_to_include_set[h_file_path] return h_path_to_include_set[h_file_path]
...@@ -64,10 +66,10 @@ def WithoutDuplicates(input_lines, include_set, cc_file_name): ...@@ -64,10 +66,10 @@ def WithoutDuplicates(input_lines, include_set, cc_file_name):
for line in input_lines: for line in input_lines:
match = INCLUDE_REGEX.search(line) match = INCLUDE_REGEX.search(line)
if match and match.group(2) in include_set: if match and match.group(2) in include_set:
print 'Removed ' + match.group(1) + ' from ' + cc_file_name print('Removed ' + match.group(1) + ' from ' + cc_file_name)
lastLineWasOmitted = True lastLineWasOmitted = True
elif lastCopiedLineWasEmpty and lastLineWasOmitted and IsEmpty(line): elif lastCopiedLineWasEmpty and lastLineWasOmitted and IsEmpty(line):
print 'Removed empty line from ' + cc_file_name print('Removed empty line from ' + cc_file_name)
lastLineWasOmitted = True lastLineWasOmitted = True
else: else:
lastCopiedLineWasEmpty = IsEmpty(line) lastCopiedLineWasEmpty = IsEmpty(line)
......
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
from __future__ import print_function
import argparse import argparse
import collections import collections
import logging import logging
...@@ -125,7 +127,7 @@ def _GenerateCLDescriptionCommand(webgl_current, webgl_new, bugs): ...@@ -125,7 +127,7 @@ def _GenerateCLDescriptionCommand(webgl_current, webgl_new, bugs):
changelog_url = GetChangeLogURL(webgl_current.git_repo_url, changelog_url = GetChangeLogURL(webgl_current.git_repo_url,
change_str) change_str)
if webgl_current.git_commit == webgl_new.git_commit: if webgl_current.git_commit == webgl_new.git_commit:
print 'WARNING: WebGL repository is unchanged; proceeding with no-op roll' print('WARNING: WebGL repository is unchanged; proceeding with no-op roll')
def GetExtraTrybotString(): def GetExtraTrybotString():
s = '' s = ''
...@@ -311,11 +313,11 @@ class AutoRoller(object): ...@@ -311,11 +313,11 @@ class AutoRoller(object):
self._RunCommand(base_try_cmd) self._RunCommand(base_try_cmd)
cl_info = self._GetCLInfo() cl_info = self._GetCLInfo()
print 'Issue: %d URL: %s' % (cl_info.issue, cl_info.url) print('Issue: %d URL: %s' % (cl_info.issue, cl_info.url))
# Checkout master again. # Checkout master again.
self._RunCommand(['git', 'checkout', 'master']) self._RunCommand(['git', 'checkout', 'master'])
print 'Roll branch left as ' + ROLL_BRANCH_NAME print('Roll branch left as ' + ROLL_BRANCH_NAME)
return 0 return 0
def _UpdateDep(self, deps_filename, dep_relative_to_src, commit_info): def _UpdateDep(self, deps_filename, dep_relative_to_src, commit_info):
...@@ -338,9 +340,9 @@ class AutoRoller(object): ...@@ -338,9 +340,9 @@ class AutoRoller(object):
# happens all the time, update an autogenerated text file in this # happens all the time, update an autogenerated text file in this
# directory. # directory.
with open(txt_filename, 'w') as fh: with open(txt_filename, 'w') as fh:
print >> fh, '# AUTOGENERATED FILE - DO NOT EDIT' print('# AUTOGENERATED FILE - DO NOT EDIT', file=fh)
print >> fh, '# SEE roll_webgl_conformance.py' print('# SEE roll_webgl_conformance.py', file=fh)
print >> fh, 'Current webgl revision %s' % commit_info.git_commit print('Current webgl revision %s' % commit_info.git_commit, file=fh)
def _DeleteRollBranch(self): def _DeleteRollBranch(self):
self._RunCommand(['git', 'checkout', 'master']) self._RunCommand(['git', 'checkout', 'master'])
...@@ -373,7 +375,7 @@ class AutoRoller(object): ...@@ -373,7 +375,7 @@ class AutoRoller(object):
if active_branch == ROLL_BRANCH_NAME: if active_branch == ROLL_BRANCH_NAME:
active_branch = 'master' active_branch = 'master'
if ROLL_BRANCH_NAME in branches: if ROLL_BRANCH_NAME in branches:
print 'Aborting pending roll.' print('Aborting pending roll.')
self._RunCommand(['git', 'checkout', ROLL_BRANCH_NAME]) self._RunCommand(['git', 'checkout', ROLL_BRANCH_NAME])
# Ignore an error here in case an issue wasn't created for some reason. # Ignore an error here in case an issue wasn't created for some reason.
self._RunCommand(['git', 'cl', 'set_close'], ignore_exit_code=True) self._RunCommand(['git', 'cl', 'set_close'], ignore_exit_code=True)
......
...@@ -20,6 +20,8 @@ results/*` to find the tests that failed or otherwise process the log files. ...@@ -20,6 +20,8 @@ results/*` to find the tests that failed or otherwise process the log files.
See //docs/workflow/debugging-with-swarming.md for more details. See //docs/workflow/debugging-with-swarming.md for more details.
""" """
from __future__ import print_function
import argparse import argparse
import multiprocessing import multiprocessing
import os import os
...@@ -178,10 +180,12 @@ def main(): ...@@ -178,10 +180,12 @@ def main():
subprocess.check_call( subprocess.check_call(
['tools/mb/mb.py', 'isolate', '//' + args.out_dir, args.target_name]) ['tools/mb/mb.py', 'isolate', '//' + args.out_dir, args.target_name])
print 'If you get authentication errors, follow:' print('If you get authentication errors, follow:')
print ' https://www.chromium.org/developers/testing/isolated-testing/for-swes#TOC-Login-on-the-services' print(
' https://www.chromium.org/developers/testing/isolated-testing/for-swes#TOC-Login-on-the-services'
)
print 'Uploading to isolate server, this can take a while...' print('Uploading to isolate server, this can take a while...')
archive_output = subprocess.check_output( archive_output = subprocess.check_output(
['tools/swarming_client/isolate.py', 'archive', ['tools/swarming_client/isolate.py', 'archive',
'-I', 'https://isolateserver.appspot.com', '-I', 'https://isolateserver.appspot.com',
...@@ -194,7 +198,7 @@ def main(): ...@@ -194,7 +198,7 @@ def main():
os.makedirs(args.results) os.makedirs(args.results)
try: try:
print 'Triggering %d tasks...' % args.copies print('Triggering %d tasks...' % args.copies)
pool = multiprocessing.Pool() pool = multiprocessing.Pool()
spawn_args = map(lambda i: (i, args, isolated_hash), range(args.copies)) spawn_args = map(lambda i: (i, args, isolated_hash), range(args.copies))
spawn_results = pool.imap_unordered(_Spawn, spawn_args) spawn_results = pool.imap_unordered(_Spawn, spawn_args)
...@@ -207,13 +211,16 @@ def main(): ...@@ -207,13 +211,16 @@ def main():
errors = sum(1 for x in exit_codes if x == INTERNAL_ERROR_EXIT_CODE) errors = sum(1 for x in exit_codes if x == INTERNAL_ERROR_EXIT_CODE)
failures = len(exit_codes) - successes - errors failures = len(exit_codes) - successes - errors
clear_to_eol = '\033[K' clear_to_eol = '\033[K'
print('\r[%d/%d] collected: ' print(
'%d successes, %d failures, %d bot errors...%s' % (len(exit_codes), '\r[%d/%d] collected: '
args.copies, successes, failures, errors, clear_to_eol)), '%d successes, %d failures, %d bot errors...%s' %
(len(exit_codes), args.copies, successes, failures, errors,
clear_to_eol),
end=' ')
sys.stdout.flush() sys.stdout.flush()
print print()
print 'Results logs collected into', os.path.abspath(args.results) + '.' print('Results logs collected into', os.path.abspath(args.results) + '.')
finally: finally:
pool.close() pool.close()
pool.join() pool.join()
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment