Results of a rewrite pass
[python/dscho.git] / Lib / plat-riscos / rourl2path.py
blob9c213866a968788b78d91a4cc486293d6b4f36d0
1 """riscos specific module for conversion between pathnames and URLs.
2 Based on macurl2path.
3 Do not import directly, use urllib instead."""
5 import string
6 import urllib
7 import os
9 __all__ = ["url2pathname","pathname2url"]
11 __slash_dot = string.maketrans("/.", "./")
13 def url2pathname(url):
14 "Convert URL to a RISC OS path."
15 tp = urllib.splittype(url)[0]
16 if tp and tp <> 'file':
17 raise RuntimeError, 'Cannot convert non-local URL to pathname'
18 # Turn starting /// into /, an empty hostname means current host
19 if url[:3] == '///':
20 url = url[2:]
21 elif url[:2] == '//':
22 raise RuntimeError, 'Cannot convert non-local URL to pathname'
23 components = string.split(url, '/')
24 if not components[0]:
25 if '$' in components:
26 del components[0]
27 else:
28 components[0] = '$'
29 # Remove . and embedded ..
30 i = 0
31 while i < len(components):
32 if components[i] == '.':
33 del components[i]
34 elif components[i] == '..' and i > 0 and \
35 components[i-1] not in ('', '..'):
36 del components[i-1:i+1]
37 i -= 1
38 elif components[i] == '..':
39 components[i] = '^'
40 i += 1
41 elif components[i] == '' and i > 0 and components[i-1] <> '':
42 del components[i]
43 else:
44 i += 1
45 components = map(lambda x: urllib.unquote(x).translate(__slash_dot), components)
46 return '.'.join(components)
48 def pathname2url(pathname):
49 "Convert a RISC OS path name to a file url."
50 return urllib.quote('///' + pathname.translate(__slash_dot), "/$:")
52 def test():
53 for url in ["index.html",
54 "/SCSI::SCSI4/$/Anwendung/Comm/Apps/!Fresco/Welcome",
55 "/SCSI::SCSI4/$/Anwendung/Comm/Apps/../!Fresco/Welcome",
56 "../index.html",
57 "bar/index.html",
58 "/foo/bar/index.html",
59 "/foo/bar/",
60 "/"]:
61 print `url`, '->', `url2pathname(url)`
62 print "*******************************************************"
63 for path in ["SCSI::SCSI4.$.Anwendung",
64 "PythonApp:Lib",
65 "PythonApp:Lib.rourl2path/py"]:
66 print `path`, '->', `pathname2url(path)`
68 if __name__ == '__main__':
69 test()