macurl2path.py 3.2 KB
Newer Older
1 2 3
"""Macintosh-specific module for conversion between pathnames and URLs.

Do not import directly; use urllib instead."""
4 5 6 7

import urllib
import os

8 9
__all__ = ["url2pathname","pathname2url"]

10
def url2pathname(pathname):
11 12
    """OS-specific conversion from a relative URL of the 'file' scheme
    to a file system path; not recommended for general use."""
13 14 15 16
    #
    # XXXX The .. handling should be fixed...
    #
    tp = urllib.splittype(pathname)[0]
17
    if tp and tp != 'file':
18
        raise RuntimeError, 'Cannot convert non-local URL to pathname'
19 20
    # Turn starting /// into /, an empty hostname means current host
    if pathname[:3] == '///':
Tim Peters's avatar
Tim Peters committed
21
        pathname = pathname[2:]
22 23
    elif pathname[:2] == '//':
        raise RuntimeError, 'Cannot convert non-local URL to pathname'
24
    components = pathname.split('/')
25 26 27
    # Remove . and embedded ..
    i = 0
    while i < len(components):
28 29 30 31 32 33
        if components[i] == '.':
            del components[i]
        elif components[i] == '..' and i > 0 and \
                                  components[i-1] not in ('', '..'):
            del components[i-1:i+1]
            i = i-1
34
        elif components[i] == '' and i > 0 and components[i-1] != '':
35 36 37
            del components[i]
        else:
            i = i+1
38
    if not components[0]:
39
        # Absolute unix path, don't start with colon
40
        rv = ':'.join(components[1:])
41
    else:
42 43 44 45 46 47
        # relative unix path, start with colon. First replace
        # leading .. by empty strings (giving ::file)
        i = 0
        while i < len(components) and components[i] == '..':
            components[i] = ''
            i = i + 1
48
        rv = ':' + ':'.join(components)
49 50
    # and finally unquote slashes and other funny characters
    return urllib.unquote(rv)
51 52

def pathname2url(pathname):
53 54
    """OS-specific conversion from a file system path to a relative URL
    of the 'file' scheme; not recommended for general use."""
55
    if '/' in pathname:
56
        raise RuntimeError, "Cannot convert pathname containing slashes"
57
    components = pathname.split(':')
58 59
    # Remove empty first and/or last component
    if components[0] == '':
60
        del components[0]
61
    if components[-1] == '':
62
        del components[-1]
63
    # Replace empty string ('::') by .. (will result in '/../' later)
64
    for i in range(len(components)):
65 66
        if components[i] == '':
            components[i] = '..'
67
    # Truncate names longer than 31 bytes
68
    components = map(_pncomp2url, components)
69 70

    if os.path.isabs(pathname):
71
        return '/' + '/'.join(components)
72
    else:
73
        return '/'.join(components)
Tim Peters's avatar
Tim Peters committed
74

75
def _pncomp2url(component):
Tim Peters's avatar
Tim Peters committed
76 77 78
    component = urllib.quote(component[:31], safe='')  # We want to quote slashes
    return component

79 80
def test():
    for url in ["index.html",
81 82 83 84
                "bar/index.html",
                "/foo/bar/index.html",
                "/foo/bar/",
                "/"]:
85
        print '%r -> %r' % (url, url2pathname(url))
86
    for path in ["drive:",
87 88 89 90 91 92 93
                 "drive:dir:",
                 "drive:dir:file",
                 "drive:file",
                 "file",
                 ":file",
                 ":dir:",
                 ":dir:file"]:
94
        print '%r -> %r' % (path, pathname2url(path))
95 96 97

if __name__ == '__main__':
    test()