1import os
2import string
3import urllib.parse # noqa: F401
4
5from .compat import WINDOWS
6
7
8def path_to_url(path: str) -> str:
9 """
10 Convert a path to a file: URL. The path will be made absolute and have
11 quoted path parts.
12 """
13 import urllib.request
14
15 path = os.path.normpath(os.path.abspath(path))
16 url = urllib.parse.urljoin("file://", urllib.request.pathname2url(path))
17 return url
18
19
20def url_to_path(url: str) -> str:
21 """
22 Convert a file: URL to a path.
23 """
24 import urllib.request
25
26 assert url.startswith(
27 "file:"
28 ), f"You can only turn file: urls into filenames (not {url!r})"
29
30 _, netloc, path, _, _ = urllib.parse.urlsplit(url)
31
32 if not netloc or netloc == "localhost":
33 # According to RFC 8089, same as empty authority.
34 netloc = ""
35 elif WINDOWS:
36 # If we have a UNC path, prepend UNC share notation.
37 netloc = "\\\\" + netloc
38 else:
39 raise ValueError(
40 f"non-local file URIs are not supported on this platform: {url!r}"
41 )
42
43 path = urllib.request.url2pathname(netloc + path)
44
45 # On Windows, urlsplit parses the path as something like "/C:/Users/foo".
46 # This creates issues for path-related functions like io.open(), so we try
47 # to detect and strip the leading slash.
48 if (
49 WINDOWS
50 and not netloc # Not UNC.
51 and len(path) >= 3
52 and path[0] == "/" # Leading slash to strip.
53 and path[1] in string.ascii_letters # Drive letter.
54 and path[2:4] in (":", ":/") # Colon + end of string, or colon + absolute path.
55 ):
56 path = path[1:]
57
58 return path