Guido van Rossum | 5c97167 | 1996-07-22 15:23:25 +0000 | [diff] [blame] | 1 | """Mac specific module for conversion between pathnames and URLs.""" |
| 2 | |
| 3 | import string |
| 4 | import urllib |
| 5 | import os |
| 6 | |
| 7 | def url2pathname(pathname): |
| 8 | "Convert /-delimited pathname to mac pathname" |
| 9 | # |
| 10 | # XXXX The .. handling should be fixed... |
| 11 | # |
| 12 | tp = urllib.splittype(pathname)[0] |
| 13 | if tp and tp <> 'file': |
| 14 | raise RuntimeError, 'Cannot convert non-local URL to pathname' |
| 15 | components = string.split(pathname, '/') |
| 16 | # Remove . and embedded .. |
| 17 | i = 0 |
| 18 | while i < len(components): |
| 19 | if components[i] == '.': |
| 20 | del components[i] |
| 21 | elif components[i] == '..' and i > 0 and \ |
| 22 | components[i-1] not in ('', '..'): |
| 23 | del components[i-1:i+1] |
| 24 | i = i-1 |
| 25 | elif components[i] == '' and i > 0 and components[i-1] <> '': |
| 26 | del components[i] |
| 27 | else: |
| 28 | i = i+1 |
| 29 | if not components[0]: |
| 30 | # Absolute unix path, don't start with colon |
| 31 | return string.join(components[1:], ':') |
| 32 | else: |
| 33 | # relative unix path, start with colon. First replace |
| 34 | # leading .. by empty strings (giving ::file) |
| 35 | i = 0 |
| 36 | while i < len(components) and components[i] == '..': |
| 37 | components[i] = '' |
| 38 | i = i + 1 |
| 39 | return ':' + string.join(components, ':') |
| 40 | |
| 41 | def pathname2url(pathname): |
| 42 | "convert mac pathname to /-delimited pathname" |
| 43 | if '/' in pathname: |
| 44 | raise RuntimeError, "Cannot convert pathname containing slashes" |
| 45 | components = string.split(pathname, ':') |
| 46 | # Replace empty string ('::') by .. (will result in '/../' later) |
| 47 | for i in range(1, len(components)): |
| 48 | if components[i] == '': |
| 49 | components[i] = '..' |
| 50 | # Truncate names longer than 31 bytes |
| 51 | components = map(lambda x: x[:31], components) |
| 52 | |
| 53 | if os.path.isabs(pathname): |
| 54 | return '/' + string.join(components, '/') |
| 55 | else: |
| 56 | return string.join(components, '/') |
| 57 | |
| 58 | def test(): |
| 59 | for url in ["index.html", |
| 60 | "bar/index.html", |
| 61 | "/foo/bar/index.html", |
| 62 | "/foo/bar/", |
| 63 | "/"]: |
| 64 | print `url`, '->', `url2pathname(url)` |
| 65 | for path in ["drive:", |
| 66 | "drive:dir:", |
| 67 | "drive:dir:file", |
| 68 | "drive:file", |
| 69 | "file", |
| 70 | ":file", |
| 71 | ":dir:", |
| 72 | ":dir:file"]: |
| 73 | print `path`, '->', `pathname2url(path)` |
| 74 | |
| 75 | if __name__ == '__main__': |
| 76 | test() |