Skip to content

Commit 5fac450

Browse files
authored
Merge pull request #9368 from jdufresne/ensure
Remove unnecessary uses of six.ensure_(binary|str|text)
2 parents 4b3ecda + c115cdc commit 5fac450

11 files changed

+26
-54
lines changed

news/bca635a1-abe3-4532-8add-bf7491b0eea5.bugfix.rst

Whitespace-only changes.

src/pip/_internal/network/session.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import urllib.parse
1717
import warnings
1818

19-
from pip._vendor import requests, six, urllib3
19+
from pip._vendor import requests, urllib3
2020
from pip._vendor.cachecontrol import CacheControlAdapter
2121
from pip._vendor.requests.adapters import BaseAdapter, HTTPAdapter
2222
from pip._vendor.requests.models import Response
@@ -371,14 +371,8 @@ def is_secure_origin(self, location):
371371
continue
372372

373373
try:
374-
addr = ipaddress.ip_address(
375-
None
376-
if origin_host is None
377-
else six.ensure_text(origin_host)
378-
)
379-
network = ipaddress.ip_network(
380-
six.ensure_text(secure_host)
381-
)
374+
addr = ipaddress.ip_address(origin_host)
375+
network = ipaddress.ip_network(secure_host)
382376
except ValueError:
383377
# We don't have both a valid address or a valid network, so
384378
# we'll check this origin against hostnames.

src/pip/_internal/req/req_install.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ def name(self):
255255
# type: () -> Optional[str]
256256
if self.req is None:
257257
return None
258-
return six.ensure_str(pkg_resources.safe_name(self.req.name))
258+
return pkg_resources.safe_name(self.req.name)
259259

260260
@property
261261
def specifier(self):

src/pip/_internal/self_outdated_check.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import sys
77

88
from pip._vendor.packaging import version as packaging_version
9-
from pip._vendor.six import ensure_binary
109

1110
from pip._internal.index.collector import LinkCollector
1211
from pip._internal.index.package_finder import PackageFinder
@@ -31,7 +30,7 @@
3130

3231
def _get_statefile_name(key):
3332
# type: (str) -> str
34-
key_bytes = ensure_binary(key)
33+
key_bytes = key.encode()
3534
name = hashlib.sha224(key_bytes).hexdigest()
3635
return name
3736

@@ -85,7 +84,7 @@ def save(self, pypi_version, current_time):
8584
text = json.dumps(state, sort_keys=True, separators=(",", ":"))
8685

8786
with adjacent_tmp_file(self.statefile_path) as f:
88-
f.write(ensure_binary(text))
87+
f.write(text.encode())
8988

9089
try:
9190
# Since we have a prefix-specific state file, we can just

src/pip/_internal/utils/pkg_resources.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
from pip._vendor.pkg_resources import yield_lines
2-
from pip._vendor.six import ensure_str
32

43
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
54

@@ -21,7 +20,7 @@ def has_metadata(self, name):
2120
def get_metadata(self, name):
2221
# type: (str) -> str
2322
try:
24-
return ensure_str(self._metadata[name])
23+
return self._metadata[name].decode()
2524
except UnicodeDecodeError as e:
2625
# Mirrors handling done in pkg_resources.NullProvider.
2726
e.reason += f" in {name} file"

src/pip/_internal/utils/temp_dir.py

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,7 @@
66
from contextlib import contextmanager
77

88
from pip._vendor.contextlib2 import ExitStack
9-
from pip._vendor.six import ensure_text
109

11-
from pip._internal.utils.compat import WINDOWS
1210
from pip._internal.utils.misc import enum, rmtree
1311
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
1412

@@ -196,15 +194,7 @@ def cleanup(self):
196194
self._deleted = True
197195
if not os.path.exists(self._path):
198196
return
199-
# Make sure to pass unicode on Python 2 to make the contents also
200-
# use unicode, ensuring non-ASCII names and can be represented.
201-
# This is only done on Windows because POSIX platforms use bytes
202-
# natively for paths, and the bytes-text conversion omission avoids
203-
# errors caused by the environment configuring encodings incorrectly.
204-
if WINDOWS:
205-
rmtree(ensure_text(self._path))
206-
else:
207-
rmtree(self._path)
197+
rmtree(self._path)
208198

209199

210200
class AdjacentTempDirectory(TempDirectory):

src/pip/_internal/utils/wheel.py

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
from pip._vendor.packaging.utils import canonicalize_name
99
from pip._vendor.pkg_resources import DistInfoDistribution
10-
from pip._vendor.six import ensure_str
1110

1211
from pip._internal.exceptions import UnsupportedWheel
1312
from pip._internal.utils.pkg_resources import DictMetadata
@@ -62,17 +61,10 @@ def pkg_resources_distribution_for_wheel(wheel_zip, name, location):
6261

6362
metadata_text = {} # type: Dict[str, bytes]
6463
for path in metadata_files:
65-
# If a flag is set, namelist entries may be unicode in Python 2.
66-
# We coerce them to native str type to match the types used in the rest
67-
# of the code. This cannot fail because unicode can always be encoded
68-
# with UTF-8.
69-
full_path = ensure_str(path)
70-
_, metadata_name = full_path.split("/", 1)
64+
_, metadata_name = path.split("/", 1)
7165

7266
try:
73-
metadata_text[metadata_name] = read_wheel_metadata_file(
74-
wheel_zip, full_path
75-
)
67+
metadata_text[metadata_name] = read_wheel_metadata_file(wheel_zip, path)
7668
except UnsupportedWheel as e:
7769
raise UnsupportedWheel(
7870
"{} has an invalid wheel, {}".format(name, str(e))
@@ -139,9 +131,7 @@ def wheel_dist_info_dir(source, name):
139131
)
140132
)
141133

142-
# Zip file paths can be unicode or str depending on the zip entry flags,
143-
# so normalize it.
144-
return ensure_str(info_dir)
134+
return info_dir
145135

146136

147137
def read_wheel_metadata_file(source, path):
@@ -166,7 +156,7 @@ def wheel_metadata(source, dist_info_dir):
166156
wheel_contents = read_wheel_metadata_file(source, path)
167157

168158
try:
169-
wheel_text = ensure_str(wheel_contents)
159+
wheel_text = wheel_contents.decode()
170160
except UnicodeDecodeError as e:
171161
raise UnsupportedWheel(f"error decoding {path!r}: {e!r}")
172162

tests/lib/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
from zipfile import ZipFile
1414

1515
import pytest
16-
from pip._vendor.six import ensure_binary
1716
from scripttest import FoundDir, TestFileEnvironment
1817

1918
from pip._internal.index.collector import LinkCollector
@@ -1095,7 +1094,7 @@ def create_basic_sdist_for_package(
10951094
for fname in files:
10961095
path = script.temp_path / fname
10971096
path.parent.mkdir(exist_ok=True, parents=True)
1098-
path.write_bytes(ensure_binary(files[fname]))
1097+
path.write_bytes(files[fname].encode("utf-8"))
10991098

11001099
retval = script.scratch_path / archive_name
11011100
generated = shutil.make_archive(

tests/lib/test_wheel.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55
from functools import partial
66
from zipfile import ZipFile
77

8-
from pip._vendor.six import ensure_text
9-
108
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
119
from tests.lib.wheel import (
1210
_default,
@@ -164,7 +162,7 @@ def test_make_wheel_default_record():
164162
extra_data_files={"purelib/info.txt": "c"},
165163
).as_zipfile() as z:
166164
record_bytes = z.read("simple-0.1.0.dist-info/RECORD")
167-
record_text = ensure_text(record_bytes)
165+
record_text = record_bytes.decode()
168166
record_rows = list(csv.reader(record_text.splitlines()))
169167
records = {
170168
row[0]: row[1:] for row in record_rows

tests/lib/wheel.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
from zipfile import ZipFile
1414

1515
from pip._vendor.requests.structures import CaseInsensitiveDict
16-
from pip._vendor.six import ensure_binary, ensure_text
1716

1817
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
1918
from tests.lib.path import Path
@@ -61,6 +60,13 @@ class Defaulted(Union[Default, T]):
6160
pass
6261

6362

63+
def ensure_binary(value):
64+
# type: (AnyStr) -> bytes
65+
if isinstance(value, bytes):
66+
return value
67+
return value.encode()
68+
69+
6470
def message_from_dict(headers):
6571
# type: (Dict[str, HeaderValue]) -> Message
6672
"""Plain key-value pairs are set in the returned message.
@@ -110,7 +116,7 @@ def make_metadata_file(
110116
if body is not _default:
111117
message.set_payload(body)
112118

113-
return File(path, ensure_binary(message_from_dict(metadata).as_string()))
119+
return File(path, message_from_dict(metadata).as_bytes())
114120

115121

116122
def make_wheel_metadata_file(
@@ -139,7 +145,7 @@ def make_wheel_metadata_file(
139145
if updates is not _default:
140146
metadata.update(updates)
141147

142-
return File(path, ensure_binary(message_from_dict(metadata).as_string()))
148+
return File(path, message_from_dict(metadata).as_bytes())
143149

144150

145151
def make_entry_points_file(
@@ -167,7 +173,7 @@ def make_entry_points_file(
167173

168174
return File(
169175
dist_info_path(name, version, "entry_points.txt"),
170-
ensure_binary("\n".join(lines)),
176+
"\n".join(lines).encode(),
171177
)
172178

173179

@@ -243,7 +249,7 @@ def record_file_maker_wrapper(
243249
with StringIO(newline="") as buf:
244250
writer = csv.writer(buf)
245251
for record in records:
246-
writer.writerow(map(ensure_text, record))
252+
writer.writerow(record)
247253
contents = buf.getvalue().encode("utf-8")
248254

249255
yield File(record_path, contents)

tests/unit/test_utils_pkg_resources.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import pytest
44
from pip._vendor.pkg_resources import DistInfoDistribution, Requirement
5-
from pip._vendor.six import ensure_binary
65

76
from pip._internal.utils.packaging import get_metadata, get_requires_python
87
from pip._internal.utils.pkg_resources import DictMetadata
@@ -26,9 +25,7 @@ def test_dict_metadata_works():
2625
metadata["Provides-Extra"] = extra
2726
metadata["Requires-Python"] = requires_python
2827

29-
inner_metadata = DictMetadata({
30-
"METADATA": ensure_binary(metadata.as_string())
31-
})
28+
inner_metadata = DictMetadata({"METADATA": metadata.as_bytes()})
3229
dist = DistInfoDistribution(
3330
location="<in-memory>", metadata=inner_metadata, project_name=name
3431
)

0 commit comments

Comments
 (0)