Fix compiler warning (and whitespace) on Mac OS 10.4. (A lot of this code looked...
[python.git] / Lib / nturl2path.py
blob31064044e73d7687986618ecea165a2f51bd543c
1 """Convert a NT pathname to a file URL and vice versa."""
3 def url2pathname(url):
4 """OS-specific conversion from a relative URL of the 'file' scheme
5 to a file system path; not recommended for general use."""
6 # e.g.
7 # ///C|/foo/bar/spam.foo
8 # becomes
9 # C:\foo\bar\spam.foo
10 import string, urllib
11 # Windows itself uses ":" even in URLs.
12 url = url.replace(':', '|')
13 if not '|' in url:
14 # No drive specifier, just convert slashes
15 if url[:4] == '////':
16 # path is something like ////host/path/on/remote/host
17 # convert this to \\host\path\on\remote\host
18 # (notice halving of slashes at the start of the path)
19 url = url[2:]
20 components = url.split('/')
21 # make sure not to convert quoted slashes :-)
22 return urllib.unquote('\\'.join(components))
23 comp = url.split('|')
24 if len(comp) != 2 or comp[0][-1] not in string.ascii_letters:
25 error = 'Bad URL: ' + url
26 raise IOError, error
27 drive = comp[0][-1].upper()
28 components = comp[1].split('/')
29 path = drive + ':'
30 for comp in components:
31 if comp:
32 path = path + '\\' + urllib.unquote(comp)
33 return path
35 def pathname2url(p):
36 """OS-specific conversion from a file system path to a relative URL
37 of the 'file' scheme; not recommended for general use."""
38 # e.g.
39 # C:\foo\bar\spam.foo
40 # becomes
41 # ///C|/foo/bar/spam.foo
42 import urllib
43 if not ':' in p:
44 # No drive specifier, just convert slashes and quote the name
45 if p[:2] == '\\\\':
46 # path is something like \\host\path\on\remote\host
47 # convert this to ////host/path/on/remote/host
48 # (notice doubling of slashes at the start of the path)
49 p = '\\\\' + p
50 components = p.split('\\')
51 return urllib.quote('/'.join(components))
52 comp = p.split(':')
53 if len(comp) != 2 or len(comp[0]) > 1:
54 error = 'Bad path: ' + p
55 raise IOError, error
57 drive = urllib.quote(comp[0].upper())
58 components = comp[1].split('\\')
59 path = '///' + drive + '|'
60 for comp in components:
61 if comp:
62 path = path + '/' + urllib.quote(comp)
63 return path