1 """Macintosh-specific module for conversion between pathnames and URLs.
3 Do not import directly; use urllib instead."""
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 ..
25 while i
< len(components
):
26 if components
[i
] == '.':
28 elif components
[i
] == '..' and i
> 0 and \
29 components
[i
-1] not in ('', '..'):
30 del components
[i
-1:i
+1]
32 elif components
[i
] == '' and i
> 0 and components
[i
-1] <> '':
37 # Absolute unix path, don't start with colon
38 rv
= string
.join(components
[1:], ':')
40 # relative unix path, start with colon. First replace
41 # leading .. by empty strings (giving ::file)
43 while i
< len(components
) and components
[i
] == '..':
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"
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] == '':
58 if components
[-1] == '':
60 # Replace empty string ('::') by .. (will result in '/../' later)
61 for i
in range(len(components
)):
62 if 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
, '/')
70 return string
.join(components
, '/')
72 def _pncomp2url(component
):
73 component
= urllib
.quote(component
[:31], safe
='') # We want to quote slashes
77 for url
in ["index.html",
79 "/foo/bar/index.html",
82 print `url`
, '->', `
url2pathname(url
)`
83 for path
in ["drive:",
91 print `path`
, '->', `
pathname2url(path
)`
93 if __name__
== '__main__':