Commit 61c72651 authored by Tom McKee's avatar Tom McKee Committed by LUCI CQ

Harden _PresubmitResult against varying string types

When presubmit checks fail, we want to print the error message from the
underlying check/tool. We use _PresubmitResult objects to collect these
diagnostics and output them to the console and json files.

This change ensures that the string values passed to the
_PresubmitResult constructor will be converted, as needed, to 'str'
instances. This way, we will avoid encoding errors and make sure to
print the actual messages instead of repr(message).

SHERIFFS: this patch breaks backwards compatibility of presubmit error
handling but we don't expect issues in downstream projects. Please
revert if downstream presubmit checks start failing spuriously.

Bug: 1225052
Change-Id: If7f5c99cb5d730c1bfbd6d108b912f77b5f2455c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/3037262
Commit-Queue: Tom McKee <tommckee@chromium.org>
Reviewed-by: 's avatarDirk Pranke <dpranke@google.com>
parent 1c3175be
...@@ -316,7 +316,24 @@ class _PresubmitResult(object): ...@@ -316,7 +316,24 @@ class _PresubmitResult(object):
""" """
self._message = message self._message = message
self._items = items or [] self._items = items or []
self._long_text = long_text.rstrip() self._long_text = _PresubmitResult._ensure_str(long_text.rstrip())
@staticmethod
def _ensure_str(val):
"""
val: A "stringish" value. Can be any of str, unicode or bytes.
returns: A str after applying encoding/decoding as needed.
Assumes/uses UTF-8 for relevant inputs/outputs.
We'd prefer to use six.ensure_str but our copy of six is old :(
"""
if isinstance(val, str):
return val
if six.PY2 and isinstance(val, unicode):
return val.encode()
elif six.PY3 and isinstance(val, bytes):
return val.decode()
raise ValueError("Unknown string type %s" % type(val))
def handle(self): def handle(self):
sys.stdout.write(self._message) sys.stdout.write(self._message)
...@@ -331,7 +348,7 @@ class _PresubmitResult(object): ...@@ -331,7 +348,7 @@ class _PresubmitResult(object):
if self._long_text: if self._long_text:
sys.stdout.write('\n***************\n') sys.stdout.write('\n***************\n')
# Write separately in case it's unicode. # Write separately in case it's unicode.
sys.stdout.write(str(self._long_text)) sys.stdout.write(self._long_text)
sys.stdout.write('\n***************\n') sys.stdout.write('\n***************\n')
def json_format(self): def json_format(self):
......
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