blob: 7d53d624aa7296d1e4cddc643ea4c098e80ad185 [file] [log] [blame]
Guido van Rossum008ec681996-10-15 14:40:41 +00001"""Mac specific module for conversion between pathnames and URLs.
2Do not import directly, use urllib instead."""
Guido van Rossum1acbffe1996-05-28 23:52:06 +00003
4import string
5import urllib
6import os
7
8def url2pathname(pathname):
9 "Convert /-delimited pathname to mac pathname"
10 #
11 # XXXX The .. handling should be fixed...
12 #
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 return 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 return ':' + string.join(components, ':')
41
42def pathname2url(pathname):
43 "convert mac pathname to /-delimited pathname"
44 if '/' in pathname:
45 raise RuntimeError, "Cannot convert pathname containing slashes"
46 components = string.split(pathname, ':')
47 # Replace empty string ('::') by .. (will result in '/../' later)
48 for i in range(1, len(components)):
49 if components[i] == '':
50 components[i] = '..'
51 # Truncate names longer than 31 bytes
52 components = map(lambda x: x[:31], components)
53
54 if os.path.isabs(pathname):
55 return '/' + string.join(components, '/')
56 else:
57 return string.join(components, '/')
58
59def test():
60 for url in ["index.html",
61 "bar/index.html",
62 "/foo/bar/index.html",
63 "/foo/bar/",
64 "/"]:
65 print `url`, '->', `url2pathname(url)`
66 for path in ["drive:",
67 "drive:dir:",
68 "drive:dir:file",
69 "drive:file",
70 "file",
71 ":file",
72 ":dir:",
73 ":dir:file"]:
74 print `path`, '->', `pathname2url(path)`
75
76if __name__ == '__main__':
77 test()