forked from graalvm/mx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mx_urlrewrites.py
163 lines (139 loc) · 5.87 KB
/
mx_urlrewrites.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#
# ----------------------------------------------------------------------------------------------------
#
# Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# ----------------------------------------------------------------------------------------------------
from __future__ import print_function
import re
import json
import mx
_urlrewrites = [] # list of URLRewrite objects
def register_urlrewrite(urlrewrite, onError=None):
"""
Appends a URL rewrite rule to the current rewrite rules.
A URL rewrite rule is a dict where the key is a regex for matching a URL and the value describes
how to rewrite.
:Example:
{
"https://git.acme.com/(.*).git" : {
"replacement" : "https://my.company.com/foo-git-cache/\1.git",
}
}
:param urlrewrite: a URL rewrite rule
:type urlrewrite: dict or URLRewrite
:param function onError: called with error message argument if urlwrewrite is badly formed
"""
if onError is None:
def _error(msg):
raise Exception(msg)
onError = _error
if isinstance(urlrewrite, URLRewrite):
_urlrewrites.append(urlrewrite)
return
if not isinstance(urlrewrite, dict) or len(urlrewrite) != 1:
onError('A URL rewrite rule must be a dict with a single entry')
for pattern, attrs in urlrewrite.items():
replacement = attrs.pop('replacement', None)
if replacement is None:
raise Exception('URL rewrite for pattern "' + pattern + '" is missing "replacement" entry')
if len(attrs) != 0:
raise Exception('Unsupported attributes found for URL rewrite "' + pattern + '": ' + str(attrs))
try:
pattern = re.compile(pattern)
except Exception as e: # pylint: disable=broad-except
onError('Error parsing URL rewrite pattern "' + pattern + '": ' + str(e))
urlrewrite = URLRewrite(pattern, str(replacement))
mx.logvv("Registering url rewrite: " + str(urlrewrite))
_urlrewrites.append(urlrewrite)
def register_urlrewrites_from_env(name):
"""
Appends rewrite rules denoted by the environment variable named by `name`.
If the environment variable has a non-empty value it must either be an JSON
object describing a single rewrite rule, a JSON array describing a list of
rewrite rules or a file containing one of these JSON values.
:param str name: name of an environment variable denoting URL rewrite rules
"""
value = mx.get_env(name, None)
if value:
def raiseError(msg):
raise Exception('Error processing URL rewrite rules denoted by environment variable ' + name + ':\n' + msg)
value = value.strip()
if value[0] not in '{[':
with open(value) as fp:
jsonValue = fp.read().strip()
else:
jsonValue = value
def loadJson(jsonValue):
try:
return json.loads(jsonValue)
except ValueError as e:
raise Exception('Error parsing JSON object denoted by ' + name + ' environment variable:\n' + str(e))
if jsonValue:
rewrites = loadJson(jsonValue) # JSON root is always either list or dict
if isinstance(rewrites, dict):
rewrites = [rewrites]
for rewrite in rewrites:
register_urlrewrite(rewrite, raiseError)
def rewriteurl(url):
"""
Finds the first registered URL rewrite rule that matches `url` and returns the replacement
provided by the rule.
:param str url: a URL to match against the registered rerwrite rules
:return: the value of `url` rewritten according to the first matching rewrite URL or unmodified
if no rules match
:rtype: str
"""
original_url = url
jar_url = mx._JarURL.parse(url)
if jar_url:
url = jar_url.base_url
for urlrewrite in _urlrewrites:
res = urlrewrite._rewrite(url)
if res:
if jar_url is not None:
jar_url.base_url = res
res = str(jar_url)
mx.logvv("Rewrote '{}' to '{}'".format(original_url, res))
return res
return original_url
def urlrewrite_cli(args):
"""rewrites the given URL using MX_URLREWRITES"""
assert len(args) == 1
print(rewriteurl(args[0]))
class URLRewrite(object):
"""
Represents a regular expression based rewrite rule that can be applied to a URL.
:param :class:`re.RegexObject` pattern: a regular expression for matching URLs
:param str replacement: the replacement to use for a URL matched by `pattern`
"""
def __init__(self, pattern, replacement):
self.pattern = pattern
self.replacement = replacement
def _rewrite(self, url):
match = self.pattern.match(url)
if match:
return self.pattern.sub(self.replacement, url)
else:
return None
def __str__(self):
return self.pattern.pattern + ' -> ' + self.replacement