Path: blob/main/test/lib/python3.9/site-packages/pip/_internal/utils/urls.py
4804 views
import os1import string2import urllib.parse3import urllib.request4from typing import Optional56from .compat import WINDOWS789def get_url_scheme(url: str) -> Optional[str]:10if ":" not in url:11return None12return url.split(":", 1)[0].lower()131415def path_to_url(path: str) -> str:16"""17Convert a path to a file: URL. The path will be made absolute and have18quoted path parts.19"""20path = os.path.normpath(os.path.abspath(path))21url = urllib.parse.urljoin("file:", urllib.request.pathname2url(path))22return url232425def url_to_path(url: str) -> str:26"""27Convert a file: URL to a path.28"""29assert url.startswith(30"file:"31), f"You can only turn file: urls into filenames (not {url!r})"3233_, netloc, path, _, _ = urllib.parse.urlsplit(url)3435if not netloc or netloc == "localhost":36# According to RFC 8089, same as empty authority.37netloc = ""38elif WINDOWS:39# If we have a UNC path, prepend UNC share notation.40netloc = "\\\\" + netloc41else:42raise ValueError(43f"non-local file URIs are not supported on this platform: {url!r}"44)4546path = urllib.request.url2pathname(netloc + path)4748# On Windows, urlsplit parses the path as something like "/C:/Users/foo".49# This creates issues for path-related functions like io.open(), so we try50# to detect and strip the leading slash.51if (52WINDOWS53and not netloc # Not UNC.54and len(path) >= 355and path[0] == "/" # Leading slash to strip.56and path[1] in string.ascii_letters # Drive letter.57and path[2:4] in (":", ":/") # Colon + end of string, or colon + absolute path.58):59path = path[1:]6061return path626364