Skip to content

Commit 77d0ddc

Browse files
ichard26uranusjr
andauthored
Replace captured_output() and get_url_scheme() with stdlib alternatives (#12639)
Co-authored-by: Tzu-ping Chung <[email protected]>
1 parent e0946f3 commit 77d0ddc

File tree

8 files changed

+14
-71
lines changed

8 files changed

+14
-71
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Replace ``captured_output()`` and ``get_url_scheme()`` with stdlib alternatives.

src/pip/_internal/operations/install/wheel.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@
5151
from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl
5252
from pip._internal.models.scheme import SCHEME_KEYS, Scheme
5353
from pip._internal.utils.filesystem import adjacent_tmp_file, replace
54-
from pip._internal.utils.misc import captured_stdout, ensure_dir, hash_file, partition
54+
from pip._internal.utils.misc import StreamWrapper, ensure_dir, hash_file, partition
5555
from pip._internal.utils.unpacking import (
5656
current_umask,
5757
is_within_directory,
@@ -603,7 +603,9 @@ def pyc_output_path(path: str) -> str:
603603

604604
# Compile all of the pyc files for the installed files
605605
if pycompile:
606-
with captured_stdout() as stdout:
606+
with contextlib.redirect_stdout(
607+
StreamWrapper.from_stream(sys.stdout)
608+
) as stdout:
607609
with warnings.catch_warnings():
608610
warnings.filterwarnings("ignore")
609611
for path in pyc_source_file_paths():

src/pip/_internal/req/req_file.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
from pip._internal.exceptions import InstallationError, RequirementsFileParseError
2727
from pip._internal.models.search_scope import SearchScope
2828
from pip._internal.utils.encoding import auto_decode
29-
from pip._internal.utils.urls import get_url_scheme
3029

3130
if TYPE_CHECKING:
3231
from pip._internal.index.package_finder import PackageFinder
@@ -533,8 +532,7 @@ def get_file_content(url: str, session: "PipSession") -> Tuple[str, str]:
533532
:param url: File path or url.
534533
:param session: PipSession instance.
535534
"""
536-
scheme = get_url_scheme(url)
537-
535+
scheme = urllib.parse.urlsplit(url).scheme
538536
# Pip has special support for file:// URLs (LocalFSAdapter).
539537
if scheme in ["http", "https", "file"]:
540538
# Delay importing heavy network modules until absolutely necessary.

src/pip/_internal/utils/misc.py

Lines changed: 0 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import contextlib
21
import errno
32
import getpass
43
import hashlib
@@ -21,7 +20,6 @@
2120
Any,
2221
BinaryIO,
2322
Callable,
24-
ContextManager,
2523
Dict,
2624
Generator,
2725
Iterable,
@@ -57,7 +55,6 @@
5755
"normalize_path",
5856
"renames",
5957
"get_prog",
60-
"captured_stdout",
6158
"ensure_dir",
6259
"remove_auth_from_url",
6360
"check_externally_managed",
@@ -400,40 +397,6 @@ def encoding(self) -> str: # type: ignore
400397
return self.orig_stream.encoding
401398

402399

403-
@contextlib.contextmanager
404-
def captured_output(stream_name: str) -> Generator[StreamWrapper, None, None]:
405-
"""Return a context manager used by captured_stdout/stdin/stderr
406-
that temporarily replaces the sys stream *stream_name* with a StringIO.
407-
408-
Taken from Lib/support/__init__.py in the CPython repo.
409-
"""
410-
orig_stdout = getattr(sys, stream_name)
411-
setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout))
412-
try:
413-
yield getattr(sys, stream_name)
414-
finally:
415-
setattr(sys, stream_name, orig_stdout)
416-
417-
418-
def captured_stdout() -> ContextManager[StreamWrapper]:
419-
"""Capture the output of sys.stdout:
420-
421-
with captured_stdout() as stdout:
422-
print('hello')
423-
self.assertEqual(stdout.getvalue(), 'hello\n')
424-
425-
Taken from Lib/support/__init__.py in the CPython repo.
426-
"""
427-
return captured_output("stdout")
428-
429-
430-
def captured_stderr() -> ContextManager[StreamWrapper]:
431-
"""
432-
See captured_stdout().
433-
"""
434-
return captured_output("stderr")
435-
436-
437400
# Simulates an enum
438401
def enum(*sequential: Any, **named: Any) -> Type[Any]:
439402
enums = dict(zip(sequential, range(len(sequential))), **named)

src/pip/_internal/utils/urls.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,10 @@
22
import string
33
import urllib.parse
44
import urllib.request
5-
from typing import Optional
65

76
from .compat import WINDOWS
87

98

10-
def get_url_scheme(url: str) -> Optional[str]:
11-
if ":" not in url:
12-
return None
13-
return url.split(":", 1)[0].lower()
14-
15-
169
def path_to_url(path: str) -> str:
1710
"""
1811
Convert a path to a file: URL. The path will be made absolute and have

src/pip/_internal/vcs/versioncontrol.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838
format_command_args,
3939
make_command,
4040
)
41-
from pip._internal.utils.urls import get_url_scheme
4241

4342
__all__ = ["vcs"]
4443

@@ -52,8 +51,8 @@ def is_url(name: str) -> bool:
5251
"""
5352
Return true if the name looks like a URL.
5453
"""
55-
scheme = get_url_scheme(name)
56-
if scheme is None:
54+
scheme = urllib.parse.urlsplit(name).scheme
55+
if not scheme:
5756
return False
5857
return scheme in ["http", "https", "file", "ftp"] + vcs.all_schemes
5958

tests/unit/test_logging.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import logging
22
import time
3+
from contextlib import redirect_stderr, redirect_stdout
4+
from io import StringIO
35
from threading import Thread
46
from unittest.mock import patch
57

@@ -11,7 +13,6 @@
1113
RichPipStreamHandler,
1214
indent_log,
1315
)
14-
from pip._internal.utils.misc import captured_stderr, captured_stdout
1516

1617
logger = logging.getLogger(__name__)
1718

@@ -140,7 +141,7 @@ def test_broken_pipe_in_stderr_flush(self) -> None:
140141
"""
141142
record = self._make_log_record()
142143

143-
with captured_stderr() as stderr:
144+
with redirect_stderr(StringIO()) as stderr:
144145
handler = RichPipStreamHandler(stream=stderr, no_color=True)
145146
with patch("sys.stderr.flush") as mock_flush:
146147
mock_flush.side_effect = BrokenPipeError()
@@ -163,7 +164,7 @@ def test_broken_pipe_in_stdout_write(self) -> None:
163164
"""
164165
record = self._make_log_record()
165166

166-
with captured_stdout() as stdout:
167+
with redirect_stdout(StringIO()) as stdout:
167168
handler = RichPipStreamHandler(stream=stdout, no_color=True)
168169
with patch("sys.stdout.write") as mock_write:
169170
mock_write.side_effect = BrokenPipeError()
@@ -178,7 +179,7 @@ def test_broken_pipe_in_stdout_flush(self) -> None:
178179
"""
179180
record = self._make_log_record()
180181

181-
with captured_stdout() as stdout:
182+
with redirect_stdout(StringIO()) as stdout:
182183
handler = RichPipStreamHandler(stream=stdout, no_color=True)
183184
with patch("sys.stdout.flush") as mock_flush:
184185
mock_flush.side_effect = BrokenPipeError()

tests/unit/test_urls.py

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,10 @@
11
import os
22
import sys
33
import urllib.request
4-
from typing import Optional
54

65
import pytest
76

8-
from pip._internal.utils.urls import get_url_scheme, path_to_url, url_to_path
9-
10-
11-
@pytest.mark.parametrize(
12-
"url,expected",
13-
[
14-
("http://localhost:8080/", "http"),
15-
("file:c:/path/to/file", "file"),
16-
("file:/dev/null", "file"),
17-
("", None),
18-
],
19-
)
20-
def test_get_url_scheme(url: str, expected: Optional[str]) -> None:
21-
assert get_url_scheme(url) == expected
7+
from pip._internal.utils.urls import path_to_url, url_to_path
228

239

2410
@pytest.mark.skipif("sys.platform == 'win32'")

0 commit comments

Comments
 (0)