Debian Codegraph @

mechanize/_rfc3986.py

raw symbols SCIP
1 """RFC 3986 URI parsing and relative reference resolution / absolutization.
2
3 (aka splitting and joining)
4
5 Copyright 2006 John J. Lee <[email protected]>
6
7 This code is free software; you can redistribute it and/or modify it under
8 the terms of the BSD or ZPL 2.1 licenses (see the file LICENSE
9 included with the distribution).
10
11 """
12
13 # XXX Wow, this is ugly. Overly-direct translation of the RFC ATM.
14
15 from __future__ import absolute_import
16 import re
17
18 from .polyglot import quote
19 # def chr_range(a, b):
20 # return "".join(map(chr, range(ord(a), ord(b)+1)))
21
22 # UNRESERVED_URI_CHARS = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
23 # "abcdefghijklmnopqrstuvwxyz"
24 # "0123456789"
25 # "-_.~")
26 # RESERVED_URI_CHARS = "!*'();:@&=+$,/?#[]"
27 # URI_CHARS = RESERVED_URI_CHARS+UNRESERVED_URI_CHARS+'%'
28 # this re matches any character that's not in URI_CHARS
29 BAD_URI_CHARS_RE = re.compile(r"[^A-Za-z0-9\-_.~!*'();:@&=+$,/?%#[\]]")
30
31
32 def clean_url(url, encoding='utf-8'):
33 # percent-encode illegal URI characters
34 # Trying to come up with test cases for this gave me a headache, revisit
35 # when do switch to unicode.
36 # Somebody else's comments (lost the attribution):
37 # - IE will return you the url in the encoding you send it
38 # - Mozilla/Firefox will send you latin-1 if there's no non latin-1
39 # characters in your link. It will send you utf-8 however if there are...
40 is_unicode = not isinstance(url, bytes)
41 if not is_unicode:
42 url = url.decode(encoding, "replace")
43 url = url.strip()
44 # for second param to urllib.quote(), we want URI_CHARS, minus the
45 # 'always_safe' characters that urllib.quote() never percent-encodes
46 ans = quote(url.encode(encoding), "!*'();:@&=+$,/?%#[]~")
47 if is_unicode and isinstance(ans, bytes):
48 ans = ans.decode(encoding)
49 return ans
50
51
52 def is_clean_uri(uri):
53 """
54 >>> is_clean_uri("ABC!")
55 True
56 >>> is_clean_uri(u"ABC!")
57 True
58 >>> is_clean_uri("ABC|")
59 False
60 >>> is_clean_uri(u"ABC|")
61 False
62 >>> is_clean_uri("http://example.com/0")
63 True
64 >>> is_clean_uri(u"http://example.com/0")
65 True
66 """
67 # note module re treats bytestrings as through they were decoded as latin-1
68 # so this function accepts both unicode and bytestrings
69 return not bool(BAD_URI_CHARS_RE.search(uri))
70
71
72 SPLIT_MATCH = re.compile(
73 r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?").match
74
75
76 def urlsplit(absolute_uri):
77 """Return scheme, authority, path, query, fragment."""
78 match = SPLIT_MATCH(absolute_uri)
79 if match:
80 g = match.groups()
81 return g[1], g[3], g[4], g[6], g[8]
82
83
84 def urlunsplit(parts):
85 scheme, authority, path, query, fragment = parts
86 r = []
87 append = r.append
88 if scheme is not None:
89 append(scheme)
90 append(":")
91 if authority is not None:
92 append("//")
93 append(authority)
94 append(path)
95 if query is not None:
96 append("?")
97 append(query)
98 if fragment is not None:
99 append("#")
100 append(fragment)
101 return "".join(r)
102
103
104 def urljoin(base_uri, uri_reference):
105 """Join a base URI with a URI reference and return the resulting URI.
106
107 See RFC 3986.
108 """
109 return urlunsplit(urljoin_parts(urlsplit(base_uri),
110 urlsplit(uri_reference)))
111
112 # oops, this doesn't do the same thing as the literal translation
113 # from the RFC below
114 # import posixpath
115 # def urljoin_parts(base_parts, reference_parts):
116 # scheme, authority, path, query, fragment = base_parts
117 # rscheme, rauthority, rpath, rquery, rfragment = reference_parts
118
119 # compute target URI path
120 # if rpath == "":
121 # tpath = path
122 # else:
123 # tpath = rpath
124 # if not tpath.startswith("/"):
125 # tpath = merge(authority, path, tpath)
126 # tpath = posixpath.normpath(tpath)
127
128 # if rscheme is not None:
129 # return (rscheme, rauthority, tpath, rquery, rfragment)
130 # elif rauthority is not None:
131 # return (scheme, rauthority, tpath, rquery, rfragment)
132 # elif rpath == "":
133 # if rquery is not None:
134 # tquery = rquery
135 # else:
136 # tquery = query
137 # return (scheme, authority, tpath, tquery, rfragment)
138 # else:
139 # return (scheme, authority, tpath, rquery, rfragment)
140
141
142 def urljoin_parts(base_parts, reference_parts):
143 scheme, authority, path, query, fragment = base_parts
144 rscheme, rauthority, rpath, rquery, rfragment = reference_parts
145
146 if rscheme == scheme:
147 rscheme = None
148
149 if rscheme is not None:
150 tscheme, tauthority, tpath, tquery = (
151 rscheme, rauthority, remove_dot_segments(rpath), rquery)
152 else:
153 if rauthority is not None:
154 tauthority, tpath, tquery = (
155 rauthority, remove_dot_segments(rpath), rquery)
156 else:
157 if rpath == "":
158 tpath = path
159 if rquery is not None:
160 tquery = rquery
161 else:
162 tquery = query
163 else:
164 if rpath.startswith("/"):
165 tpath = remove_dot_segments(rpath)
166 else:
167 tpath = merge(authority, path, rpath)
168 tpath = remove_dot_segments(tpath)
169 tquery = rquery
170 tauthority = authority
171 tscheme = scheme
172 tfragment = rfragment
173 return (tscheme, tauthority, tpath, tquery, tfragment)
174
175 # um, something *vaguely* like this is what I want, but I have to generate
176 # lots of test cases first, if only to understand what it is that
177 # remove_dot_segments really does...
178 # def remove_dot_segments(path):
179 # if path == '':
180 # return ''
181 # comps = path.split('/')
182 # new_comps = []
183 # for comp in comps:
184 # if comp in ['.', '']:
185 # if not new_comps or new_comps[-1]:
186 # new_comps.append('')
187 # continue
188 # if comp != '..':
189 # new_comps.append(comp)
190 # elif new_comps:
191 # new_comps.pop()
192 # return '/'.join(new_comps)
193
194
195 def remove_dot_segments(path):
196 r = []
197 while path:
198 # A
199 if path.startswith("../"):
200 path = path[3:]
201 continue
202 if path.startswith("./"):
203 path = path[2:]
204 continue
205 # B
206 if path.startswith("/./"):
207 path = path[2:]
208 continue
209 if path == "/.":
210 path = "/"
211 continue
212 # C
213 if path.startswith("/../"):
214 path = path[3:]
215 if r:
216 r.pop()
217 continue
218 if path == "/..":
219 path = "/"
220 if r:
221 r.pop()
222 continue
223 # D
224 if path == ".":
225 path = path[1:]
226 continue
227 if path == "..":
228 path = path[2:]
229 continue
230 # E
231 start = 0
232 if path.startswith("/"):
233 start = 1
234 ii = path.find("/", start)
235 if ii < 0:
236 ii = None
237 r.append(path[:ii])
238 if ii is None:
239 break
240 path = path[ii:]
241 return "".join(r)
242
243
244 def merge(base_authority, base_path, ref_path):
245 # XXXX Oddly, the sample Perl implementation of this by Roy Fielding
246 # doesn't even take base_authority as a parameter, despite the wording in
247 # the RFC suggesting otherwise. Perhaps I'm missing some obvious identity.
248 # if base_authority is not None and base_path == "":
249 if base_path == "":
250 return "/" + ref_path
251 ii = base_path.rfind("/")
252 if ii >= 0:
253 return base_path[:ii + 1] + ref_path
254 return ref_path
255
256
257 if __name__ == "__main__":
258 import doctest
259 doctest.testmod()