File: _url_tools.py

package info (click to toggle)
python-fs 2.4.16-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,944 kB
  • sloc: python: 13,048; makefile: 226; sh: 3
file content (51 lines) | stat: -rw-r--r-- 1,380 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import typing

import platform
import re
import urllib.request

if typing.TYPE_CHECKING:
    from typing import Text

_WINDOWS_PLATFORM = platform.system() == "Windows"


def url_quote(path_snippet):
    # type: (Text) -> Text
    """Quote a URL without quoting the Windows drive letter, if any.

    On Windows, it will separate drive letter and quote Windows
    path alone. No magic on Unix-like path, just pythonic
    `~urllib.request.pathname2url`.

    Arguments:
       path_snippet (str): a file path, relative or absolute.

    """
    if _WINDOWS_PLATFORM and _has_drive_letter(path_snippet):
        drive_letter, path = path_snippet.split(":", 1)
        path = urllib.request.pathname2url(path)
        path_snippet = "{}:{}".format(drive_letter, path)
    else:
        path_snippet = urllib.request.pathname2url(path_snippet)
    return path_snippet


def _has_drive_letter(path_snippet):
    # type: (Text) -> bool
    """Check whether a path contains a drive letter.

    Arguments:
       path_snippet (str): a file path, relative or absolute.

    Example:
        >>> _has_drive_letter("D:/Data")
        True
        >>> _has_drive_letter(r"C:\\System32\\ test")
        True
        >>> _has_drive_letter("/tmp/abc:test")
        False

    """
    windows_drive_pattern = ".:[/\\\\].*$"
    return re.match(windows_drive_pattern, path_snippet) is not None