Bump version to 0.9.1.
[python/dscho.git] / Lib / macurl2path.py
blobc971edaa22dad13a1ffe4b57cff15255334ef45a
1 """Macintosh-specific module for conversion between pathnames and URLs.
3 Do not import directly; use urllib instead."""
5 import string
6 import urllib
7 import os
9 def url2pathname(pathname):
10 "Convert /-delimited pathname to mac pathname"
12 # XXXX The .. handling should be fixed...
14 tp = urllib.splittype(pathname)[0]
15 if tp and tp <> 'file':
16 raise RuntimeError, 'Cannot convert non-local URL to pathname'
17 # Turn starting /// into /, an empty hostname means current host
18 if pathname[:3] == '///':
19 pathname = pathname[2:]
20 elif pathname[:2] == '//':
21 raise RuntimeError, 'Cannot convert non-local URL to pathname'
22 components = string.split(pathname, '/')
23 # Remove . and embedded ..
24 i = 0
25 while i < len(components):
26 if components[i] == '.':
27 del components[i]
28 elif components[i] == '..' and i > 0 and \
29 components[i-1] not in ('', '..'):
30 del components[i-1:i+1]
31 i = i-1
32 elif components[i] == '' and i > 0 and components[i-1] <> '':
33 del components[i]
34 else:
35 i = i+1
36 if not components[0]:
37 # Absolute unix path, don't start with colon
38 rv = string.join(components[1:], ':')
39 else:
40 # relative unix path, start with colon. First replace
41 # leading .. by empty strings (giving ::file)
42 i = 0
43 while i < len(components) and components[i] == '..':
44 components[i] = ''
45 i = i + 1
46 rv = ':' + string.join(components, ':')
47 # and finally unquote slashes and other funny characters
48 return urllib.unquote(rv)
50 def pathname2url(pathname):
51 "convert mac pathname to /-delimited pathname"
52 if '/' in pathname:
53 raise RuntimeError, "Cannot convert pathname containing slashes"
54 components = string.split(pathname, ':')
55 # Remove empty first and/or last component
56 if components[0] == '':
57 del components[0]
58 if components[-1] == '':
59 del components[-1]
60 # Replace empty string ('::') by .. (will result in '/../' later)
61 for i in range(len(components)):
62 if components[i] == '':
63 components[i] = '..'
64 # Truncate names longer than 31 bytes
65 components = map(_pncomp2url, components)
67 if os.path.isabs(pathname):
68 return '/' + string.join(components, '/')
69 else:
70 return string.join(components, '/')
72 def _pncomp2url(component):
73 component = urllib.quote(component[:31], safe='') # We want to quote slashes
74 return component
76 def test():
77 for url in ["index.html",
78 "bar/index.html",
79 "/foo/bar/index.html",
80 "/foo/bar/",
81 "/"]:
82 print `url`, '->', `url2pathname(url)`
83 for path in ["drive:",
84 "drive:dir:",
85 "drive:dir:file",
86 "drive:file",
87 "file",
88 ":file",
89 ":dir:",
90 ":dir:file"]:
91 print `path`, '->', `pathname2url(path)`
93 if __name__ == '__main__':
94 test()