0001 """Macintosh-specific module for conversion between pathnames and URLs. 0002 0003 Do not import directly; use urllib instead.""" 0004 0005 import urllib 0006 import os 0007 0008 __all__ = ["url2pathname","pathname2url"] 0009 0010 def url2pathname(pathname): 0011 "Convert /-delimited pathname to mac pathname" 0012 # 0013 # XXXX The .. handling should be fixed... 0014 # 0015 tp = urllib.splittype(pathname)[0] 0016 if tp and tp != 'file': 0017 raise RuntimeError, 'Cannot convert non-local URL to pathname' 0018 # Turn starting /// into /, an empty hostname means current host 0019 if pathname[:3] == '///': 0020 pathname = pathname[2:] 0021 elif pathname[:2] == '//': 0022 raise RuntimeError, 'Cannot convert non-local URL to pathname' 0023 components = pathname.split('/') 0024 # Remove . and embedded .. 0025 i = 0 0026 while i < len(components): 0027 if components[i] == '.': 0028 del components[i] 0029 elif components[i] == '..' and i > 0 and \ 0030 components[i-1] not in ('', '..'): 0031 del components[i-1:i+1] 0032 i = i-1 0033 elif components[i] == '' and i > 0 and components[i-1] != '': 0034 del components[i] 0035 else: 0036 i = i+1 0037 if not components[0]: 0038 # Absolute unix path, don't start with colon 0039 rv = ':'.join(components[1:]) 0040 else: 0041 # relative unix path, start with colon. First replace 0042 # leading .. by empty strings (giving ::file) 0043 i = 0 0044 while i < len(components) and components[i] == '..': 0045 components[i] = '' 0046 i = i + 1 0047 rv = ':' + ':'.join(components) 0048 # and finally unquote slashes and other funny characters 0049 return urllib.unquote(rv) 0050 0051 def pathname2url(pathname): 0052 "convert mac pathname to /-delimited pathname" 0053 if '/' in pathname: 0054 raise RuntimeError, "Cannot convert pathname containing slashes" 0055 components = pathname.split(':') 0056 # Remove empty first and/or last component 0057 if components[0] == '': 0058 del components[0] 0059 if components[-1] == '': 0060 del components[-1] 0061 # Replace empty string ('::') by .. (will result in '/../' later) 0062 for i in range(len(components)): 0063 if components[i] == '': 0064 components[i] = '..' 0065 # Truncate names longer than 31 bytes 0066 components = map(_pncomp2url, components) 0067 0068 if os.path.isabs(pathname): 0069 return '/' + '/'.join(components) 0070 else: 0071 return '/'.join(components) 0072 0073 def _pncomp2url(component): 0074 component = urllib.quote(component[:31], safe='') # We want to quote slashes 0075 return component 0076 0077 def test(): 0078 for url in ["index.html", 0079 "bar/index.html", 0080 "/foo/bar/index.html", 0081 "/foo/bar/", 0082 "/"]: 0083 print '%r -> %r' % (url, url2pathname(url)) 0084 for path in ["drive:", 0085 "drive:dir:", 0086 "drive:dir:file", 0087 "drive:file", 0088 "file", 0089 ":file", 0090 ":dir:", 0091 ":dir:file"]: 0092 print '%r -> %r' % (path, pathname2url(path)) 0093 0094 if __name__ == '__main__': 0095 test() 0096
Generated by PyXR 0.9.4