-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathhref.py
69 lines (53 loc) · 2.13 KB
/
href.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from urlparse import urlparse
from re import match
def get_redirect(req_path, ref_url):
'''
>>> get_redirect('/style.css', 'http://preview.local/foo/bar/baz/')
'/foo/bar/baz/style.css'
>>> get_redirect('/style.css', 'http://preview.local/foo/bar/baz/quux.html')
'/foo/bar/baz/style.css'
>>> get_redirect('/quux/style.css', 'http://preview.local/foo/bar/baz/')
'/foo/bar/baz/quux/style.css'
'''
_, ref_host, ref_path, _, _, _ = urlparse(ref_url)
ref_git_preamble_match = match(r'((/[^/]+){3})', ref_path)
return ref_git_preamble_match.group(1) + req_path
def needs_redirect(req_host, req_path, ref_url):
'''
Don't redirect when the request and referer hosts don't match:
>>> needs_redirect('preview.local', '/style.css', 'http://example.com/foo/bar/baz/')
False
Don't redirect when the referer doesn't appear to include a git path.
>>> needs_redirect('preview.local', '/style.css', 'http://preview.local/about/')
False
Don't redirect when the request path already includes the git preamble.
>>> needs_redirect('preview.local', '/foo/bar/baz/style.css', 'http://preview.local/foo/bar/baz/')
False
>>> needs_redirect('preview.local', '/', 'http://preview.local/foo/bar/baz/')
True
>>> needs_redirect('preview.local', '/style.css', 'http://preview.local/foo/bar/baz/')
True
>>> needs_redirect('preview.local', '/fee/fi/fo/fum/style.css', 'http://preview.local/foo/bar/baz/')
True
'''
_, ref_host, ref_path, _, _, _ = urlparse(ref_url)
#
# Don't redirect when the request and referer hosts don't match.
#
if req_host != ref_host:
return False
ref_git_preamble_match = match(r'(/([^/]+/){3})', ref_path)
#
# Don't redirect when the referer doesn't appear to include a git path.
#
if not ref_git_preamble_match:
return False
#
# Don't redirect when the request path already includes the git preamble.
#
if req_path.startswith(ref_git_preamble_match.group(1)):
return False
return True
if __name__ == '__main__':
import doctest
doctest.testmod()