Add typing to compat.py

This commit is contained in:
cytolentino 2018-10-27 15:26:46 +01:00 committed by cytolentino
parent 35701ea3cd
commit ecf90d4792
2 changed files with 22 additions and 6 deletions

View File

@ -11,6 +11,11 @@ import sys
from pip._vendor.six import text_type
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import Tuple, Text # noqa: F401
try:
import ipaddress
except ImportError:
@ -68,6 +73,7 @@ else:
def console_to_str(data):
# type: (bytes) -> Text
"""Return a string, safe for output, of subprocess output.
We assume the data is in the locale preferred encoding.
@ -88,13 +94,13 @@ def console_to_str(data):
# Now try to decode the data - if we fail, warn the user and
# decode with replacement.
try:
s = data.decode(encoding)
decoded_data = data.decode(encoding)
except UnicodeDecodeError:
logger.warning(
"Subprocess output does not appear to be encoded as %s",
encoding,
)
s = data.decode(encoding, errors=backslashreplace_decode)
decoded_data = data.decode(encoding, errors=backslashreplace_decode)
# Make sure we can print the output, by encoding it to the output
# encoding with replacement of unencodable characters, and then
@ -112,20 +118,25 @@ def console_to_str(data):
"encoding", None)
if output_encoding:
s = s.encode(output_encoding, errors="backslashreplace")
s = s.decode(output_encoding)
output_encoded = decoded_data.encode(
output_encoding,
errors="backslashreplace"
)
decoded_data = output_encoded.decode(output_encoding)
return s
return decoded_data
if sys.version_info >= (3,):
def native_str(s, replace=False):
# type: (str, bool) -> str
if isinstance(s, bytes):
return s.decode('utf-8', 'replace' if replace else 'strict')
return s
else:
def native_str(s, replace=False):
# type: (str, bool) -> str
# Replace is ignored -- unicode to UTF-8 can't fail
if isinstance(s, text_type):
return s.encode('utf-8')
@ -133,6 +144,7 @@ else:
def get_path_uid(path):
# type: (str) -> int
"""
Return path's uid.
@ -174,6 +186,7 @@ else:
def expanduser(path):
# type: (str) -> str
"""
Expand ~ and ~user constructions.
@ -199,6 +212,7 @@ WINDOWS = (sys.platform.startswith("win") or
def samefile(file1, file2):
# type: (str, str) -> bool
"""Provide an alternative for os.path.samefile on Windows/Python2"""
if hasattr(os.path, 'samefile'):
return os.path.samefile(file1, file2)
@ -210,13 +224,15 @@ def samefile(file1, file2):
if hasattr(shutil, 'get_terminal_size'):
def get_terminal_size():
# type: () -> Tuple[int, int]
"""
Returns a tuple (x, y) representing the width(x) and the height(y)
in characters of the terminal window.
"""
return tuple(shutil.get_terminal_size())
return tuple(shutil.get_terminal_size()) # type: ignore
else:
def get_terminal_size():
# type: () -> Tuple[int, int]
"""
Returns a tuple (x, y) representing the width(x) and the height(y)
in characters of the terminal window.