From 8b3bc259a0e075b5fe351422f6c9c0ec7d0ed5e6 Mon Sep 17 00:00:00 2001 From: Josip Sokcevic Date: Fri, 4 Jun 2021 18:44:11 +0000 Subject: [PATCH] Fix gclient_utils.FileRead() behavior for both 2 and 3. We always want gclient_utils.FileRead() to return a text string these days, but the existing code didn't work right for Python2 if you called it explicitly with mode='r'. R=ehmaldonado@chromium.org Bug: 1210746 Change-Id: If540746f31308b671f9101334b5cd9848a7e9257 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2930626 Reviewed-by: Josip Sokcevic Reviewed-by: Edward Lesmes Commit-Queue: Josip Sokcevic --- gclient_utils.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/gclient_utils.py b/gclient_utils.py index fb6770870..4b858ceee 100644 --- a/gclient_utils.py +++ b/gclient_utils.py @@ -171,14 +171,12 @@ def AskForData(message): def FileRead(filename, mode='rbU'): - # Always decodes output to a Unicode string. - # On Python 3 newlines are converted to '\n' by default and 'U' is deprecated. - if mode == 'rbU' and sys.version_info.major == 3: - mode = 'rb' - with open(filename, mode=mode) as f: + # mode is ignored now; we always return unicode strings. + with open(filename, mode='rb') as f: s = f.read() - if isinstance(s, bytes): - return s.decode('utf-8', 'replace') + try: + return s.decode('utf-8', 'replace') + except (UnicodeDecodeError, AttributeError): return s