Skip to content

Commit 6d488f1

Browse files
author
bors-servo
authored
Auto merge of servo#24435 - marmeladema:issue-23607/compat, r=jdm
Issue 23607: first pass of changes for compatibility with Python3 As much as i want to migrate entirely to Python3 (see servo#23607), it will require some time as changes in web-platform-tests are significant and rely on upstream fixes to be merged and synced downstream. In the meantime, lets improve compatibility with Python3 so that later, migration will be less painful. Build system is definitely not ready yet for Python3, but its a step in the right direction. --- <!-- Thank you for contributing to Servo! Please replace each `[ ]` by `[X]` when the step is complete, and replace `___` with appropriate data: --> - [x ] `./mach build -d` does not report any errors - [ x] `./mach test-tidy` does not report any errors <!-- Also, please make sure that "Allow edits from maintainers" checkbox is checked, so that we can help you if you get stuck somewhere along the way.--> <!-- Pull requests that do not address these steps are welcome, but they will require additional verification as part of the review process. -->
2 parents bcd8c5e + 2b3f6a2 commit 6d488f1

13 files changed

+70
-56
lines changed

etc/ci/clean_build_artifacts.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ set -o nounset
99
set -o pipefail
1010

1111
rm -rf target/
12+
rm -rf python/_virtualenv/

python/requirements.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,7 @@ boto3 == 1.4.4
3232
# https://github.com/servo/servo/pull/18942
3333
certifi
3434

35+
# For Python3 compatibility
36+
six
37+
3538
-e python/tidy

python/servo/bootstrap.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import platform
1212
import shutil
1313
import subprocess
14-
import urllib
14+
import six.moves.urllib as urllib
1515
from subprocess import PIPE
1616
from zipfile import BadZipfile
1717

@@ -293,7 +293,7 @@ def check_cmake(version):
293293

294294
def prepare_file(zip_path, full_spec):
295295
if not os.path.isfile(zip_path):
296-
zip_url = "{}{}.zip".format(deps_url, urllib.quote(full_spec))
296+
zip_url = "{}{}.zip".format(deps_url, urllib.parse.quote(full_spec))
297297
download_file(full_spec, zip_url, zip_path)
298298

299299
print("Extracting {}...".format(full_spec), end='')

python/servo/bootstrap_commands.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
import subprocess
1919
import sys
2020
import traceback
21-
import urllib2
21+
import six.moves.urllib as urllib
2222
import glob
2323

2424
from mach.decorators import (
@@ -220,7 +220,7 @@ def bootstrap_hsts_preload(self, force=False):
220220

221221
try:
222222
content_base64 = download_bytes("Chromium HSTS preload list", chromium_hsts_url)
223-
except urllib2.URLError:
223+
except urllib.error.URLError:
224224
print("Unable to download chromium HSTS preload list; are you connected to the internet?")
225225
sys.exit(1)
226226

@@ -244,7 +244,7 @@ def bootstrap_hsts_preload(self, force=False):
244244

245245
with open(path.join(preload_path, preload_filename), 'w') as fd:
246246
json.dump(entries, fd, indent=4)
247-
except ValueError, e:
247+
except ValueError as e:
248248
print("Unable to parse chromium HSTS preload list, has the format changed?")
249249
sys.exit(1)
250250

@@ -258,7 +258,7 @@ def bootstrap_pub_suffix(self, force=False):
258258

259259
try:
260260
content = download_bytes("Public suffix list", list_url)
261-
except urllib2.URLError:
261+
except urllib.error.URLError:
262262
print("Unable to download the public suffix list; are you connected to the internet?")
263263
sys.exit(1)
264264

python/servo/build_commands.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import shutil
1717
import subprocess
1818
import sys
19-
import urllib
19+
import six.moves.urllib as urllib
2020
import zipfile
2121
import stat
2222

@@ -498,7 +498,7 @@ def build(self, release=False, dev=False, jobs=None, params=None,
498498
print("Downloading GStreamer dependencies")
499499
gst_url = "https://servo-deps.s3.amazonaws.com/gstreamer/%s" % gst_lib_zip
500500
print(gst_url)
501-
urllib.urlretrieve(gst_url, gst_lib_zip)
501+
urllib.request.urlretrieve(gst_url, gst_lib_zip)
502502
zip_ref = zipfile.ZipFile(gst_lib_zip, "r")
503503
zip_ref.extractall(gst_dir)
504504
os.remove(gst_lib_zip)

python/servo/command_base.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
# option. This file may not be copied, modified, or distributed
88
# except according to those terms.
99

10+
from __future__ import print_function
11+
1012
from errno import ENOENT as NO_SUCH_FILE_OR_DIRECTORY
1113
from glob import glob
1214
import shutil
@@ -25,7 +27,7 @@
2527
import zipfile
2628
from xml.etree.ElementTree import XML
2729
from servo.util import download_file
28-
import urllib2
30+
import six.moves.urllib as urllib
2931
from bootstrap import check_gstreamer_lib
3032

3133
from mach.decorators import CommandArgument
@@ -105,7 +107,7 @@ def reset(tarinfo):
105107
# packaging (in case of exceptional situations like running out of disk space).
106108
# TODO do this in a temporary folder after #11983 is fixed
107109
temp_file = '{}.temp~'.format(dest_archive)
108-
with os.fdopen(os.open(temp_file, os.O_WRONLY | os.O_CREAT, 0644), 'w') as out_file:
110+
with os.fdopen(os.open(temp_file, os.O_WRONLY | os.O_CREAT, 0o644), 'w') as out_file:
109111
if dest_archive.endswith('.zip'):
110112
with zipfile.ZipFile(temp_file, 'w', zipfile.ZIP_DEFLATED) as zip_file:
111113
for entry in file_list:
@@ -350,15 +352,15 @@ def call_rustup_run(self, args, **kwargs):
350352
version_line = subprocess.check_output(["rustup" + BIN_SUFFIX, "--version"])
351353
except OSError as e:
352354
if e.errno == NO_SUCH_FILE_OR_DIRECTORY:
353-
print "It looks like rustup is not installed. See instructions at " \
354-
"https://github.com/servo/servo/#setting-up-your-environment"
355-
print
355+
print("It looks like rustup is not installed. See instructions at "
356+
"https://github.com/servo/servo/#setting-up-your-environment")
357+
print()
356358
return 1
357359
raise
358360
version = tuple(map(int, re.match("rustup (\d+)\.(\d+)\.(\d+)", version_line).groups()))
359361
if version < (1, 11, 0):
360-
print "rustup is at version %s.%s.%s, Servo requires 1.11.0 or more recent." % version
361-
print "Try running 'rustup self update'."
362+
print("rustup is at version %s.%s.%s, Servo requires 1.11.0 or more recent." % version)
363+
print("Try running 'rustup self update'.")
362364
return 1
363365
toolchain = self.toolchain()
364366
if platform.system() == "Windows":
@@ -504,15 +506,15 @@ def get_nightly_binary_path(self, nightly_date):
504506
nightly_date = nightly_date.strip()
505507
# Fetch the filename to download from the build list
506508
repository_index = NIGHTLY_REPOSITORY_URL + "?list-type=2&prefix=nightly"
507-
req = urllib2.Request(
509+
req = urllib.request.Request(
508510
"{}/{}/{}".format(repository_index, os_prefix, nightly_date))
509511
try:
510-
response = urllib2.urlopen(req).read()
512+
response = urllib.request.urlopen(req).read()
511513
tree = XML(response)
512514
namespaces = {'ns': tree.tag[1:tree.tag.index('}')]}
513515
file_to_download = tree.find('ns:Contents', namespaces).find(
514516
'ns:Key', namespaces).text
515-
except urllib2.URLError as e:
517+
except urllib.error.URLError as e:
516518
print("Could not fetch the available nightly versions from the repository : {}".format(
517519
e.reason))
518520
sys.exit(1)

python/servo/devenv_commands.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import signal
1515
import sys
1616
import tempfile
17-
import urllib2
17+
import six.moves.urllib as urllib
1818
import json
1919
import subprocess
2020

@@ -201,7 +201,7 @@ def grep(self, params):
201201
category='devenv')
202202
def rustup(self):
203203
url = get_static_rust_lang_org_dist() + "/channel-rust-nightly-date.txt"
204-
nightly_date = urllib2.urlopen(url, **get_urlopen_kwargs()).read()
204+
nightly_date = urllib.request.urlopen(url, **get_urlopen_kwargs()).read()
205205
toolchain = "nightly-" + nightly_date
206206
filename = path.join(self.context.topdir, "rust-toolchain")
207207
with open(filename, "w") as f:

python/servo/lints/wpt_lint.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
# option. This file may not be copied, modified, or distributed
88
# except according to those terms.
99

10+
from __future__ import print_function
11+
1012
import os
1113
import sys
1214

@@ -20,7 +22,7 @@ class Lint(LintRunner):
2022
def _get_wpt_files(self, suite):
2123
working_dir = os.path.join(WPT_PATH, suite, '')
2224
file_iter = self.get_files(working_dir, exclude_dirs=[])
23-
print '\nRunning the WPT lint on %s...' % working_dir
25+
print('\nRunning the WPT lint on %s...' % working_dir)
2426
for f in file_iter:
2527
if filter_file(f):
2628
yield f[len(working_dir):]

python/servo/mutation/mutator.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
# option. This file may not be copied, modified, or distributed
88
# except according to those terms.
99

10+
from __future__ import print_function
11+
1012
import fileinput
1113
import re
1214
import random
@@ -28,7 +30,7 @@ def init_variables(if_blocks):
2830
def deleteStatements(file_name, line_numbers):
2931
for line in fileinput.input(file_name, inplace=True):
3032
if fileinput.lineno() not in line_numbers:
31-
print line.rstrip()
33+
print(line.rstrip())
3234

3335

3436
class Strategy:
@@ -48,7 +50,7 @@ def mutate(self, file_name):
4850
for line in fileinput.input(file_name, inplace=True):
4951
if fileinput.lineno() == mutation_line_number:
5052
line = re.sub(self._replace_strategy['regex'], self._replace_strategy['replaceString'], line)
51-
print line.rstrip()
53+
print(line.rstrip())
5254
return mutation_line_number
5355

5456

python/servo/package_commands.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
import subprocess
2020
import sys
2121
import tempfile
22-
import urllib
22+
import six.moves.urllib as urllib
2323

2424
from mach.decorators import (
2525
CommandArgument,
@@ -594,7 +594,7 @@ def get_taskcluster_secret(name):
594594
"/secrets/v1/secret/project/servo/" +
595595
name
596596
)
597-
return json.load(urllib.urlopen(url))["secret"]
597+
return json.load(urllib.request.urlopen(url))["secret"]
598598

599599
def get_s3_secret():
600600
aws_access_key = None

python/servo/testing_commands.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,11 @@
1818
from collections import OrderedDict
1919
import time
2020
import json
21-
import urllib2
21+
import six.moves.urllib as urllib
2222
import base64
2323
import shutil
2424
import subprocess
25+
from six import iteritems
2526

2627
from mach.registrar import Registrar
2728
from mach.decorators import (
@@ -59,7 +60,7 @@
5960
"include_arg": "test_name"}),
6061
])
6162

62-
TEST_SUITES_BY_PREFIX = {path: k for k, v in TEST_SUITES.iteritems() if "paths" in v for path in v["paths"]}
63+
TEST_SUITES_BY_PREFIX = {path: k for k, v in iteritems(TEST_SUITES) if "paths" in v for path in v["paths"]}
6364

6465

6566
def create_parser_wpt():
@@ -158,7 +159,7 @@ def test(self, params, render_mode=DEFAULT_RENDER_MODE, release=False, tidy_all=
158159
return 1
159160

160161
test_start = time.time()
161-
for suite, tests in selected_suites.iteritems():
162+
for suite, tests in iteritems(selected_suites):
162163
props = suites[suite]
163164
kwargs = props.get("kwargs", {})
164165
if tests:
@@ -174,7 +175,7 @@ def test(self, params, render_mode=DEFAULT_RENDER_MODE, release=False, tidy_all=
174175
def suite_for_path(self, path_arg):
175176
if os.path.exists(path.abspath(path_arg)):
176177
abs_path = path.abspath(path_arg)
177-
for prefix, suite in TEST_SUITES_BY_PREFIX.iteritems():
178+
for prefix, suite in iteritems(TEST_SUITES_BY_PREFIX):
178179
if abs_path.startswith(prefix):
179180
return suite
180181
return None
@@ -510,9 +511,9 @@ def filter_intermittents(self, summary, log_filteredsummary, log_intermittents,
510511
elif tracker_api.endswith('/'):
511512
tracker_api = tracker_api[0:-1]
512513

513-
query = urllib2.quote(failure['test'], safe='')
514-
request = urllib2.Request("%s/query.py?name=%s" % (tracker_api, query))
515-
search = urllib2.urlopen(request)
514+
query = urllib.parse.quote(failure['test'], safe='')
515+
request = urllib.request.Request("%s/query.py?name=%s" % (tracker_api, query))
516+
search = urllib.request.urlopen(request)
516517
data = json.load(search)
517518
if len(data) == 0:
518519
actual_failures += [failure]
@@ -521,11 +522,11 @@ def filter_intermittents(self, summary, log_filteredsummary, log_intermittents,
521522
else:
522523
qstr = "repo:servo/servo+label:I-intermittent+type:issue+state:open+%s" % failure['test']
523524
# we want `/` to get quoted, but not `+` (github's API doesn't like that), so we set `safe` to `+`
524-
query = urllib2.quote(qstr, safe='+')
525-
request = urllib2.Request("https://api.github.com/search/issues?q=%s" % query)
525+
query = urllib.parse.quote(qstr, safe='+')
526+
request = urllib.request.Request("https://api.github.com/search/issues?q=%s" % query)
526527
if encoded_auth:
527528
request.add_header("Authorization", "Basic %s" % encoded_auth)
528-
search = urllib2.urlopen(request)
529+
search = urllib.request.urlopen(request)
529530
data = json.load(search)
530531
if data['total_count'] == 0:
531532
actual_failures += [failure]

python/servo/util.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@
1616
import shutil
1717
from socket import error as socket_error
1818
import stat
19-
import StringIO
19+
from io import BytesIO
2020
import sys
2121
import time
2222
import zipfile
23-
import urllib2
23+
import six.moves.urllib as urllib
2424

2525

2626
try:
@@ -101,10 +101,10 @@ def download(desc, src, writer, start_byte=0):
101101
dumb = (os.environ.get("TERM") == "dumb") or (not sys.stdout.isatty())
102102

103103
try:
104-
req = urllib2.Request(src)
104+
req = urllib.request.Request(src)
105105
if start_byte:
106-
req = urllib2.Request(src, headers={'Range': 'bytes={}-'.format(start_byte)})
107-
resp = urllib2.urlopen(req, **get_urlopen_kwargs())
106+
req = urllib.request.Request(src, headers={'Range': 'bytes={}-'.format(start_byte)})
107+
resp = urllib.request.urlopen(req, **get_urlopen_kwargs())
108108

109109
fsize = None
110110
if resp.info().getheader('Content-Length'):
@@ -136,16 +136,16 @@ def download(desc, src, writer, start_byte=0):
136136

137137
if not dumb:
138138
print()
139-
except urllib2.HTTPError, e:
139+
except urllib.error.HTTPError as e:
140140
print("Download failed ({}): {} - {}".format(e.code, e.reason, src))
141141
if e.code == 403:
142142
print("No Rust compiler binary available for this platform. "
143143
"Please see https://github.com/servo/servo/#prerequisites")
144144
sys.exit(1)
145-
except urllib2.URLError, e:
145+
except urllib.error.URLError as e:
146146
print("Error downloading {}: {}. The failing URL was: {}".format(desc, e.reason, src))
147147
sys.exit(1)
148-
except socket_error, e:
148+
except socket_error as e:
149149
print("Looks like there's a connectivity issue, check your Internet connection. {}".format(e))
150150
sys.exit(1)
151151
except KeyboardInterrupt:
@@ -154,7 +154,7 @@ def download(desc, src, writer, start_byte=0):
154154

155155

156156
def download_bytes(desc, src):
157-
content_writer = StringIO.StringIO()
157+
content_writer = BytesIO()
158158
download(desc, src, content_writer)
159159
return content_writer.getvalue()
160160

0 commit comments

Comments
 (0)