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