Show More
@@ -1,58 +1,58 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
|
2 | |||
3 | # Copyright (C) 2016-2020 RhodeCode GmbH |
|
3 | # Copyright (C) 2016-2020 RhodeCode GmbH | |
4 | # |
|
4 | # | |
5 | # This program is free software: you can redistribute it and/or modify |
|
5 | # This program is free software: you can redistribute it and/or modify | |
6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
6 | # it under the terms of the GNU Affero General Public License, version 3 | |
7 | # (only), as published by the Free Software Foundation. |
|
7 | # (only), as published by the Free Software Foundation. | |
8 | # |
|
8 | # | |
9 | # This program is distributed in the hope that it will be useful, |
|
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. |
|
12 | # GNU General Public License for more details. | |
13 | # |
|
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License |
|
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | # |
|
16 | # | |
17 | # This program is dual-licensed. If you wish to learn more about the |
|
17 | # This program is dual-licensed. If you wish to learn more about the | |
18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |
20 |
|
20 | |||
21 |
|
21 | |||
22 | import uuid |
|
22 | import uuid | |
23 | import StringIO |
|
23 | from io import StringIO | |
24 | import pathlib2 |
|
24 | import pathlib2 | |
25 |
|
25 | |||
26 |
|
26 | |||
27 | def get_file_storage(settings): |
|
27 | def get_file_storage(settings): | |
28 | from rhodecode.apps.file_store.backends.local_store import LocalFileStorage |
|
28 | from rhodecode.apps.file_store.backends.local_store import LocalFileStorage | |
29 | from rhodecode.apps.file_store import config_keys |
|
29 | from rhodecode.apps.file_store import config_keys | |
30 | store_path = settings.get(config_keys.store_path) |
|
30 | store_path = settings.get(config_keys.store_path) | |
31 | return LocalFileStorage(base_path=store_path) |
|
31 | return LocalFileStorage(base_path=store_path) | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | def splitext(filename): |
|
34 | def splitext(filename): | |
35 | ext = ''.join(pathlib2.Path(filename).suffixes) |
|
35 | ext = ''.join(pathlib2.Path(filename).suffixes) | |
36 | return filename, ext |
|
36 | return filename, ext | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | def uid_filename(filename, randomized=True): |
|
39 | def uid_filename(filename, randomized=True): | |
40 | """ |
|
40 | """ | |
41 | Generates a randomized or stable (uuid) filename, |
|
41 | Generates a randomized or stable (uuid) filename, | |
42 | preserving the original extension. |
|
42 | preserving the original extension. | |
43 |
|
43 | |||
44 | :param filename: the original filename |
|
44 | :param filename: the original filename | |
45 | :param randomized: define if filename should be stable (sha1 based) or randomized |
|
45 | :param randomized: define if filename should be stable (sha1 based) or randomized | |
46 | """ |
|
46 | """ | |
47 |
|
47 | |||
48 | _, ext = splitext(filename) |
|
48 | _, ext = splitext(filename) | |
49 | if randomized: |
|
49 | if randomized: | |
50 | uid = uuid.uuid4() |
|
50 | uid = uuid.uuid4() | |
51 | else: |
|
51 | else: | |
52 | hash_key = '{}.{}'.format(filename, 'store') |
|
52 | hash_key = '{}.{}'.format(filename, 'store') | |
53 | uid = uuid.uuid5(uuid.NAMESPACE_URL, hash_key) |
|
53 | uid = uuid.uuid5(uuid.NAMESPACE_URL, hash_key) | |
54 | return str(uid) + ext.lower() |
|
54 | return str(uid) + ext.lower() | |
55 |
|
55 | |||
56 |
|
56 | |||
57 | def bytes_to_file_obj(bytes_data): |
|
57 | def bytes_to_file_obj(bytes_data): | |
58 | return StringIO.StringIO(bytes_data) |
|
58 | return StringIO.StringIO(bytes_data) |
@@ -1,839 +1,839 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Utilities for writing code that runs on Python 2 and 3""" |
|
2 | """Utilities for writing code that runs on Python 2 and 3""" | |
3 |
|
3 | |||
4 | # Copyright (c) 2010-2015 Benjamin Peterson |
|
4 | # Copyright (c) 2010-2015 Benjamin Peterson | |
5 | # |
|
5 | # | |
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy |
|
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy | |
7 | # of this software and associated documentation files (the "Software"), to deal |
|
7 | # of this software and associated documentation files (the "Software"), to deal | |
8 | # in the Software without restriction, including without limitation the rights |
|
8 | # in the Software without restriction, including without limitation the rights | |
9 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
|
9 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
10 | # copies of the Software, and to permit persons to whom the Software is |
|
10 | # copies of the Software, and to permit persons to whom the Software is | |
11 | # furnished to do so, subject to the following conditions: |
|
11 | # furnished to do so, subject to the following conditions: | |
12 | # |
|
12 | # | |
13 | # The above copyright notice and this permission notice shall be included in all |
|
13 | # The above copyright notice and this permission notice shall be included in all | |
14 | # copies or substantial portions of the Software. |
|
14 | # copies or substantial portions of the Software. | |
15 | # |
|
15 | # | |
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
18 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|
18 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
19 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|
19 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
20 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
|
20 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
21 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
|
21 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
22 | # SOFTWARE. |
|
22 | # SOFTWARE. | |
23 |
|
23 | |||
24 |
|
24 | |||
25 |
|
25 | |||
26 | import functools |
|
26 | import functools | |
27 | import itertools |
|
27 | import itertools | |
28 | import operator |
|
28 | import operator | |
29 | import sys |
|
29 | import sys | |
30 | import types |
|
30 | import types | |
31 |
|
31 | |||
32 | __author__ = "Benjamin Peterson <benjamin@python.org>" |
|
32 | __author__ = "Benjamin Peterson <benjamin@python.org>" | |
33 | __version__ = "1.9.0" |
|
33 | __version__ = "1.9.0" | |
34 |
|
34 | |||
35 |
|
35 | |||
36 | # Useful for very coarse version differentiation. |
|
36 | # Useful for very coarse version differentiation. | |
37 | PY2 = sys.version_info[0] == 2 |
|
37 | PY2 = sys.version_info[0] == 2 | |
38 | PY3 = sys.version_info[0] == 3 |
|
38 | PY3 = sys.version_info[0] == 3 | |
39 |
|
39 | |||
40 | if PY3: |
|
40 | if PY3: | |
41 | string_types = str, |
|
41 | string_types = str, | |
42 | integer_types = int, |
|
42 | integer_types = int, | |
43 | class_types = type, |
|
43 | class_types = type, | |
44 | text_type = str |
|
44 | text_type = str | |
45 | binary_type = bytes |
|
45 | binary_type = bytes | |
46 |
|
46 | |||
47 | MAXSIZE = sys.maxsize |
|
47 | MAXSIZE = sys.maxsize | |
48 | else: |
|
48 | else: | |
49 | string_types = str, |
|
49 | string_types = str, | |
50 | integer_types = (int, long) |
|
50 | integer_types = (int, long) | |
51 | class_types = (type, types.ClassType) |
|
51 | class_types = (type, types.ClassType) | |
52 | text_type = unicode |
|
52 | text_type = unicode | |
53 | binary_type = str |
|
53 | binary_type = str | |
54 |
|
54 | |||
55 | if sys.platform.startswith("java"): |
|
55 | if sys.platform.startswith("java"): | |
56 | # Jython always uses 32 bits. |
|
56 | # Jython always uses 32 bits. | |
57 | MAXSIZE = int((1 << 31) - 1) |
|
57 | MAXSIZE = int((1 << 31) - 1) | |
58 | else: |
|
58 | else: | |
59 | # It's possible to have sizeof(long) != sizeof(Py_ssize_t). |
|
59 | # It's possible to have sizeof(long) != sizeof(Py_ssize_t). | |
60 | class X(object): |
|
60 | class X(object): | |
61 | def __len__(self): |
|
61 | def __len__(self): | |
62 | return 1 << 31 |
|
62 | return 1 << 31 | |
63 | try: |
|
63 | try: | |
64 | len(X()) |
|
64 | len(X()) | |
65 | except OverflowError: |
|
65 | except OverflowError: | |
66 | # 32-bit |
|
66 | # 32-bit | |
67 | MAXSIZE = int((1 << 31) - 1) |
|
67 | MAXSIZE = int((1 << 31) - 1) | |
68 | else: |
|
68 | else: | |
69 | # 64-bit |
|
69 | # 64-bit | |
70 | MAXSIZE = int((1 << 63) - 1) |
|
70 | MAXSIZE = int((1 << 63) - 1) | |
71 | del X |
|
71 | del X | |
72 |
|
72 | |||
73 |
|
73 | |||
74 | def _add_doc(func, doc): |
|
74 | def _add_doc(func, doc): | |
75 | """Add documentation to a function.""" |
|
75 | """Add documentation to a function.""" | |
76 | func.__doc__ = doc |
|
76 | func.__doc__ = doc | |
77 |
|
77 | |||
78 |
|
78 | |||
79 | def _import_module(name): |
|
79 | def _import_module(name): | |
80 | """Import module, returning the module after the last dot.""" |
|
80 | """Import module, returning the module after the last dot.""" | |
81 | __import__(name) |
|
81 | __import__(name) | |
82 | return sys.modules[name] |
|
82 | return sys.modules[name] | |
83 |
|
83 | |||
84 |
|
84 | |||
85 | class _LazyDescr(object): |
|
85 | class _LazyDescr(object): | |
86 |
|
86 | |||
87 | def __init__(self, name): |
|
87 | def __init__(self, name): | |
88 | self.name = name |
|
88 | self.name = name | |
89 |
|
89 | |||
90 | def __get__(self, obj, tp): |
|
90 | def __get__(self, obj, tp): | |
91 | result = self._resolve() |
|
91 | result = self._resolve() | |
92 | setattr(obj, self.name, result) # Invokes __set__. |
|
92 | setattr(obj, self.name, result) # Invokes __set__. | |
93 | try: |
|
93 | try: | |
94 | # This is a bit ugly, but it avoids running this again by |
|
94 | # This is a bit ugly, but it avoids running this again by | |
95 | # removing this descriptor. |
|
95 | # removing this descriptor. | |
96 | delattr(obj.__class__, self.name) |
|
96 | delattr(obj.__class__, self.name) | |
97 | except AttributeError: |
|
97 | except AttributeError: | |
98 | pass |
|
98 | pass | |
99 | return result |
|
99 | return result | |
100 |
|
100 | |||
101 |
|
101 | |||
102 | class MovedModule(_LazyDescr): |
|
102 | class MovedModule(_LazyDescr): | |
103 |
|
103 | |||
104 | def __init__(self, name, old, new=None): |
|
104 | def __init__(self, name, old, new=None): | |
105 | super(MovedModule, self).__init__(name) |
|
105 | super(MovedModule, self).__init__(name) | |
106 | if PY3: |
|
106 | if PY3: | |
107 | if new is None: |
|
107 | if new is None: | |
108 | new = name |
|
108 | new = name | |
109 | self.mod = new |
|
109 | self.mod = new | |
110 | else: |
|
110 | else: | |
111 | self.mod = old |
|
111 | self.mod = old | |
112 |
|
112 | |||
113 | def _resolve(self): |
|
113 | def _resolve(self): | |
114 | return _import_module(self.mod) |
|
114 | return _import_module(self.mod) | |
115 |
|
115 | |||
116 | def __getattr__(self, attr): |
|
116 | def __getattr__(self, attr): | |
117 | _module = self._resolve() |
|
117 | _module = self._resolve() | |
118 | value = getattr(_module, attr) |
|
118 | value = getattr(_module, attr) | |
119 | setattr(self, attr, value) |
|
119 | setattr(self, attr, value) | |
120 | return value |
|
120 | return value | |
121 |
|
121 | |||
122 |
|
122 | |||
123 | class _LazyModule(types.ModuleType): |
|
123 | class _LazyModule(types.ModuleType): | |
124 |
|
124 | |||
125 | def __init__(self, name): |
|
125 | def __init__(self, name): | |
126 | super(_LazyModule, self).__init__(name) |
|
126 | super(_LazyModule, self).__init__(name) | |
127 | self.__doc__ = self.__class__.__doc__ |
|
127 | self.__doc__ = self.__class__.__doc__ | |
128 |
|
128 | |||
129 | def __dir__(self): |
|
129 | def __dir__(self): | |
130 | attrs = ["__doc__", "__name__"] |
|
130 | attrs = ["__doc__", "__name__"] | |
131 | attrs += [attr.name for attr in self._moved_attributes] |
|
131 | attrs += [attr.name for attr in self._moved_attributes] | |
132 | return attrs |
|
132 | return attrs | |
133 |
|
133 | |||
134 | # Subclasses should override this |
|
134 | # Subclasses should override this | |
135 | _moved_attributes = [] |
|
135 | _moved_attributes = [] | |
136 |
|
136 | |||
137 |
|
137 | |||
138 | class MovedAttribute(_LazyDescr): |
|
138 | class MovedAttribute(_LazyDescr): | |
139 |
|
139 | |||
140 | def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): |
|
140 | def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): | |
141 | super(MovedAttribute, self).__init__(name) |
|
141 | super(MovedAttribute, self).__init__(name) | |
142 | if PY3: |
|
142 | if PY3: | |
143 | if new_mod is None: |
|
143 | if new_mod is None: | |
144 | new_mod = name |
|
144 | new_mod = name | |
145 | self.mod = new_mod |
|
145 | self.mod = new_mod | |
146 | if new_attr is None: |
|
146 | if new_attr is None: | |
147 | if old_attr is None: |
|
147 | if old_attr is None: | |
148 | new_attr = name |
|
148 | new_attr = name | |
149 | else: |
|
149 | else: | |
150 | new_attr = old_attr |
|
150 | new_attr = old_attr | |
151 | self.attr = new_attr |
|
151 | self.attr = new_attr | |
152 | else: |
|
152 | else: | |
153 | self.mod = old_mod |
|
153 | self.mod = old_mod | |
154 | if old_attr is None: |
|
154 | if old_attr is None: | |
155 | old_attr = name |
|
155 | old_attr = name | |
156 | self.attr = old_attr |
|
156 | self.attr = old_attr | |
157 |
|
157 | |||
158 | def _resolve(self): |
|
158 | def _resolve(self): | |
159 | module = _import_module(self.mod) |
|
159 | module = _import_module(self.mod) | |
160 | return getattr(module, self.attr) |
|
160 | return getattr(module, self.attr) | |
161 |
|
161 | |||
162 |
|
162 | |||
163 | class _SixMetaPathImporter(object): |
|
163 | class _SixMetaPathImporter(object): | |
164 | """ |
|
164 | """ | |
165 | A meta path importer to import six.moves and its submodules. |
|
165 | A meta path importer to import six.moves and its submodules. | |
166 |
|
166 | |||
167 | This class implements a PEP302 finder and loader. It should be compatible |
|
167 | This class implements a PEP302 finder and loader. It should be compatible | |
168 | with Python 2.5 and all existing versions of Python3 |
|
168 | with Python 2.5 and all existing versions of Python3 | |
169 | """ |
|
169 | """ | |
170 | def __init__(self, six_module_name): |
|
170 | def __init__(self, six_module_name): | |
171 | self.name = six_module_name |
|
171 | self.name = six_module_name | |
172 | self.known_modules = {} |
|
172 | self.known_modules = {} | |
173 |
|
173 | |||
174 | def _add_module(self, mod, *fullnames): |
|
174 | def _add_module(self, mod, *fullnames): | |
175 | for fullname in fullnames: |
|
175 | for fullname in fullnames: | |
176 | self.known_modules[self.name + "." + fullname] = mod |
|
176 | self.known_modules[self.name + "." + fullname] = mod | |
177 |
|
177 | |||
178 | def _get_module(self, fullname): |
|
178 | def _get_module(self, fullname): | |
179 | return self.known_modules[self.name + "." + fullname] |
|
179 | return self.known_modules[self.name + "." + fullname] | |
180 |
|
180 | |||
181 | def find_module(self, fullname, path=None): |
|
181 | def find_module(self, fullname, path=None): | |
182 | if fullname in self.known_modules: |
|
182 | if fullname in self.known_modules: | |
183 | return self |
|
183 | return self | |
184 | return None |
|
184 | return None | |
185 |
|
185 | |||
186 | def __get_module(self, fullname): |
|
186 | def __get_module(self, fullname): | |
187 | try: |
|
187 | try: | |
188 | return self.known_modules[fullname] |
|
188 | return self.known_modules[fullname] | |
189 | except KeyError: |
|
189 | except KeyError: | |
190 | raise ImportError("This loader does not know module " + fullname) |
|
190 | raise ImportError("This loader does not know module " + fullname) | |
191 |
|
191 | |||
192 | def load_module(self, fullname): |
|
192 | def load_module(self, fullname): | |
193 | try: |
|
193 | try: | |
194 | # in case of a reload |
|
194 | # in case of a reload | |
195 | return sys.modules[fullname] |
|
195 | return sys.modules[fullname] | |
196 | except KeyError: |
|
196 | except KeyError: | |
197 | pass |
|
197 | pass | |
198 | mod = self.__get_module(fullname) |
|
198 | mod = self.__get_module(fullname) | |
199 | if isinstance(mod, MovedModule): |
|
199 | if isinstance(mod, MovedModule): | |
200 | mod = mod._resolve() |
|
200 | mod = mod._resolve() | |
201 | else: |
|
201 | else: | |
202 | mod.__loader__ = self |
|
202 | mod.__loader__ = self | |
203 | sys.modules[fullname] = mod |
|
203 | sys.modules[fullname] = mod | |
204 | return mod |
|
204 | return mod | |
205 |
|
205 | |||
206 | def is_package(self, fullname): |
|
206 | def is_package(self, fullname): | |
207 | """ |
|
207 | """ | |
208 | Return true, if the named module is a package. |
|
208 | Return true, if the named module is a package. | |
209 |
|
209 | |||
210 | We need this method to get correct spec objects with |
|
210 | We need this method to get correct spec objects with | |
211 | Python 3.4 (see PEP451) |
|
211 | Python 3.4 (see PEP451) | |
212 | """ |
|
212 | """ | |
213 | return hasattr(self.__get_module(fullname), "__path__") |
|
213 | return hasattr(self.__get_module(fullname), "__path__") | |
214 |
|
214 | |||
215 | def get_code(self, fullname): |
|
215 | def get_code(self, fullname): | |
216 | """Return None |
|
216 | """Return None | |
217 |
|
217 | |||
218 | Required, if is_package is implemented""" |
|
218 | Required, if is_package is implemented""" | |
219 | self.__get_module(fullname) # eventually raises ImportError |
|
219 | self.__get_module(fullname) # eventually raises ImportError | |
220 | return None |
|
220 | return None | |
221 | get_source = get_code # same as get_code |
|
221 | get_source = get_code # same as get_code | |
222 |
|
222 | |||
223 | _importer = _SixMetaPathImporter(__name__) |
|
223 | _importer = _SixMetaPathImporter(__name__) | |
224 |
|
224 | |||
225 |
|
225 | |||
226 | class _MovedItems(_LazyModule): |
|
226 | class _MovedItems(_LazyModule): | |
227 | """Lazy loading of moved objects""" |
|
227 | """Lazy loading of moved objects""" | |
228 | __path__ = [] # mark as package |
|
228 | __path__ = [] # mark as package | |
229 |
|
229 | |||
230 |
|
230 | |||
231 | _moved_attributes = [ |
|
231 | _moved_attributes = [ | |
232 | MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), |
|
232 | MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), | |
233 | MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), |
|
233 | MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), | |
234 | MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), |
|
234 | MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), | |
235 | MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), |
|
235 | MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), | |
236 | MovedAttribute("intern", "__builtin__", "sys"), |
|
236 | MovedAttribute("intern", "__builtin__", "sys"), | |
237 | MovedAttribute("map", "itertools", "builtins", "imap", "map"), |
|
237 | MovedAttribute("map", "itertools", "builtins", "imap", "map"), | |
238 | MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), |
|
238 | MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), | |
239 | MovedAttribute("reload_module", "__builtin__", "imp", "reload"), |
|
239 | MovedAttribute("reload_module", "__builtin__", "imp", "reload"), | |
240 | MovedAttribute("reduce", "__builtin__", "functools"), |
|
240 | MovedAttribute("reduce", "__builtin__", "functools"), | |
241 | MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), |
|
241 | MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), | |
242 | MovedAttribute("StringIO", "StringIO", "io"), |
|
242 | MovedAttribute("StringIO", "StringIO", "io"), | |
243 | MovedAttribute("UserDict", "UserDict", "collections"), |
|
243 | MovedAttribute("UserDict", "UserDict", "collections"), | |
244 | MovedAttribute("UserList", "UserList", "collections"), |
|
244 | MovedAttribute("UserList", "UserList", "collections"), | |
245 | MovedAttribute("UserString", "UserString", "collections"), |
|
245 | MovedAttribute("UserString", "UserString", "collections"), | |
246 | MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), |
|
246 | MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), | |
247 | MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), |
|
247 | MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), | |
248 | MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), |
|
248 | MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), | |
249 |
|
249 | |||
250 | MovedModule("builtins", "__builtin__"), |
|
250 | MovedModule("builtins", "__builtin__"), | |
251 | MovedModule("configparser", "ConfigParser"), |
|
251 | MovedModule("configparser", "ConfigParser"), | |
252 | MovedModule("copyreg", "copy_reg"), |
|
252 | MovedModule("copyreg", "copy_reg"), | |
253 | MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), |
|
253 | MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), | |
254 | MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), |
|
254 | MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), | |
255 | MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), |
|
255 | MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), | |
256 | MovedModule("http_cookies", "Cookie", "http.cookies"), |
|
256 | MovedModule("http_cookies", "Cookie", "http.cookies"), | |
257 | MovedModule("html_entities", "htmlentitydefs", "html.entities"), |
|
257 | MovedModule("html_entities", "htmlentitydefs", "html.entities"), | |
258 | MovedModule("html_parser", "HTMLParser", "html.parser"), |
|
258 | MovedModule("html_parser", "HTMLParser", "html.parser"), | |
259 | MovedModule("http_client", "httplib", "http.client"), |
|
259 | MovedModule("http_client", "httplib", "http.client"), | |
260 | MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), |
|
260 | MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), | |
261 | MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), |
|
261 | MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), | |
262 | MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), |
|
262 | MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), | |
263 | MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), |
|
263 | MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), | |
264 | MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), |
|
264 | MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), | |
265 | MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), |
|
265 | MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), | |
266 | MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), |
|
266 | MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), | |
267 | MovedModule("cPickle", "cPickle", "pickle"), |
|
267 | MovedModule("cPickle", "cPickle", "pickle"), | |
268 | MovedModule("queue", "Queue"), |
|
268 | MovedModule("queue", "Queue"), | |
269 | MovedModule("reprlib", "repr"), |
|
269 | MovedModule("reprlib", "repr"), | |
270 | MovedModule("socketserver", "SocketServer"), |
|
270 | MovedModule("socketserver", "SocketServer"), | |
271 | MovedModule("_thread", "thread", "_thread"), |
|
271 | MovedModule("_thread", "thread", "_thread"), | |
272 | MovedModule("tkinter", "Tkinter"), |
|
272 | MovedModule("tkinter", "Tkinter"), | |
273 | MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), |
|
273 | MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), | |
274 | MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), |
|
274 | MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), | |
275 | MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), |
|
275 | MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), | |
276 | MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), |
|
276 | MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), | |
277 | MovedModule("tkinter_tix", "Tix", "tkinter.tix"), |
|
277 | MovedModule("tkinter_tix", "Tix", "tkinter.tix"), | |
278 | MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), |
|
278 | MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), | |
279 | MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), |
|
279 | MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), | |
280 | MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), |
|
280 | MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), | |
281 | MovedModule("tkinter_colorchooser", "tkColorChooser", |
|
281 | MovedModule("tkinter_colorchooser", "tkColorChooser", | |
282 | "tkinter.colorchooser"), |
|
282 | "tkinter.colorchooser"), | |
283 | MovedModule("tkinter_commondialog", "tkCommonDialog", |
|
283 | MovedModule("tkinter_commondialog", "tkCommonDialog", | |
284 | "tkinter.commondialog"), |
|
284 | "tkinter.commondialog"), | |
285 | MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), |
|
285 | MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), | |
286 | MovedModule("tkinter_font", "tkFont", "tkinter.font"), |
|
286 | MovedModule("tkinter_font", "tkFont", "tkinter.font"), | |
287 | MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), |
|
287 | MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), | |
288 | MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", |
|
288 | MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", | |
289 | "tkinter.simpledialog"), |
|
289 | "tkinter.simpledialog"), | |
290 | MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), |
|
290 | MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), | |
291 | MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), |
|
291 | MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), | |
292 | MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), |
|
292 | MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), | |
293 | MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), |
|
293 | MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), | |
294 | MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), |
|
294 | MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), | |
295 | MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), |
|
295 | MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), | |
296 | MovedModule("winreg", "_winreg"), |
|
296 | MovedModule("winreg", "_winreg"), | |
297 | ] |
|
297 | ] | |
298 | for attr in _moved_attributes: |
|
298 | for attr in _moved_attributes: | |
299 | setattr(_MovedItems, attr.name, attr) |
|
299 | setattr(_MovedItems, attr.name, attr) | |
300 | if isinstance(attr, MovedModule): |
|
300 | if isinstance(attr, MovedModule): | |
301 | _importer._add_module(attr, "moves." + attr.name) |
|
301 | _importer._add_module(attr, "moves." + attr.name) | |
302 | del attr |
|
302 | del attr | |
303 |
|
303 | |||
304 | _MovedItems._moved_attributes = _moved_attributes |
|
304 | _MovedItems._moved_attributes = _moved_attributes | |
305 |
|
305 | |||
306 | moves = _MovedItems(__name__ + ".moves") |
|
306 | moves = _MovedItems(__name__ + ".moves") | |
307 | _importer._add_module(moves, "moves") |
|
307 | _importer._add_module(moves, "moves") | |
308 |
|
308 | |||
309 |
|
309 | |||
310 | class Module_six_moves_urllib_parse(_LazyModule): |
|
310 | class Module_six_moves_urllib_parse(_LazyModule): | |
311 | """Lazy loading of moved objects in six.moves.urllib_parse""" |
|
311 | """Lazy loading of moved objects in six.moves.urllib_parse""" | |
312 |
|
312 | |||
313 |
|
313 | |||
314 | _urllib_parse_moved_attributes = [ |
|
314 | _urllib_parse_moved_attributes = [ | |
315 | MovedAttribute("ParseResult", "urlparse", "urllib.parse"), |
|
315 | MovedAttribute("ParseResult", "urlparse", "urllib.parse"), | |
316 | MovedAttribute("SplitResult", "urlparse", "urllib.parse"), |
|
316 | MovedAttribute("SplitResult", "urlparse", "urllib.parse"), | |
317 | MovedAttribute("parse_qs", "urlparse", "urllib.parse"), |
|
317 | MovedAttribute("parse_qs", "urlparse", "urllib.parse"), | |
318 | MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), |
|
318 | MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), | |
319 | MovedAttribute("urldefrag", "urlparse", "urllib.parse"), |
|
319 | MovedAttribute("urldefrag", "urlparse", "urllib.parse"), | |
320 | MovedAttribute("urljoin", "urlparse", "urllib.parse"), |
|
320 | MovedAttribute("urljoin", "urlparse", "urllib.parse"), | |
321 | MovedAttribute("urlparse", "urlparse", "urllib.parse"), |
|
321 | MovedAttribute("urlparse", "urlparse", "urllib.parse"), | |
322 | MovedAttribute("urlsplit", "urlparse", "urllib.parse"), |
|
322 | MovedAttribute("urlsplit", "urlparse", "urllib.parse"), | |
323 | MovedAttribute("urlunparse", "urlparse", "urllib.parse"), |
|
323 | MovedAttribute("urlunparse", "urlparse", "urllib.parse"), | |
324 | MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), |
|
324 | MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), | |
325 | MovedAttribute("quote", "urllib", "urllib.parse"), |
|
325 | MovedAttribute("quote", "urllib", "urllib.parse"), | |
326 | MovedAttribute("quote_plus", "urllib", "urllib.parse"), |
|
326 | MovedAttribute("quote_plus", "urllib", "urllib.parse"), | |
327 | MovedAttribute("unquote", "urllib", "urllib.parse"), |
|
327 | MovedAttribute("unquote", "urllib", "urllib.parse"), | |
328 | MovedAttribute("unquote_plus", "urllib", "urllib.parse"), |
|
328 | MovedAttribute("unquote_plus", "urllib", "urllib.parse"), | |
329 | MovedAttribute("urlencode", "urllib", "urllib.parse"), |
|
329 | MovedAttribute("urlencode", "urllib", "urllib.parse"), | |
330 | MovedAttribute("splitquery", "urllib", "urllib.parse"), |
|
330 | MovedAttribute("splitquery", "urllib", "urllib.parse"), | |
331 | MovedAttribute("splittag", "urllib", "urllib.parse"), |
|
331 | MovedAttribute("splittag", "urllib", "urllib.parse"), | |
332 | MovedAttribute("splituser", "urllib", "urllib.parse"), |
|
332 | MovedAttribute("splituser", "urllib", "urllib.parse"), | |
333 | MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), |
|
333 | MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), | |
334 | MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), |
|
334 | MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), | |
335 | MovedAttribute("uses_params", "urlparse", "urllib.parse"), |
|
335 | MovedAttribute("uses_params", "urlparse", "urllib.parse"), | |
336 | MovedAttribute("uses_query", "urlparse", "urllib.parse"), |
|
336 | MovedAttribute("uses_query", "urlparse", "urllib.parse"), | |
337 | MovedAttribute("uses_relative", "urlparse", "urllib.parse"), |
|
337 | MovedAttribute("uses_relative", "urlparse", "urllib.parse"), | |
338 | ] |
|
338 | ] | |
339 | for attr in _urllib_parse_moved_attributes: |
|
339 | for attr in _urllib_parse_moved_attributes: | |
340 | setattr(Module_six_moves_urllib_parse, attr.name, attr) |
|
340 | setattr(Module_six_moves_urllib_parse, attr.name, attr) | |
341 | del attr |
|
341 | del attr | |
342 |
|
342 | |||
343 | Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes |
|
343 | Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes | |
344 |
|
344 | |||
345 | _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), |
|
345 | _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), | |
346 | "moves.urllib_parse", "moves.urllib.parse") |
|
346 | "moves.urllib_parse", "moves.urllib.parse") | |
347 |
|
347 | |||
348 |
|
348 | |||
349 | class Module_six_moves_urllib_error(_LazyModule): |
|
349 | class Module_six_moves_urllib_error(_LazyModule): | |
350 | """Lazy loading of moved objects in six.moves.urllib_error""" |
|
350 | """Lazy loading of moved objects in six.moves.urllib_error""" | |
351 |
|
351 | |||
352 |
|
352 | |||
353 | _urllib_error_moved_attributes = [ |
|
353 | _urllib_error_moved_attributes = [ | |
354 | MovedAttribute("URLError", "urllib2", "urllib.error"), |
|
354 | MovedAttribute("URLError", "urllib2", "urllib.error"), | |
355 | MovedAttribute("HTTPError", "urllib2", "urllib.error"), |
|
355 | MovedAttribute("HTTPError", "urllib2", "urllib.error"), | |
356 | MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), |
|
356 | MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), | |
357 | ] |
|
357 | ] | |
358 | for attr in _urllib_error_moved_attributes: |
|
358 | for attr in _urllib_error_moved_attributes: | |
359 | setattr(Module_six_moves_urllib_error, attr.name, attr) |
|
359 | setattr(Module_six_moves_urllib_error, attr.name, attr) | |
360 | del attr |
|
360 | del attr | |
361 |
|
361 | |||
362 | Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes |
|
362 | Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes | |
363 |
|
363 | |||
364 | _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), |
|
364 | _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), | |
365 | "moves.urllib_error", "moves.urllib.error") |
|
365 | "moves.urllib_error", "moves.urllib.error") | |
366 |
|
366 | |||
367 |
|
367 | |||
368 | class Module_six_moves_urllib_request(_LazyModule): |
|
368 | class Module_six_moves_urllib_request(_LazyModule): | |
369 | """Lazy loading of moved objects in six.moves.urllib_request""" |
|
369 | """Lazy loading of moved objects in six.moves.urllib_request""" | |
370 |
|
370 | |||
371 |
|
371 | |||
372 | _urllib_request_moved_attributes = [ |
|
372 | _urllib_request_moved_attributes = [ | |
373 | MovedAttribute("urlopen", "urllib2", "urllib.request"), |
|
373 | MovedAttribute("urlopen", "urllib2", "urllib.request"), | |
374 | MovedAttribute("install_opener", "urllib2", "urllib.request"), |
|
374 | MovedAttribute("install_opener", "urllib2", "urllib.request"), | |
375 | MovedAttribute("build_opener", "urllib2", "urllib.request"), |
|
375 | MovedAttribute("build_opener", "urllib2", "urllib.request"), | |
376 | MovedAttribute("pathname2url", "urllib", "urllib.request"), |
|
376 | MovedAttribute("pathname2url", "urllib", "urllib.request"), | |
377 | MovedAttribute("url2pathname", "urllib", "urllib.request"), |
|
377 | MovedAttribute("url2pathname", "urllib", "urllib.request"), | |
378 | MovedAttribute("getproxies", "urllib", "urllib.request"), |
|
378 | MovedAttribute("getproxies", "urllib", "urllib.request"), | |
379 | MovedAttribute("Request", "urllib2", "urllib.request"), |
|
379 | MovedAttribute("Request", "urllib2", "urllib.request"), | |
380 | MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), |
|
380 | MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), | |
381 | MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), |
|
381 | MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), | |
382 | MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), |
|
382 | MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), | |
383 | MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), |
|
383 | MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), | |
384 | MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), |
|
384 | MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), | |
385 | MovedAttribute("BaseHandler", "urllib2", "urllib.request"), |
|
385 | MovedAttribute("BaseHandler", "urllib2", "urllib.request"), | |
386 | MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), |
|
386 | MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), | |
387 | MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), |
|
387 | MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), | |
388 | MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), |
|
388 | MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), | |
389 | MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), |
|
389 | MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), | |
390 | MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), |
|
390 | MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), | |
391 | MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), |
|
391 | MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), | |
392 | MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), |
|
392 | MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), | |
393 | MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), |
|
393 | MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), | |
394 | MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), |
|
394 | MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), | |
395 | MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), |
|
395 | MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), | |
396 | MovedAttribute("FileHandler", "urllib2", "urllib.request"), |
|
396 | MovedAttribute("FileHandler", "urllib2", "urllib.request"), | |
397 | MovedAttribute("FTPHandler", "urllib2", "urllib.request"), |
|
397 | MovedAttribute("FTPHandler", "urllib2", "urllib.request"), | |
398 | MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), |
|
398 | MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), | |
399 | MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), |
|
399 | MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), | |
400 | MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), |
|
400 | MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), | |
401 | MovedAttribute("urlretrieve", "urllib", "urllib.request"), |
|
401 | MovedAttribute("urlretrieve", "urllib", "urllib.request"), | |
402 | MovedAttribute("urlcleanup", "urllib", "urllib.request"), |
|
402 | MovedAttribute("urlcleanup", "urllib", "urllib.request"), | |
403 | MovedAttribute("URLopener", "urllib", "urllib.request"), |
|
403 | MovedAttribute("URLopener", "urllib", "urllib.request"), | |
404 | MovedAttribute("FancyURLopener", "urllib", "urllib.request"), |
|
404 | MovedAttribute("FancyURLopener", "urllib", "urllib.request"), | |
405 | MovedAttribute("proxy_bypass", "urllib", "urllib.request"), |
|
405 | MovedAttribute("proxy_bypass", "urllib", "urllib.request"), | |
406 | ] |
|
406 | ] | |
407 | for attr in _urllib_request_moved_attributes: |
|
407 | for attr in _urllib_request_moved_attributes: | |
408 | setattr(Module_six_moves_urllib_request, attr.name, attr) |
|
408 | setattr(Module_six_moves_urllib_request, attr.name, attr) | |
409 | del attr |
|
409 | del attr | |
410 |
|
410 | |||
411 | Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes |
|
411 | Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes | |
412 |
|
412 | |||
413 | _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), |
|
413 | _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), | |
414 | "moves.urllib_request", "moves.urllib.request") |
|
414 | "moves.urllib_request", "moves.urllib.request") | |
415 |
|
415 | |||
416 |
|
416 | |||
417 | class Module_six_moves_urllib_response(_LazyModule): |
|
417 | class Module_six_moves_urllib_response(_LazyModule): | |
418 | """Lazy loading of moved objects in six.moves.urllib_response""" |
|
418 | """Lazy loading of moved objects in six.moves.urllib_response""" | |
419 |
|
419 | |||
420 |
|
420 | |||
421 | _urllib_response_moved_attributes = [ |
|
421 | _urllib_response_moved_attributes = [ | |
422 | MovedAttribute("addbase", "urllib", "urllib.response"), |
|
422 | MovedAttribute("addbase", "urllib", "urllib.response"), | |
423 | MovedAttribute("addclosehook", "urllib", "urllib.response"), |
|
423 | MovedAttribute("addclosehook", "urllib", "urllib.response"), | |
424 | MovedAttribute("addinfo", "urllib", "urllib.response"), |
|
424 | MovedAttribute("addinfo", "urllib", "urllib.response"), | |
425 | MovedAttribute("addinfourl", "urllib", "urllib.response"), |
|
425 | MovedAttribute("addinfourl", "urllib", "urllib.response"), | |
426 | ] |
|
426 | ] | |
427 | for attr in _urllib_response_moved_attributes: |
|
427 | for attr in _urllib_response_moved_attributes: | |
428 | setattr(Module_six_moves_urllib_response, attr.name, attr) |
|
428 | setattr(Module_six_moves_urllib_response, attr.name, attr) | |
429 | del attr |
|
429 | del attr | |
430 |
|
430 | |||
431 | Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes |
|
431 | Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes | |
432 |
|
432 | |||
433 | _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), |
|
433 | _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), | |
434 | "moves.urllib_response", "moves.urllib.response") |
|
434 | "moves.urllib_response", "moves.urllib.response") | |
435 |
|
435 | |||
436 |
|
436 | |||
437 | class Module_six_moves_urllib_robotparser(_LazyModule): |
|
437 | class Module_six_moves_urllib_robotparser(_LazyModule): | |
438 | """Lazy loading of moved objects in six.moves.urllib_robotparser""" |
|
438 | """Lazy loading of moved objects in six.moves.urllib_robotparser""" | |
439 |
|
439 | |||
440 |
|
440 | |||
441 | _urllib_robotparser_moved_attributes = [ |
|
441 | _urllib_robotparser_moved_attributes = [ | |
442 | MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), |
|
442 | MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), | |
443 | ] |
|
443 | ] | |
444 | for attr in _urllib_robotparser_moved_attributes: |
|
444 | for attr in _urllib_robotparser_moved_attributes: | |
445 | setattr(Module_six_moves_urllib_robotparser, attr.name, attr) |
|
445 | setattr(Module_six_moves_urllib_robotparser, attr.name, attr) | |
446 | del attr |
|
446 | del attr | |
447 |
|
447 | |||
448 | Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes |
|
448 | Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes | |
449 |
|
449 | |||
450 | _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), |
|
450 | _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), | |
451 | "moves.urllib_robotparser", "moves.urllib.robotparser") |
|
451 | "moves.urllib_robotparser", "moves.urllib.robotparser") | |
452 |
|
452 | |||
453 |
|
453 | |||
454 | class Module_six_moves_urllib(types.ModuleType): |
|
454 | class Module_six_moves_urllib(types.ModuleType): | |
455 | """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" |
|
455 | """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" | |
456 | __path__ = [] # mark as package |
|
456 | __path__ = [] # mark as package | |
457 | parse = _importer._get_module("moves.urllib_parse") |
|
457 | parse = _importer._get_module("moves.urllib_parse") | |
458 | error = _importer._get_module("moves.urllib_error") |
|
458 | error = _importer._get_module("moves.urllib_error") | |
459 | request = _importer._get_module("moves.urllib_request") |
|
459 | request = _importer._get_module("moves.urllib_request") | |
460 | response = _importer._get_module("moves.urllib_response") |
|
460 | response = _importer._get_module("moves.urllib_response") | |
461 | robotparser = _importer._get_module("moves.urllib_robotparser") |
|
461 | robotparser = _importer._get_module("moves.urllib_robotparser") | |
462 |
|
462 | |||
463 | def __dir__(self): |
|
463 | def __dir__(self): | |
464 | return ['parse', 'error', 'request', 'response', 'robotparser'] |
|
464 | return ['parse', 'error', 'request', 'response', 'robotparser'] | |
465 |
|
465 | |||
466 | _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), |
|
466 | _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), | |
467 | "moves.urllib") |
|
467 | "moves.urllib") | |
468 |
|
468 | |||
469 |
|
469 | |||
470 | def add_move(move): |
|
470 | def add_move(move): | |
471 | """Add an item to six.moves.""" |
|
471 | """Add an item to six.moves.""" | |
472 | setattr(_MovedItems, move.name, move) |
|
472 | setattr(_MovedItems, move.name, move) | |
473 |
|
473 | |||
474 |
|
474 | |||
475 | def remove_move(name): |
|
475 | def remove_move(name): | |
476 | """Remove item from six.moves.""" |
|
476 | """Remove item from six.moves.""" | |
477 | try: |
|
477 | try: | |
478 | delattr(_MovedItems, name) |
|
478 | delattr(_MovedItems, name) | |
479 | except AttributeError: |
|
479 | except AttributeError: | |
480 | try: |
|
480 | try: | |
481 | del moves.__dict__[name] |
|
481 | del moves.__dict__[name] | |
482 | except KeyError: |
|
482 | except KeyError: | |
483 | raise AttributeError("no such move, %r" % (name,)) |
|
483 | raise AttributeError("no such move, %r" % (name,)) | |
484 |
|
484 | |||
485 |
|
485 | |||
486 | if PY3: |
|
486 | if PY3: | |
487 | _meth_func = "__func__" |
|
487 | _meth_func = "__func__" | |
488 | _meth_self = "__self__" |
|
488 | _meth_self = "__self__" | |
489 |
|
489 | |||
490 | _func_closure = "__closure__" |
|
490 | _func_closure = "__closure__" | |
491 | _func_code = "__code__" |
|
491 | _func_code = "__code__" | |
492 | _func_defaults = "__defaults__" |
|
492 | _func_defaults = "__defaults__" | |
493 | _func_globals = "__globals__" |
|
493 | _func_globals = "__globals__" | |
494 | else: |
|
494 | else: | |
495 | _meth_func = "im_func" |
|
495 | _meth_func = "im_func" | |
496 | _meth_self = "im_self" |
|
496 | _meth_self = "im_self" | |
497 |
|
497 | |||
498 | _func_closure = "func_closure" |
|
498 | _func_closure = "func_closure" | |
499 | _func_code = "func_code" |
|
499 | _func_code = "func_code" | |
500 | _func_defaults = "func_defaults" |
|
500 | _func_defaults = "func_defaults" | |
501 | _func_globals = "func_globals" |
|
501 | _func_globals = "func_globals" | |
502 |
|
502 | |||
503 |
|
503 | |||
504 | try: |
|
504 | try: | |
505 | advance_iterator = next |
|
505 | advance_iterator = next | |
506 | except NameError: |
|
506 | except NameError: | |
507 | def advance_iterator(it): |
|
507 | def advance_iterator(it): | |
508 | return it.next() |
|
508 | return it.next() | |
509 | next = advance_iterator |
|
509 | next = advance_iterator | |
510 |
|
510 | |||
511 |
|
511 | |||
512 | try: |
|
512 | try: | |
513 | callable = callable |
|
513 | callable = callable | |
514 | except NameError: |
|
514 | except NameError: | |
515 | def callable(obj): |
|
515 | def callable(obj): | |
516 | return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) |
|
516 | return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) | |
517 |
|
517 | |||
518 |
|
518 | |||
519 | if PY3: |
|
519 | if PY3: | |
520 | def get_unbound_function(unbound): |
|
520 | def get_unbound_function(unbound): | |
521 | return unbound |
|
521 | return unbound | |
522 |
|
522 | |||
523 | create_bound_method = types.MethodType |
|
523 | create_bound_method = types.MethodType | |
524 |
|
524 | |||
525 | Iterator = object |
|
525 | Iterator = object | |
526 | else: |
|
526 | else: | |
527 | def get_unbound_function(unbound): |
|
527 | def get_unbound_function(unbound): | |
528 | return unbound.im_func |
|
528 | return unbound.im_func | |
529 |
|
529 | |||
530 | def create_bound_method(func, obj): |
|
530 | def create_bound_method(func, obj): | |
531 | return types.MethodType(func, obj, obj.__class__) |
|
531 | return types.MethodType(func, obj, obj.__class__) | |
532 |
|
532 | |||
533 | class Iterator(object): |
|
533 | class Iterator(object): | |
534 |
|
534 | |||
535 | def next(self): |
|
535 | def next(self): | |
536 | return type(self).__next__(self) |
|
536 | return type(self).__next__(self) | |
537 |
|
537 | |||
538 | callable = callable |
|
538 | callable = callable | |
539 | _add_doc(get_unbound_function, |
|
539 | _add_doc(get_unbound_function, | |
540 | """Get the function out of a possibly unbound function""") |
|
540 | """Get the function out of a possibly unbound function""") | |
541 |
|
541 | |||
542 |
|
542 | |||
543 | get_method_function = operator.attrgetter(_meth_func) |
|
543 | get_method_function = operator.attrgetter(_meth_func) | |
544 | get_method_self = operator.attrgetter(_meth_self) |
|
544 | get_method_self = operator.attrgetter(_meth_self) | |
545 | get_function_closure = operator.attrgetter(_func_closure) |
|
545 | get_function_closure = operator.attrgetter(_func_closure) | |
546 | get_function_code = operator.attrgetter(_func_code) |
|
546 | get_function_code = operator.attrgetter(_func_code) | |
547 | get_function_defaults = operator.attrgetter(_func_defaults) |
|
547 | get_function_defaults = operator.attrgetter(_func_defaults) | |
548 | get_function_globals = operator.attrgetter(_func_globals) |
|
548 | get_function_globals = operator.attrgetter(_func_globals) | |
549 |
|
549 | |||
550 |
|
550 | |||
551 | if PY3: |
|
551 | if PY3: | |
552 | def iterkeys(d, **kw): |
|
552 | def iterkeys(d, **kw): | |
553 | return iter(d.keys(**kw)) |
|
553 | return iter(d.keys(**kw)) | |
554 |
|
554 | |||
555 | def itervalues(d, **kw): |
|
555 | def itervalues(d, **kw): | |
556 | return iter(d.values(**kw)) |
|
556 | return iter(d.values(**kw)) | |
557 |
|
557 | |||
558 | def iteritems(d, **kw): |
|
558 | def iteritems(d, **kw): | |
559 | return iter(d.items(**kw)) |
|
559 | return iter(d.items(**kw)) | |
560 |
|
560 | |||
561 | def iterlists(d, **kw): |
|
561 | def iterlists(d, **kw): | |
562 | return iter(d.lists(**kw)) |
|
562 | return iter(d.lists(**kw)) | |
563 |
|
563 | |||
564 | viewkeys = operator.methodcaller("keys") |
|
564 | viewkeys = operator.methodcaller("keys") | |
565 |
|
565 | |||
566 | viewvalues = operator.methodcaller("values") |
|
566 | viewvalues = operator.methodcaller("values") | |
567 |
|
567 | |||
568 | viewitems = operator.methodcaller("items") |
|
568 | viewitems = operator.methodcaller("items") | |
569 | else: |
|
569 | else: | |
570 | def iterkeys(d, **kw): |
|
570 | def iterkeys(d, **kw): | |
571 | return iter(d.iterkeys(**kw)) |
|
571 | return iter(d.iterkeys(**kw)) | |
572 |
|
572 | |||
573 | def itervalues(d, **kw): |
|
573 | def itervalues(d, **kw): | |
574 | return iter(d.itervalues(**kw)) |
|
574 | return iter(d.itervalues(**kw)) | |
575 |
|
575 | |||
576 | def iteritems(d, **kw): |
|
576 | def iteritems(d, **kw): | |
577 | return iter(d.iteritems(**kw)) |
|
577 | return iter(d.iteritems(**kw)) | |
578 |
|
578 | |||
579 | def iterlists(d, **kw): |
|
579 | def iterlists(d, **kw): | |
580 | return iter(d.iterlists(**kw)) |
|
580 | return iter(d.iterlists(**kw)) | |
581 |
|
581 | |||
582 | viewkeys = operator.methodcaller("viewkeys") |
|
582 | viewkeys = operator.methodcaller("viewkeys") | |
583 |
|
583 | |||
584 | viewvalues = operator.methodcaller("viewvalues") |
|
584 | viewvalues = operator.methodcaller("viewvalues") | |
585 |
|
585 | |||
586 | viewitems = operator.methodcaller("viewitems") |
|
586 | viewitems = operator.methodcaller("viewitems") | |
587 |
|
587 | |||
588 | _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") |
|
588 | _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") | |
589 | _add_doc(itervalues, "Return an iterator over the values of a dictionary.") |
|
589 | _add_doc(itervalues, "Return an iterator over the values of a dictionary.") | |
590 | _add_doc(iteritems, |
|
590 | _add_doc(iteritems, | |
591 | "Return an iterator over the (key, value) pairs of a dictionary.") |
|
591 | "Return an iterator over the (key, value) pairs of a dictionary.") | |
592 | _add_doc(iterlists, |
|
592 | _add_doc(iterlists, | |
593 | "Return an iterator over the (key, [values]) pairs of a dictionary.") |
|
593 | "Return an iterator over the (key, [values]) pairs of a dictionary.") | |
594 |
|
594 | |||
595 |
|
595 | |||
596 | if PY3: |
|
596 | if PY3: | |
597 | def b(s): |
|
597 | def b(s): | |
598 | return s.encode("latin-1") |
|
598 | return s.encode("latin-1") | |
599 | def u(s): |
|
599 | def u(s): | |
600 | return s |
|
600 | return s | |
601 | unichr = chr |
|
601 | unichr = chr | |
602 | if sys.version_info[1] <= 1: |
|
602 | if sys.version_info[1] <= 1: | |
603 | def int2byte(i): |
|
603 | def int2byte(i): | |
604 | return bytes((i,)) |
|
604 | return bytes((i,)) | |
605 | else: |
|
605 | else: | |
606 | # This is about 2x faster than the implementation above on 3.2+ |
|
606 | # This is about 2x faster than the implementation above on 3.2+ | |
607 | int2byte = operator.methodcaller("to_bytes", 1, "big") |
|
607 | int2byte = operator.methodcaller("to_bytes", 1, "big") | |
608 | byte2int = operator.itemgetter(0) |
|
608 | byte2int = operator.itemgetter(0) | |
609 | indexbytes = operator.getitem |
|
609 | indexbytes = operator.getitem | |
610 | iterbytes = iter |
|
610 | iterbytes = iter | |
611 | import io |
|
611 | import io | |
612 | StringIO = io.StringIO |
|
612 | StringIO = io.StringIO | |
613 | BytesIO = io.BytesIO |
|
613 | BytesIO = io.BytesIO | |
614 | _assertCountEqual = "assertCountEqual" |
|
614 | _assertCountEqual = "assertCountEqual" | |
615 | _assertRaisesRegex = "assertRaisesRegex" |
|
615 | _assertRaisesRegex = "assertRaisesRegex" | |
616 | _assertRegex = "assertRegex" |
|
616 | _assertRegex = "assertRegex" | |
617 | else: |
|
617 | else: | |
618 | def b(s): |
|
618 | def b(s): | |
619 | return s |
|
619 | return s | |
620 | # Workaround for standalone backslash |
|
620 | # Workaround for standalone backslash | |
621 | def u(s): |
|
621 | def u(s): | |
622 | return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") |
|
622 | return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") | |
623 | unichr = unichr |
|
623 | unichr = unichr | |
624 | int2byte = chr |
|
624 | int2byte = chr | |
625 | def byte2int(bs): |
|
625 | def byte2int(bs): | |
626 | return ord(bs[0]) |
|
626 | return ord(bs[0]) | |
627 | def indexbytes(buf, i): |
|
627 | def indexbytes(buf, i): | |
628 | return ord(buf[i]) |
|
628 | return ord(buf[i]) | |
629 | iterbytes = functools.partial(itertools.imap, ord) |
|
629 | iterbytes = functools.partial(itertools.imap, ord) | |
630 | import StringIO |
|
630 | from io import StringIO | |
631 | StringIO = BytesIO = StringIO.StringIO |
|
631 | StringIO = BytesIO = StringIO.StringIO | |
632 | _assertCountEqual = "assertItemsEqual" |
|
632 | _assertCountEqual = "assertItemsEqual" | |
633 | _assertRaisesRegex = "assertRaisesRegexp" |
|
633 | _assertRaisesRegex = "assertRaisesRegexp" | |
634 | _assertRegex = "assertRegexpMatches" |
|
634 | _assertRegex = "assertRegexpMatches" | |
635 | _add_doc(b, """Byte literal""") |
|
635 | _add_doc(b, """Byte literal""") | |
636 | _add_doc(u, """Text literal""") |
|
636 | _add_doc(u, """Text literal""") | |
637 |
|
637 | |||
638 |
|
638 | |||
639 | def assertCountEqual(self, *args, **kwargs): |
|
639 | def assertCountEqual(self, *args, **kwargs): | |
640 | return getattr(self, _assertCountEqual)(*args, **kwargs) |
|
640 | return getattr(self, _assertCountEqual)(*args, **kwargs) | |
641 |
|
641 | |||
642 |
|
642 | |||
643 | def assertRaisesRegex(self, *args, **kwargs): |
|
643 | def assertRaisesRegex(self, *args, **kwargs): | |
644 | return getattr(self, _assertRaisesRegex)(*args, **kwargs) |
|
644 | return getattr(self, _assertRaisesRegex)(*args, **kwargs) | |
645 |
|
645 | |||
646 |
|
646 | |||
647 | def assertRegex(self, *args, **kwargs): |
|
647 | def assertRegex(self, *args, **kwargs): | |
648 | return getattr(self, _assertRegex)(*args, **kwargs) |
|
648 | return getattr(self, _assertRegex)(*args, **kwargs) | |
649 |
|
649 | |||
650 |
|
650 | |||
651 | if PY3: |
|
651 | if PY3: | |
652 | exec_ = getattr(moves.builtins, "exec") |
|
652 | exec_ = getattr(moves.builtins, "exec") | |
653 |
|
653 | |||
654 |
|
654 | |||
655 | def reraise(tp, value, tb=None): |
|
655 | def reraise(tp, value, tb=None): | |
656 | if value is None: |
|
656 | if value is None: | |
657 | value = tp() |
|
657 | value = tp() | |
658 | if value.__traceback__ is not tb: |
|
658 | if value.__traceback__ is not tb: | |
659 | raise value.with_traceback(tb) |
|
659 | raise value.with_traceback(tb) | |
660 | raise value |
|
660 | raise value | |
661 |
|
661 | |||
662 | else: |
|
662 | else: | |
663 | def exec_(_code_, _globs_=None, _locs_=None): |
|
663 | def exec_(_code_, _globs_=None, _locs_=None): | |
664 | """Execute code in a namespace.""" |
|
664 | """Execute code in a namespace.""" | |
665 | if _globs_ is None: |
|
665 | if _globs_ is None: | |
666 | frame = sys._getframe(1) |
|
666 | frame = sys._getframe(1) | |
667 | _globs_ = frame.f_globals |
|
667 | _globs_ = frame.f_globals | |
668 | if _locs_ is None: |
|
668 | if _locs_ is None: | |
669 | _locs_ = frame.f_locals |
|
669 | _locs_ = frame.f_locals | |
670 | del frame |
|
670 | del frame | |
671 | elif _locs_ is None: |
|
671 | elif _locs_ is None: | |
672 | _locs_ = _globs_ |
|
672 | _locs_ = _globs_ | |
673 | exec("""exec _code_ in _globs_, _locs_""") |
|
673 | exec("""exec _code_ in _globs_, _locs_""") | |
674 |
|
674 | |||
675 |
|
675 | |||
676 | exec_("""def reraise(tp, value, tb=None): |
|
676 | exec_("""def reraise(tp, value, tb=None): | |
677 | raise tp, value, tb |
|
677 | raise tp, value, tb | |
678 | """) |
|
678 | """) | |
679 |
|
679 | |||
680 |
|
680 | |||
681 | if sys.version_info[:2] == (3, 2): |
|
681 | if sys.version_info[:2] == (3, 2): | |
682 | exec_("""def raise_from(value, from_value): |
|
682 | exec_("""def raise_from(value, from_value): | |
683 | if from_value is None: |
|
683 | if from_value is None: | |
684 | raise value |
|
684 | raise value | |
685 | raise value from from_value |
|
685 | raise value from from_value | |
686 | """) |
|
686 | """) | |
687 | elif sys.version_info[:2] > (3, 2): |
|
687 | elif sys.version_info[:2] > (3, 2): | |
688 | exec_("""def raise_from(value, from_value): |
|
688 | exec_("""def raise_from(value, from_value): | |
689 | raise value from from_value |
|
689 | raise value from from_value | |
690 | """) |
|
690 | """) | |
691 | else: |
|
691 | else: | |
692 | def raise_from(value, from_value): |
|
692 | def raise_from(value, from_value): | |
693 | raise value |
|
693 | raise value | |
694 |
|
694 | |||
695 |
|
695 | |||
696 | print_ = getattr(moves.builtins, "print", None) |
|
696 | print_ = getattr(moves.builtins, "print", None) | |
697 | if print_ is None: |
|
697 | if print_ is None: | |
698 | def print_(*args, **kwargs): |
|
698 | def print_(*args, **kwargs): | |
699 | """The new-style print function for Python 2.4 and 2.5.""" |
|
699 | """The new-style print function for Python 2.4 and 2.5.""" | |
700 | fp = kwargs.pop("file", sys.stdout) |
|
700 | fp = kwargs.pop("file", sys.stdout) | |
701 | if fp is None: |
|
701 | if fp is None: | |
702 | return |
|
702 | return | |
703 | def write(data): |
|
703 | def write(data): | |
704 | if not isinstance(data, str): |
|
704 | if not isinstance(data, str): | |
705 | data = str(data) |
|
705 | data = str(data) | |
706 | # If the file has an encoding, encode unicode with it. |
|
706 | # If the file has an encoding, encode unicode with it. | |
707 | if (isinstance(fp, file) and |
|
707 | if (isinstance(fp, file) and | |
708 | isinstance(data, unicode) and |
|
708 | isinstance(data, unicode) and | |
709 | fp.encoding is not None): |
|
709 | fp.encoding is not None): | |
710 | errors = getattr(fp, "errors", None) |
|
710 | errors = getattr(fp, "errors", None) | |
711 | if errors is None: |
|
711 | if errors is None: | |
712 | errors = "strict" |
|
712 | errors = "strict" | |
713 | data = data.encode(fp.encoding, errors) |
|
713 | data = data.encode(fp.encoding, errors) | |
714 | fp.write(data) |
|
714 | fp.write(data) | |
715 | want_unicode = False |
|
715 | want_unicode = False | |
716 | sep = kwargs.pop("sep", None) |
|
716 | sep = kwargs.pop("sep", None) | |
717 | if sep is not None: |
|
717 | if sep is not None: | |
718 | if isinstance(sep, unicode): |
|
718 | if isinstance(sep, unicode): | |
719 | want_unicode = True |
|
719 | want_unicode = True | |
720 | elif not isinstance(sep, str): |
|
720 | elif not isinstance(sep, str): | |
721 | raise TypeError("sep must be None or a string") |
|
721 | raise TypeError("sep must be None or a string") | |
722 | end = kwargs.pop("end", None) |
|
722 | end = kwargs.pop("end", None) | |
723 | if end is not None: |
|
723 | if end is not None: | |
724 | if isinstance(end, unicode): |
|
724 | if isinstance(end, unicode): | |
725 | want_unicode = True |
|
725 | want_unicode = True | |
726 | elif not isinstance(end, str): |
|
726 | elif not isinstance(end, str): | |
727 | raise TypeError("end must be None or a string") |
|
727 | raise TypeError("end must be None or a string") | |
728 | if kwargs: |
|
728 | if kwargs: | |
729 | raise TypeError("invalid keyword arguments to print()") |
|
729 | raise TypeError("invalid keyword arguments to print()") | |
730 | if not want_unicode: |
|
730 | if not want_unicode: | |
731 | for arg in args: |
|
731 | for arg in args: | |
732 | if isinstance(arg, unicode): |
|
732 | if isinstance(arg, unicode): | |
733 | want_unicode = True |
|
733 | want_unicode = True | |
734 | break |
|
734 | break | |
735 | if want_unicode: |
|
735 | if want_unicode: | |
736 | newline = unicode("\n") |
|
736 | newline = unicode("\n") | |
737 | space = unicode(" ") |
|
737 | space = unicode(" ") | |
738 | else: |
|
738 | else: | |
739 | newline = "\n" |
|
739 | newline = "\n" | |
740 | space = " " |
|
740 | space = " " | |
741 | if sep is None: |
|
741 | if sep is None: | |
742 | sep = space |
|
742 | sep = space | |
743 | if end is None: |
|
743 | if end is None: | |
744 | end = newline |
|
744 | end = newline | |
745 | for i, arg in enumerate(args): |
|
745 | for i, arg in enumerate(args): | |
746 | if i: |
|
746 | if i: | |
747 | write(sep) |
|
747 | write(sep) | |
748 | write(arg) |
|
748 | write(arg) | |
749 | write(end) |
|
749 | write(end) | |
750 | if sys.version_info[:2] < (3, 3): |
|
750 | if sys.version_info[:2] < (3, 3): | |
751 | _print = print_ |
|
751 | _print = print_ | |
752 | def print_(*args, **kwargs): |
|
752 | def print_(*args, **kwargs): | |
753 | fp = kwargs.get("file", sys.stdout) |
|
753 | fp = kwargs.get("file", sys.stdout) | |
754 | flush = kwargs.pop("flush", False) |
|
754 | flush = kwargs.pop("flush", False) | |
755 | _print(*args, **kwargs) |
|
755 | _print(*args, **kwargs) | |
756 | if flush and fp is not None: |
|
756 | if flush and fp is not None: | |
757 | fp.flush() |
|
757 | fp.flush() | |
758 |
|
758 | |||
759 | _add_doc(reraise, """Reraise an exception.""") |
|
759 | _add_doc(reraise, """Reraise an exception.""") | |
760 |
|
760 | |||
761 | if sys.version_info[0:2] < (3, 4): |
|
761 | if sys.version_info[0:2] < (3, 4): | |
762 | def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, |
|
762 | def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, | |
763 | updated=functools.WRAPPER_UPDATES): |
|
763 | updated=functools.WRAPPER_UPDATES): | |
764 | def wrapper(f): |
|
764 | def wrapper(f): | |
765 | f = functools.wraps(wrapped, assigned, updated)(f) |
|
765 | f = functools.wraps(wrapped, assigned, updated)(f) | |
766 | f.__wrapped__ = wrapped |
|
766 | f.__wrapped__ = wrapped | |
767 | return f |
|
767 | return f | |
768 | return wrapper |
|
768 | return wrapper | |
769 | else: |
|
769 | else: | |
770 | wraps = functools.wraps |
|
770 | wraps = functools.wraps | |
771 |
|
771 | |||
772 | def with_metaclass(meta, *bases): |
|
772 | def with_metaclass(meta, *bases): | |
773 | """Create a base class with a metaclass.""" |
|
773 | """Create a base class with a metaclass.""" | |
774 | # This requires a bit of explanation: the basic idea is to make a dummy |
|
774 | # This requires a bit of explanation: the basic idea is to make a dummy | |
775 | # metaclass for one level of class instantiation that replaces itself with |
|
775 | # metaclass for one level of class instantiation that replaces itself with | |
776 | # the actual metaclass. |
|
776 | # the actual metaclass. | |
777 | class metaclass(meta): |
|
777 | class metaclass(meta): | |
778 | def __new__(cls, name, this_bases, d): |
|
778 | def __new__(cls, name, this_bases, d): | |
779 | return meta(name, bases, d) |
|
779 | return meta(name, bases, d) | |
780 | return type.__new__(metaclass, 'temporary_class', (), {}) |
|
780 | return type.__new__(metaclass, 'temporary_class', (), {}) | |
781 |
|
781 | |||
782 |
|
782 | |||
783 | def add_metaclass(metaclass): |
|
783 | def add_metaclass(metaclass): | |
784 | """Class decorator for creating a class with a metaclass.""" |
|
784 | """Class decorator for creating a class with a metaclass.""" | |
785 | def wrapper(cls): |
|
785 | def wrapper(cls): | |
786 | orig_vars = cls.__dict__.copy() |
|
786 | orig_vars = cls.__dict__.copy() | |
787 | slots = orig_vars.get('__slots__') |
|
787 | slots = orig_vars.get('__slots__') | |
788 | if slots is not None: |
|
788 | if slots is not None: | |
789 | if isinstance(slots, str): |
|
789 | if isinstance(slots, str): | |
790 | slots = [slots] |
|
790 | slots = [slots] | |
791 | for slots_var in slots: |
|
791 | for slots_var in slots: | |
792 | orig_vars.pop(slots_var) |
|
792 | orig_vars.pop(slots_var) | |
793 | orig_vars.pop('__dict__', None) |
|
793 | orig_vars.pop('__dict__', None) | |
794 | orig_vars.pop('__weakref__', None) |
|
794 | orig_vars.pop('__weakref__', None) | |
795 | return metaclass(cls.__name__, cls.__bases__, orig_vars) |
|
795 | return metaclass(cls.__name__, cls.__bases__, orig_vars) | |
796 | return wrapper |
|
796 | return wrapper | |
797 |
|
797 | |||
798 |
|
798 | |||
799 | def python_2_unicode_compatible(klass): |
|
799 | def python_2_unicode_compatible(klass): | |
800 | """ |
|
800 | """ | |
801 | A decorator that defines __unicode__ and __str__ methods under Python 2. |
|
801 | A decorator that defines __unicode__ and __str__ methods under Python 2. | |
802 | Under Python 3 it does nothing. |
|
802 | Under Python 3 it does nothing. | |
803 |
|
803 | |||
804 | To support Python 2 and 3 with a single code base, define a __str__ method |
|
804 | To support Python 2 and 3 with a single code base, define a __str__ method | |
805 | returning text and apply this decorator to the class. |
|
805 | returning text and apply this decorator to the class. | |
806 | """ |
|
806 | """ | |
807 | if PY2: |
|
807 | if PY2: | |
808 | if '__str__' not in klass.__dict__: |
|
808 | if '__str__' not in klass.__dict__: | |
809 | raise ValueError("@python_2_unicode_compatible cannot be applied " |
|
809 | raise ValueError("@python_2_unicode_compatible cannot be applied " | |
810 | "to %s because it doesn't define __str__()." % |
|
810 | "to %s because it doesn't define __str__()." % | |
811 | klass.__name__) |
|
811 | klass.__name__) | |
812 | klass.__unicode__ = klass.__str__ |
|
812 | klass.__unicode__ = klass.__str__ | |
813 | klass.__str__ = lambda self: self.__unicode__().encode('utf-8') |
|
813 | klass.__str__ = lambda self: self.__unicode__().encode('utf-8') | |
814 | return klass |
|
814 | return klass | |
815 |
|
815 | |||
816 |
|
816 | |||
817 | # Complete the moves implementation. |
|
817 | # Complete the moves implementation. | |
818 | # This code is at the end of this module to speed up module loading. |
|
818 | # This code is at the end of this module to speed up module loading. | |
819 | # Turn this module into a package. |
|
819 | # Turn this module into a package. | |
820 | __path__ = [] # required for PEP 302 and PEP 451 |
|
820 | __path__ = [] # required for PEP 302 and PEP 451 | |
821 | __package__ = __name__ # see PEP 366 @ReservedAssignment |
|
821 | __package__ = __name__ # see PEP 366 @ReservedAssignment | |
822 | if globals().get("__spec__") is not None: |
|
822 | if globals().get("__spec__") is not None: | |
823 | __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable |
|
823 | __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable | |
824 | # Remove other six meta path importers, since they cause problems. This can |
|
824 | # Remove other six meta path importers, since they cause problems. This can | |
825 | # happen if six is removed from sys.modules and then reloaded. (Setuptools does |
|
825 | # happen if six is removed from sys.modules and then reloaded. (Setuptools does | |
826 | # this for some reason.) |
|
826 | # this for some reason.) | |
827 | if sys.meta_path: |
|
827 | if sys.meta_path: | |
828 | for i, importer in enumerate(sys.meta_path): |
|
828 | for i, importer in enumerate(sys.meta_path): | |
829 | # Here's some real nastiness: Another "instance" of the six module might |
|
829 | # Here's some real nastiness: Another "instance" of the six module might | |
830 | # be floating around. Therefore, we can't use isinstance() to check for |
|
830 | # be floating around. Therefore, we can't use isinstance() to check for | |
831 | # the six meta path importer, since the other six instance will have |
|
831 | # the six meta path importer, since the other six instance will have | |
832 | # inserted an importer with different class. |
|
832 | # inserted an importer with different class. | |
833 | if (type(importer).__name__ == "_SixMetaPathImporter" and |
|
833 | if (type(importer).__name__ == "_SixMetaPathImporter" and | |
834 | importer.name == __name__): |
|
834 | importer.name == __name__): | |
835 | del sys.meta_path[i] |
|
835 | del sys.meta_path[i] | |
836 | break |
|
836 | break | |
837 | del i, importer |
|
837 | del i, importer | |
838 | # Finally, add the importer to the meta path import hook. |
|
838 | # Finally, add the importer to the meta path import hook. | |
839 | sys.meta_path.append(_importer) |
|
839 | sys.meta_path.append(_importer) |
@@ -1,314 +1,314 b'' | |||||
1 | """ |
|
1 | """ | |
2 | Extensions to SQLAlchemy for altering existing tables. |
|
2 | Extensions to SQLAlchemy for altering existing tables. | |
3 |
|
3 | |||
4 | At the moment, this isn't so much based off of ANSI as much as |
|
4 | At the moment, this isn't so much based off of ANSI as much as | |
5 | things that just happen to work with multiple databases. |
|
5 | things that just happen to work with multiple databases. | |
6 | """ |
|
6 | """ | |
7 | import StringIO |
|
7 | from io import StringIO | |
8 |
|
8 | |||
9 | import sqlalchemy as sa |
|
9 | import sqlalchemy as sa | |
10 | from sqlalchemy.schema import SchemaVisitor |
|
10 | from sqlalchemy.schema import SchemaVisitor | |
11 | from sqlalchemy.engine.default import DefaultDialect |
|
11 | from sqlalchemy.engine.default import DefaultDialect | |
12 | from sqlalchemy.sql import ClauseElement |
|
12 | from sqlalchemy.sql import ClauseElement | |
13 | from sqlalchemy.schema import (ForeignKeyConstraint, |
|
13 | from sqlalchemy.schema import (ForeignKeyConstraint, | |
14 | PrimaryKeyConstraint, |
|
14 | PrimaryKeyConstraint, | |
15 | CheckConstraint, |
|
15 | CheckConstraint, | |
16 | UniqueConstraint, |
|
16 | UniqueConstraint, | |
17 | Index) |
|
17 | Index) | |
18 |
|
18 | |||
19 | import sqlalchemy.sql.compiler |
|
19 | import sqlalchemy.sql.compiler | |
20 | from rhodecode.lib.dbmigrate.migrate import exceptions |
|
20 | from rhodecode.lib.dbmigrate.migrate import exceptions | |
21 | from rhodecode.lib.dbmigrate.migrate.changeset import constraint |
|
21 | from rhodecode.lib.dbmigrate.migrate.changeset import constraint | |
22 | from rhodecode.lib.dbmigrate.migrate.changeset import util |
|
22 | from rhodecode.lib.dbmigrate.migrate.changeset import util | |
23 |
|
23 | |||
24 | from sqlalchemy.schema import AddConstraint, DropConstraint |
|
24 | from sqlalchemy.schema import AddConstraint, DropConstraint | |
25 | from sqlalchemy.sql.compiler import DDLCompiler |
|
25 | from sqlalchemy.sql.compiler import DDLCompiler | |
26 | SchemaGenerator = SchemaDropper = DDLCompiler |
|
26 | SchemaGenerator = SchemaDropper = DDLCompiler | |
27 |
|
27 | |||
28 |
|
28 | |||
29 | class AlterTableVisitor(SchemaVisitor): |
|
29 | class AlterTableVisitor(SchemaVisitor): | |
30 | """Common operations for ``ALTER TABLE`` statements.""" |
|
30 | """Common operations for ``ALTER TABLE`` statements.""" | |
31 |
|
31 | |||
32 | # engine.Compiler looks for .statement |
|
32 | # engine.Compiler looks for .statement | |
33 | # when it spawns off a new compiler |
|
33 | # when it spawns off a new compiler | |
34 | statement = ClauseElement() |
|
34 | statement = ClauseElement() | |
35 |
|
35 | |||
36 | def append(self, s): |
|
36 | def append(self, s): | |
37 | """Append content to the SchemaIterator's query buffer.""" |
|
37 | """Append content to the SchemaIterator's query buffer.""" | |
38 |
|
38 | |||
39 | self.buffer.write(s) |
|
39 | self.buffer.write(s) | |
40 |
|
40 | |||
41 | def execute(self): |
|
41 | def execute(self): | |
42 | """Execute the contents of the SchemaIterator's buffer.""" |
|
42 | """Execute the contents of the SchemaIterator's buffer.""" | |
43 | try: |
|
43 | try: | |
44 | return self.connection.execute(self.buffer.getvalue()) |
|
44 | return self.connection.execute(self.buffer.getvalue()) | |
45 | finally: |
|
45 | finally: | |
46 | self.buffer.seek(0) |
|
46 | self.buffer.seek(0) | |
47 | self.buffer.truncate() |
|
47 | self.buffer.truncate() | |
48 |
|
48 | |||
49 | def __init__(self, dialect, connection, **kw): |
|
49 | def __init__(self, dialect, connection, **kw): | |
50 | self.connection = connection |
|
50 | self.connection = connection | |
51 | self.buffer = StringIO.StringIO() |
|
51 | self.buffer = StringIO.StringIO() | |
52 | self.preparer = dialect.identifier_preparer |
|
52 | self.preparer = dialect.identifier_preparer | |
53 | self.dialect = dialect |
|
53 | self.dialect = dialect | |
54 |
|
54 | |||
55 | def traverse_single(self, elem): |
|
55 | def traverse_single(self, elem): | |
56 | ret = super(AlterTableVisitor, self).traverse_single(elem) |
|
56 | ret = super(AlterTableVisitor, self).traverse_single(elem) | |
57 | if ret: |
|
57 | if ret: | |
58 | # adapt to 0.6 which uses a string-returning |
|
58 | # adapt to 0.6 which uses a string-returning | |
59 | # object |
|
59 | # object | |
60 | self.append(" %s" % ret) |
|
60 | self.append(" %s" % ret) | |
61 |
|
61 | |||
62 | def _to_table(self, param): |
|
62 | def _to_table(self, param): | |
63 | """Returns the table object for the given param object.""" |
|
63 | """Returns the table object for the given param object.""" | |
64 | if isinstance(param, (sa.Column, sa.Index, sa.schema.Constraint)): |
|
64 | if isinstance(param, (sa.Column, sa.Index, sa.schema.Constraint)): | |
65 | ret = param.table |
|
65 | ret = param.table | |
66 | else: |
|
66 | else: | |
67 | ret = param |
|
67 | ret = param | |
68 | return ret |
|
68 | return ret | |
69 |
|
69 | |||
70 | def start_alter_table(self, param): |
|
70 | def start_alter_table(self, param): | |
71 | """Returns the start of an ``ALTER TABLE`` SQL-Statement. |
|
71 | """Returns the start of an ``ALTER TABLE`` SQL-Statement. | |
72 |
|
72 | |||
73 | Use the param object to determine the table name and use it |
|
73 | Use the param object to determine the table name and use it | |
74 | for building the SQL statement. |
|
74 | for building the SQL statement. | |
75 |
|
75 | |||
76 | :param param: object to determine the table from |
|
76 | :param param: object to determine the table from | |
77 | :type param: :class:`sqlalchemy.Column`, :class:`sqlalchemy.Index`, |
|
77 | :type param: :class:`sqlalchemy.Column`, :class:`sqlalchemy.Index`, | |
78 | :class:`sqlalchemy.schema.Constraint`, :class:`sqlalchemy.Table`, |
|
78 | :class:`sqlalchemy.schema.Constraint`, :class:`sqlalchemy.Table`, | |
79 | or string (table name) |
|
79 | or string (table name) | |
80 | """ |
|
80 | """ | |
81 | table = self._to_table(param) |
|
81 | table = self._to_table(param) | |
82 | self.append('\nALTER TABLE %s ' % self.preparer.format_table(table)) |
|
82 | self.append('\nALTER TABLE %s ' % self.preparer.format_table(table)) | |
83 | return table |
|
83 | return table | |
84 |
|
84 | |||
85 |
|
85 | |||
86 | class ANSIColumnGenerator(AlterTableVisitor, SchemaGenerator): |
|
86 | class ANSIColumnGenerator(AlterTableVisitor, SchemaGenerator): | |
87 | """Extends ansisql generator for column creation (alter table add col)""" |
|
87 | """Extends ansisql generator for column creation (alter table add col)""" | |
88 |
|
88 | |||
89 | def visit_column(self, column): |
|
89 | def visit_column(self, column): | |
90 | """Create a column (table already exists). |
|
90 | """Create a column (table already exists). | |
91 |
|
91 | |||
92 | :param column: column object |
|
92 | :param column: column object | |
93 | :type column: :class:`sqlalchemy.Column` instance |
|
93 | :type column: :class:`sqlalchemy.Column` instance | |
94 | """ |
|
94 | """ | |
95 | if column.default is not None: |
|
95 | if column.default is not None: | |
96 | self.traverse_single(column.default) |
|
96 | self.traverse_single(column.default) | |
97 |
|
97 | |||
98 | table = self.start_alter_table(column) |
|
98 | table = self.start_alter_table(column) | |
99 | self.append("ADD ") |
|
99 | self.append("ADD ") | |
100 | self.append(self.get_column_specification(column)) |
|
100 | self.append(self.get_column_specification(column)) | |
101 |
|
101 | |||
102 | for cons in column.constraints: |
|
102 | for cons in column.constraints: | |
103 | self.traverse_single(cons) |
|
103 | self.traverse_single(cons) | |
104 | self.execute() |
|
104 | self.execute() | |
105 |
|
105 | |||
106 | # ALTER TABLE STATEMENTS |
|
106 | # ALTER TABLE STATEMENTS | |
107 |
|
107 | |||
108 | # add indexes and unique constraints |
|
108 | # add indexes and unique constraints | |
109 | if column.index_name: |
|
109 | if column.index_name: | |
110 | Index(column.index_name,column).create() |
|
110 | Index(column.index_name,column).create() | |
111 | elif column.unique_name: |
|
111 | elif column.unique_name: | |
112 | constraint.UniqueConstraint(column, |
|
112 | constraint.UniqueConstraint(column, | |
113 | name=column.unique_name).create() |
|
113 | name=column.unique_name).create() | |
114 |
|
114 | |||
115 | # SA bounds FK constraints to table, add manually |
|
115 | # SA bounds FK constraints to table, add manually | |
116 | for fk in column.foreign_keys: |
|
116 | for fk in column.foreign_keys: | |
117 | self.add_foreignkey(fk.constraint) |
|
117 | self.add_foreignkey(fk.constraint) | |
118 |
|
118 | |||
119 | # add primary key constraint if needed |
|
119 | # add primary key constraint if needed | |
120 | if column.primary_key_name: |
|
120 | if column.primary_key_name: | |
121 | cons = constraint.PrimaryKeyConstraint(column, |
|
121 | cons = constraint.PrimaryKeyConstraint(column, | |
122 | name=column.primary_key_name) |
|
122 | name=column.primary_key_name) | |
123 | cons.create() |
|
123 | cons.create() | |
124 |
|
124 | |||
125 | def add_foreignkey(self, fk): |
|
125 | def add_foreignkey(self, fk): | |
126 | self.connection.execute(AddConstraint(fk)) |
|
126 | self.connection.execute(AddConstraint(fk)) | |
127 |
|
127 | |||
128 | class ANSIColumnDropper(AlterTableVisitor, SchemaDropper): |
|
128 | class ANSIColumnDropper(AlterTableVisitor, SchemaDropper): | |
129 | """Extends ANSI SQL dropper for column dropping (``ALTER TABLE |
|
129 | """Extends ANSI SQL dropper for column dropping (``ALTER TABLE | |
130 | DROP COLUMN``). |
|
130 | DROP COLUMN``). | |
131 | """ |
|
131 | """ | |
132 |
|
132 | |||
133 | def visit_column(self, column): |
|
133 | def visit_column(self, column): | |
134 | """Drop a column from its table. |
|
134 | """Drop a column from its table. | |
135 |
|
135 | |||
136 | :param column: the column object |
|
136 | :param column: the column object | |
137 | :type column: :class:`sqlalchemy.Column` |
|
137 | :type column: :class:`sqlalchemy.Column` | |
138 | """ |
|
138 | """ | |
139 | table = self.start_alter_table(column) |
|
139 | table = self.start_alter_table(column) | |
140 | self.append('DROP COLUMN %s' % self.preparer.format_column(column)) |
|
140 | self.append('DROP COLUMN %s' % self.preparer.format_column(column)) | |
141 | self.execute() |
|
141 | self.execute() | |
142 |
|
142 | |||
143 |
|
143 | |||
144 | class ANSISchemaChanger(AlterTableVisitor, SchemaGenerator): |
|
144 | class ANSISchemaChanger(AlterTableVisitor, SchemaGenerator): | |
145 | """Manages changes to existing schema elements. |
|
145 | """Manages changes to existing schema elements. | |
146 |
|
146 | |||
147 | Note that columns are schema elements; ``ALTER TABLE ADD COLUMN`` |
|
147 | Note that columns are schema elements; ``ALTER TABLE ADD COLUMN`` | |
148 | is in SchemaGenerator. |
|
148 | is in SchemaGenerator. | |
149 |
|
149 | |||
150 | All items may be renamed. Columns can also have many of their properties - |
|
150 | All items may be renamed. Columns can also have many of their properties - | |
151 | type, for example - changed. |
|
151 | type, for example - changed. | |
152 |
|
152 | |||
153 | Each function is passed a tuple, containing (object, name); where |
|
153 | Each function is passed a tuple, containing (object, name); where | |
154 | object is a type of object you'd expect for that function |
|
154 | object is a type of object you'd expect for that function | |
155 | (ie. table for visit_table) and name is the object's new |
|
155 | (ie. table for visit_table) and name is the object's new | |
156 | name. NONE means the name is unchanged. |
|
156 | name. NONE means the name is unchanged. | |
157 | """ |
|
157 | """ | |
158 |
|
158 | |||
159 | def visit_table(self, table): |
|
159 | def visit_table(self, table): | |
160 | """Rename a table. Other ops aren't supported.""" |
|
160 | """Rename a table. Other ops aren't supported.""" | |
161 | self.start_alter_table(table) |
|
161 | self.start_alter_table(table) | |
162 | q = util.safe_quote(table) |
|
162 | q = util.safe_quote(table) | |
163 | self.append("RENAME TO %s" % self.preparer.quote(table.new_name, q)) |
|
163 | self.append("RENAME TO %s" % self.preparer.quote(table.new_name, q)) | |
164 | self.execute() |
|
164 | self.execute() | |
165 |
|
165 | |||
166 | def visit_index(self, index): |
|
166 | def visit_index(self, index): | |
167 | """Rename an index""" |
|
167 | """Rename an index""" | |
168 | if hasattr(self, '_validate_identifier'): |
|
168 | if hasattr(self, '_validate_identifier'): | |
169 | # SA <= 0.6.3 |
|
169 | # SA <= 0.6.3 | |
170 | self.append("ALTER INDEX %s RENAME TO %s" % ( |
|
170 | self.append("ALTER INDEX %s RENAME TO %s" % ( | |
171 | self.preparer.quote( |
|
171 | self.preparer.quote( | |
172 | self._validate_identifier( |
|
172 | self._validate_identifier( | |
173 | index.name, True), index.quote), |
|
173 | index.name, True), index.quote), | |
174 | self.preparer.quote( |
|
174 | self.preparer.quote( | |
175 | self._validate_identifier( |
|
175 | self._validate_identifier( | |
176 | index.new_name, True), index.quote))) |
|
176 | index.new_name, True), index.quote))) | |
177 | elif hasattr(self, '_index_identifier'): |
|
177 | elif hasattr(self, '_index_identifier'): | |
178 | # SA >= 0.6.5, < 0.8 |
|
178 | # SA >= 0.6.5, < 0.8 | |
179 | self.append("ALTER INDEX %s RENAME TO %s" % ( |
|
179 | self.append("ALTER INDEX %s RENAME TO %s" % ( | |
180 | self.preparer.quote( |
|
180 | self.preparer.quote( | |
181 | self._index_identifier( |
|
181 | self._index_identifier( | |
182 | index.name), index.quote), |
|
182 | index.name), index.quote), | |
183 | self.preparer.quote( |
|
183 | self.preparer.quote( | |
184 | self._index_identifier( |
|
184 | self._index_identifier( | |
185 | index.new_name), index.quote))) |
|
185 | index.new_name), index.quote))) | |
186 | else: |
|
186 | else: | |
187 | # SA >= 0.8 |
|
187 | # SA >= 0.8 | |
188 | class NewName(object): |
|
188 | class NewName(object): | |
189 | """Map obj.name -> obj.new_name""" |
|
189 | """Map obj.name -> obj.new_name""" | |
190 | def __init__(self, index): |
|
190 | def __init__(self, index): | |
191 | self.name = index.new_name |
|
191 | self.name = index.new_name | |
192 | self._obj = index |
|
192 | self._obj = index | |
193 |
|
193 | |||
194 | def __getattr__(self, attr): |
|
194 | def __getattr__(self, attr): | |
195 | if attr == 'name': |
|
195 | if attr == 'name': | |
196 | return getattr(self, attr) |
|
196 | return getattr(self, attr) | |
197 | return getattr(self._obj, attr) |
|
197 | return getattr(self._obj, attr) | |
198 |
|
198 | |||
199 | self.append("ALTER INDEX %s RENAME TO %s" % ( |
|
199 | self.append("ALTER INDEX %s RENAME TO %s" % ( | |
200 | self._prepared_index_name(index), |
|
200 | self._prepared_index_name(index), | |
201 | self._prepared_index_name(NewName(index)))) |
|
201 | self._prepared_index_name(NewName(index)))) | |
202 |
|
202 | |||
203 | self.execute() |
|
203 | self.execute() | |
204 |
|
204 | |||
205 | def visit_column(self, delta): |
|
205 | def visit_column(self, delta): | |
206 | """Rename/change a column.""" |
|
206 | """Rename/change a column.""" | |
207 | # ALTER COLUMN is implemented as several ALTER statements |
|
207 | # ALTER COLUMN is implemented as several ALTER statements | |
208 | keys = delta.keys() |
|
208 | keys = delta.keys() | |
209 | if 'type' in keys: |
|
209 | if 'type' in keys: | |
210 | self._run_subvisit(delta, self._visit_column_type) |
|
210 | self._run_subvisit(delta, self._visit_column_type) | |
211 | if 'nullable' in keys: |
|
211 | if 'nullable' in keys: | |
212 | self._run_subvisit(delta, self._visit_column_nullable) |
|
212 | self._run_subvisit(delta, self._visit_column_nullable) | |
213 | if 'server_default' in keys: |
|
213 | if 'server_default' in keys: | |
214 | # Skip 'default': only handle server-side defaults, others |
|
214 | # Skip 'default': only handle server-side defaults, others | |
215 | # are managed by the app, not the db. |
|
215 | # are managed by the app, not the db. | |
216 | self._run_subvisit(delta, self._visit_column_default) |
|
216 | self._run_subvisit(delta, self._visit_column_default) | |
217 | if 'name' in keys: |
|
217 | if 'name' in keys: | |
218 | self._run_subvisit(delta, self._visit_column_name, start_alter=False) |
|
218 | self._run_subvisit(delta, self._visit_column_name, start_alter=False) | |
219 |
|
219 | |||
220 | def _run_subvisit(self, delta, func, start_alter=True): |
|
220 | def _run_subvisit(self, delta, func, start_alter=True): | |
221 | """Runs visit method based on what needs to be changed on column""" |
|
221 | """Runs visit method based on what needs to be changed on column""" | |
222 | table = self._to_table(delta.table) |
|
222 | table = self._to_table(delta.table) | |
223 | col_name = delta.current_name |
|
223 | col_name = delta.current_name | |
224 | if start_alter: |
|
224 | if start_alter: | |
225 | self.start_alter_column(table, col_name) |
|
225 | self.start_alter_column(table, col_name) | |
226 | ret = func(table, delta.result_column, delta) |
|
226 | ret = func(table, delta.result_column, delta) | |
227 | self.execute() |
|
227 | self.execute() | |
228 |
|
228 | |||
229 | def start_alter_column(self, table, col_name): |
|
229 | def start_alter_column(self, table, col_name): | |
230 | """Starts ALTER COLUMN""" |
|
230 | """Starts ALTER COLUMN""" | |
231 | self.start_alter_table(table) |
|
231 | self.start_alter_table(table) | |
232 | q = util.safe_quote(table) |
|
232 | q = util.safe_quote(table) | |
233 | self.append("ALTER COLUMN %s " % self.preparer.quote(col_name, q)) |
|
233 | self.append("ALTER COLUMN %s " % self.preparer.quote(col_name, q)) | |
234 |
|
234 | |||
235 | def _visit_column_nullable(self, table, column, delta): |
|
235 | def _visit_column_nullable(self, table, column, delta): | |
236 | nullable = delta['nullable'] |
|
236 | nullable = delta['nullable'] | |
237 | if nullable: |
|
237 | if nullable: | |
238 | self.append("DROP NOT NULL") |
|
238 | self.append("DROP NOT NULL") | |
239 | else: |
|
239 | else: | |
240 | self.append("SET NOT NULL") |
|
240 | self.append("SET NOT NULL") | |
241 |
|
241 | |||
242 | def _visit_column_default(self, table, column, delta): |
|
242 | def _visit_column_default(self, table, column, delta): | |
243 | default_text = self.get_column_default_string(column) |
|
243 | default_text = self.get_column_default_string(column) | |
244 | if default_text is not None: |
|
244 | if default_text is not None: | |
245 | self.append("SET DEFAULT %s" % default_text) |
|
245 | self.append("SET DEFAULT %s" % default_text) | |
246 | else: |
|
246 | else: | |
247 | self.append("DROP DEFAULT") |
|
247 | self.append("DROP DEFAULT") | |
248 |
|
248 | |||
249 | def _visit_column_type(self, table, column, delta): |
|
249 | def _visit_column_type(self, table, column, delta): | |
250 | type_ = delta['type'] |
|
250 | type_ = delta['type'] | |
251 | type_text = str(type_.compile(dialect=self.dialect)) |
|
251 | type_text = str(type_.compile(dialect=self.dialect)) | |
252 | self.append("TYPE %s" % type_text) |
|
252 | self.append("TYPE %s" % type_text) | |
253 |
|
253 | |||
254 | def _visit_column_name(self, table, column, delta): |
|
254 | def _visit_column_name(self, table, column, delta): | |
255 | self.start_alter_table(table) |
|
255 | self.start_alter_table(table) | |
256 | q = util.safe_quote(table) |
|
256 | q = util.safe_quote(table) | |
257 | col_name = self.preparer.quote(delta.current_name, q) |
|
257 | col_name = self.preparer.quote(delta.current_name, q) | |
258 | new_name = self.preparer.format_column(delta.result_column) |
|
258 | new_name = self.preparer.format_column(delta.result_column) | |
259 | self.append('RENAME COLUMN %s TO %s' % (col_name, new_name)) |
|
259 | self.append('RENAME COLUMN %s TO %s' % (col_name, new_name)) | |
260 |
|
260 | |||
261 |
|
261 | |||
262 | class ANSIConstraintCommon(AlterTableVisitor): |
|
262 | class ANSIConstraintCommon(AlterTableVisitor): | |
263 | """ |
|
263 | """ | |
264 | Migrate's constraints require a separate creation function from |
|
264 | Migrate's constraints require a separate creation function from | |
265 | SA's: Migrate's constraints are created independently of a table; |
|
265 | SA's: Migrate's constraints are created independently of a table; | |
266 | SA's are created at the same time as the table. |
|
266 | SA's are created at the same time as the table. | |
267 | """ |
|
267 | """ | |
268 |
|
268 | |||
269 | def get_constraint_name(self, cons): |
|
269 | def get_constraint_name(self, cons): | |
270 | """Gets a name for the given constraint. |
|
270 | """Gets a name for the given constraint. | |
271 |
|
271 | |||
272 | If the name is already set it will be used otherwise the |
|
272 | If the name is already set it will be used otherwise the | |
273 | constraint's :meth:`autoname <migrate.changeset.constraint.ConstraintChangeset.autoname>` |
|
273 | constraint's :meth:`autoname <migrate.changeset.constraint.ConstraintChangeset.autoname>` | |
274 | method is used. |
|
274 | method is used. | |
275 |
|
275 | |||
276 | :param cons: constraint object |
|
276 | :param cons: constraint object | |
277 | """ |
|
277 | """ | |
278 | if cons.name is not None: |
|
278 | if cons.name is not None: | |
279 | ret = cons.name |
|
279 | ret = cons.name | |
280 | else: |
|
280 | else: | |
281 | ret = cons.name = cons.autoname() |
|
281 | ret = cons.name = cons.autoname() | |
282 | return self.preparer.quote(ret, cons.quote) |
|
282 | return self.preparer.quote(ret, cons.quote) | |
283 |
|
283 | |||
284 | def visit_migrate_primary_key_constraint(self, *p, **k): |
|
284 | def visit_migrate_primary_key_constraint(self, *p, **k): | |
285 | self._visit_constraint(*p, **k) |
|
285 | self._visit_constraint(*p, **k) | |
286 |
|
286 | |||
287 | def visit_migrate_foreign_key_constraint(self, *p, **k): |
|
287 | def visit_migrate_foreign_key_constraint(self, *p, **k): | |
288 | self._visit_constraint(*p, **k) |
|
288 | self._visit_constraint(*p, **k) | |
289 |
|
289 | |||
290 | def visit_migrate_check_constraint(self, *p, **k): |
|
290 | def visit_migrate_check_constraint(self, *p, **k): | |
291 | self._visit_constraint(*p, **k) |
|
291 | self._visit_constraint(*p, **k) | |
292 |
|
292 | |||
293 | def visit_migrate_unique_constraint(self, *p, **k): |
|
293 | def visit_migrate_unique_constraint(self, *p, **k): | |
294 | self._visit_constraint(*p, **k) |
|
294 | self._visit_constraint(*p, **k) | |
295 |
|
295 | |||
296 | class ANSIConstraintGenerator(ANSIConstraintCommon, SchemaGenerator): |
|
296 | class ANSIConstraintGenerator(ANSIConstraintCommon, SchemaGenerator): | |
297 | def _visit_constraint(self, constraint): |
|
297 | def _visit_constraint(self, constraint): | |
298 | constraint.name = self.get_constraint_name(constraint) |
|
298 | constraint.name = self.get_constraint_name(constraint) | |
299 | self.append(self.process(AddConstraint(constraint))) |
|
299 | self.append(self.process(AddConstraint(constraint))) | |
300 | self.execute() |
|
300 | self.execute() | |
301 |
|
301 | |||
302 | class ANSIConstraintDropper(ANSIConstraintCommon, SchemaDropper): |
|
302 | class ANSIConstraintDropper(ANSIConstraintCommon, SchemaDropper): | |
303 | def _visit_constraint(self, constraint): |
|
303 | def _visit_constraint(self, constraint): | |
304 | constraint.name = self.get_constraint_name(constraint) |
|
304 | constraint.name = self.get_constraint_name(constraint) | |
305 | self.append(self.process(DropConstraint(constraint, cascade=constraint.cascade))) |
|
305 | self.append(self.process(DropConstraint(constraint, cascade=constraint.cascade))) | |
306 | self.execute() |
|
306 | self.execute() | |
307 |
|
307 | |||
308 |
|
308 | |||
309 | class ANSIDialect(DefaultDialect): |
|
309 | class ANSIDialect(DefaultDialect): | |
310 | columngenerator = ANSIColumnGenerator |
|
310 | columngenerator = ANSIColumnGenerator | |
311 | columndropper = ANSIColumnDropper |
|
311 | columndropper = ANSIColumnDropper | |
312 | schemachanger = ANSISchemaChanger |
|
312 | schemachanger = ANSISchemaChanger | |
313 | constraintgenerator = ANSIConstraintGenerator |
|
313 | constraintgenerator = ANSIConstraintGenerator | |
314 | constraintdropper = ANSIConstraintDropper |
|
314 | constraintdropper = ANSIConstraintDropper |
@@ -1,159 +1,159 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # -*- coding: utf-8 -*- |
|
2 | # -*- coding: utf-8 -*- | |
3 |
|
3 | |||
4 | import shutil |
|
4 | import shutil | |
5 | import warnings |
|
5 | import warnings | |
6 | import logging |
|
6 | import logging | |
7 | import inspect |
|
7 | import inspect | |
8 |
from |
|
8 | from io import StringIO | |
9 |
|
9 | |||
10 | from rhodecode.lib.dbmigrate import migrate |
|
10 | from rhodecode.lib.dbmigrate import migrate | |
11 | from rhodecode.lib.dbmigrate.migrate.versioning import genmodel, schemadiff |
|
11 | from rhodecode.lib.dbmigrate.migrate.versioning import genmodel, schemadiff | |
12 | from rhodecode.lib.dbmigrate.migrate.versioning.config import operations |
|
12 | from rhodecode.lib.dbmigrate.migrate.versioning.config import operations | |
13 | from rhodecode.lib.dbmigrate.migrate.versioning.template import Template |
|
13 | from rhodecode.lib.dbmigrate.migrate.versioning.template import Template | |
14 | from rhodecode.lib.dbmigrate.migrate.versioning.script import base |
|
14 | from rhodecode.lib.dbmigrate.migrate.versioning.script import base | |
15 | from rhodecode.lib.dbmigrate.migrate.versioning.util import import_path, load_model, with_engine |
|
15 | from rhodecode.lib.dbmigrate.migrate.versioning.util import import_path, load_model, with_engine | |
16 | from rhodecode.lib.dbmigrate.migrate.exceptions import MigrateDeprecationWarning, InvalidScriptError, ScriptError |
|
16 | from rhodecode.lib.dbmigrate.migrate.exceptions import MigrateDeprecationWarning, InvalidScriptError, ScriptError | |
17 |
|
17 | |||
18 | log = logging.getLogger(__name__) |
|
18 | log = logging.getLogger(__name__) | |
19 | __all__ = ['PythonScript'] |
|
19 | __all__ = ['PythonScript'] | |
20 |
|
20 | |||
21 |
|
21 | |||
22 | class PythonScript(base.BaseScript): |
|
22 | class PythonScript(base.BaseScript): | |
23 | """Base for Python scripts""" |
|
23 | """Base for Python scripts""" | |
24 |
|
24 | |||
25 | @classmethod |
|
25 | @classmethod | |
26 | def create(cls, path, **opts): |
|
26 | def create(cls, path, **opts): | |
27 | """Create an empty migration script at specified path |
|
27 | """Create an empty migration script at specified path | |
28 |
|
28 | |||
29 | :returns: :class:`PythonScript instance <migrate.versioning.script.py.PythonScript>`""" |
|
29 | :returns: :class:`PythonScript instance <migrate.versioning.script.py.PythonScript>`""" | |
30 | cls.require_notfound(path) |
|
30 | cls.require_notfound(path) | |
31 |
|
31 | |||
32 | src = Template(opts.pop('templates_path', None)).get_script(theme=opts.pop('templates_theme', None)) |
|
32 | src = Template(opts.pop('templates_path', None)).get_script(theme=opts.pop('templates_theme', None)) | |
33 | shutil.copy(src, path) |
|
33 | shutil.copy(src, path) | |
34 |
|
34 | |||
35 | return cls(path) |
|
35 | return cls(path) | |
36 |
|
36 | |||
37 | @classmethod |
|
37 | @classmethod | |
38 | def make_update_script_for_model(cls, engine, oldmodel, |
|
38 | def make_update_script_for_model(cls, engine, oldmodel, | |
39 | model, repository, **opts): |
|
39 | model, repository, **opts): | |
40 | """Create a migration script based on difference between two SA models. |
|
40 | """Create a migration script based on difference between two SA models. | |
41 |
|
41 | |||
42 | :param repository: path to migrate repository |
|
42 | :param repository: path to migrate repository | |
43 | :param oldmodel: dotted.module.name:SAClass or SAClass object |
|
43 | :param oldmodel: dotted.module.name:SAClass or SAClass object | |
44 | :param model: dotted.module.name:SAClass or SAClass object |
|
44 | :param model: dotted.module.name:SAClass or SAClass object | |
45 | :param engine: SQLAlchemy engine |
|
45 | :param engine: SQLAlchemy engine | |
46 | :type repository: string or :class:`Repository instance <migrate.versioning.repository.Repository>` |
|
46 | :type repository: string or :class:`Repository instance <migrate.versioning.repository.Repository>` | |
47 | :type oldmodel: string or Class |
|
47 | :type oldmodel: string or Class | |
48 | :type model: string or Class |
|
48 | :type model: string or Class | |
49 | :type engine: Engine instance |
|
49 | :type engine: Engine instance | |
50 | :returns: Upgrade / Downgrade script |
|
50 | :returns: Upgrade / Downgrade script | |
51 | :rtype: string |
|
51 | :rtype: string | |
52 | """ |
|
52 | """ | |
53 |
|
53 | |||
54 | if isinstance(repository, str): |
|
54 | if isinstance(repository, str): | |
55 | # oh dear, an import cycle! |
|
55 | # oh dear, an import cycle! | |
56 | from rhodecode.lib.dbmigrate.migrate.versioning.repository import Repository |
|
56 | from rhodecode.lib.dbmigrate.migrate.versioning.repository import Repository | |
57 | repository = Repository(repository) |
|
57 | repository = Repository(repository) | |
58 |
|
58 | |||
59 | oldmodel = load_model(oldmodel) |
|
59 | oldmodel = load_model(oldmodel) | |
60 | model = load_model(model) |
|
60 | model = load_model(model) | |
61 |
|
61 | |||
62 | # Compute differences. |
|
62 | # Compute differences. | |
63 | diff = schemadiff.getDiffOfModelAgainstModel( |
|
63 | diff = schemadiff.getDiffOfModelAgainstModel( | |
64 | model, |
|
64 | model, | |
65 | oldmodel, |
|
65 | oldmodel, | |
66 | excludeTables=[repository.version_table]) |
|
66 | excludeTables=[repository.version_table]) | |
67 | # TODO: diff can be False (there is no difference?) |
|
67 | # TODO: diff can be False (there is no difference?) | |
68 | decls, upgradeCommands, downgradeCommands = \ |
|
68 | decls, upgradeCommands, downgradeCommands = \ | |
69 | genmodel.ModelGenerator(diff,engine).genB2AMigration() |
|
69 | genmodel.ModelGenerator(diff,engine).genB2AMigration() | |
70 |
|
70 | |||
71 | # Store differences into file. |
|
71 | # Store differences into file. | |
72 | src = Template(opts.pop('templates_path', None)).get_script(opts.pop('templates_theme', None)) |
|
72 | src = Template(opts.pop('templates_path', None)).get_script(opts.pop('templates_theme', None)) | |
73 | with open(src) as f: |
|
73 | with open(src) as f: | |
74 | contents = f.read() |
|
74 | contents = f.read() | |
75 |
|
75 | |||
76 | # generate source |
|
76 | # generate source | |
77 | search = 'def upgrade(migrate_engine):' |
|
77 | search = 'def upgrade(migrate_engine):' | |
78 | contents = contents.replace(search, '\n\n'.join((decls, search)), 1) |
|
78 | contents = contents.replace(search, '\n\n'.join((decls, search)), 1) | |
79 | if upgradeCommands: |
|
79 | if upgradeCommands: | |
80 | contents = contents.replace(' pass', upgradeCommands, 1) |
|
80 | contents = contents.replace(' pass', upgradeCommands, 1) | |
81 | if downgradeCommands: |
|
81 | if downgradeCommands: | |
82 | contents = contents.replace(' pass', downgradeCommands, 1) |
|
82 | contents = contents.replace(' pass', downgradeCommands, 1) | |
83 | return contents |
|
83 | return contents | |
84 |
|
84 | |||
85 | @classmethod |
|
85 | @classmethod | |
86 | def verify_module(cls, path): |
|
86 | def verify_module(cls, path): | |
87 | """Ensure path is a valid script |
|
87 | """Ensure path is a valid script | |
88 |
|
88 | |||
89 | :param path: Script location |
|
89 | :param path: Script location | |
90 | :type path: string |
|
90 | :type path: string | |
91 | :raises: :exc:`InvalidScriptError <migrate.exceptions.InvalidScriptError>` |
|
91 | :raises: :exc:`InvalidScriptError <migrate.exceptions.InvalidScriptError>` | |
92 | :returns: Python module |
|
92 | :returns: Python module | |
93 | """ |
|
93 | """ | |
94 | # Try to import and get the upgrade() func |
|
94 | # Try to import and get the upgrade() func | |
95 | module = import_path(path) |
|
95 | module = import_path(path) | |
96 | try: |
|
96 | try: | |
97 | assert callable(module.upgrade) |
|
97 | assert callable(module.upgrade) | |
98 | except Exception as e: |
|
98 | except Exception as e: | |
99 | raise InvalidScriptError(path + ': %s' % str(e)) |
|
99 | raise InvalidScriptError(path + ': %s' % str(e)) | |
100 | return module |
|
100 | return module | |
101 |
|
101 | |||
102 | def preview_sql(self, url, step, **args): |
|
102 | def preview_sql(self, url, step, **args): | |
103 | """Mocks SQLAlchemy Engine to store all executed calls in a string |
|
103 | """Mocks SQLAlchemy Engine to store all executed calls in a string | |
104 | and runs :meth:`PythonScript.run <migrate.versioning.script.py.PythonScript.run>` |
|
104 | and runs :meth:`PythonScript.run <migrate.versioning.script.py.PythonScript.run>` | |
105 |
|
105 | |||
106 | :returns: SQL file |
|
106 | :returns: SQL file | |
107 | """ |
|
107 | """ | |
108 | buf = StringIO() |
|
108 | buf = StringIO() | |
109 | args['engine_arg_strategy'] = 'mock' |
|
109 | args['engine_arg_strategy'] = 'mock' | |
110 | args['engine_arg_executor'] = lambda s, p = '': buf.write(str(s) + p) |
|
110 | args['engine_arg_executor'] = lambda s, p = '': buf.write(str(s) + p) | |
111 |
|
111 | |||
112 | @with_engine |
|
112 | @with_engine | |
113 | def go(url, step, **kw): |
|
113 | def go(url, step, **kw): | |
114 | engine = kw.pop('engine') |
|
114 | engine = kw.pop('engine') | |
115 | self.run(engine, step) |
|
115 | self.run(engine, step) | |
116 | return buf.getvalue() |
|
116 | return buf.getvalue() | |
117 |
|
117 | |||
118 | return go(url, step, **args) |
|
118 | return go(url, step, **args) | |
119 |
|
119 | |||
120 | def run(self, engine, step): |
|
120 | def run(self, engine, step): | |
121 | """Core method of Script file. |
|
121 | """Core method of Script file. | |
122 | Exectues :func:`update` or :func:`downgrade` functions |
|
122 | Exectues :func:`update` or :func:`downgrade` functions | |
123 |
|
123 | |||
124 | :param engine: SQLAlchemy Engine |
|
124 | :param engine: SQLAlchemy Engine | |
125 | :param step: Operation to run |
|
125 | :param step: Operation to run | |
126 | :type engine: string |
|
126 | :type engine: string | |
127 | :type step: int |
|
127 | :type step: int | |
128 | """ |
|
128 | """ | |
129 | if step > 0: |
|
129 | if step > 0: | |
130 | op = 'upgrade' |
|
130 | op = 'upgrade' | |
131 | elif step < 0: |
|
131 | elif step < 0: | |
132 | op = 'downgrade' |
|
132 | op = 'downgrade' | |
133 | else: |
|
133 | else: | |
134 | raise ScriptError("%d is not a valid step" % step) |
|
134 | raise ScriptError("%d is not a valid step" % step) | |
135 |
|
135 | |||
136 | funcname = base.operations[op] |
|
136 | funcname = base.operations[op] | |
137 | script_func = self._func(funcname) |
|
137 | script_func = self._func(funcname) | |
138 |
|
138 | |||
139 | # check for old way of using engine |
|
139 | # check for old way of using engine | |
140 | if not inspect.getargspec(script_func)[0]: |
|
140 | if not inspect.getargspec(script_func)[0]: | |
141 | raise TypeError("upgrade/downgrade functions must accept engine" |
|
141 | raise TypeError("upgrade/downgrade functions must accept engine" | |
142 | " parameter (since version 0.5.4)") |
|
142 | " parameter (since version 0.5.4)") | |
143 |
|
143 | |||
144 | script_func(engine) |
|
144 | script_func(engine) | |
145 |
|
145 | |||
146 | @property |
|
146 | @property | |
147 | def module(self): |
|
147 | def module(self): | |
148 | """Calls :meth:`migrate.versioning.script.py.verify_module` |
|
148 | """Calls :meth:`migrate.versioning.script.py.verify_module` | |
149 | and returns it. |
|
149 | and returns it. | |
150 | """ |
|
150 | """ | |
151 | if not hasattr(self, '_module'): |
|
151 | if not hasattr(self, '_module'): | |
152 | self._module = self.verify_module(self.path) |
|
152 | self._module = self.verify_module(self.path) | |
153 | return self._module |
|
153 | return self._module | |
154 |
|
154 | |||
155 | def _func(self, funcname): |
|
155 | def _func(self, funcname): | |
156 | if not hasattr(self.module, funcname): |
|
156 | if not hasattr(self.module, funcname): | |
157 | msg = "Function '%s' is not defined in this script" |
|
157 | msg = "Function '%s' is not defined in this script" | |
158 | raise ScriptError(msg % funcname) |
|
158 | raise ScriptError(msg % funcname) | |
159 | return getattr(self.module, funcname) |
|
159 | return getattr(self.module, funcname) |
@@ -1,446 +1,446 b'' | |||||
1 | # Copyright (c) Django Software Foundation and individual contributors. |
|
1 | # Copyright (c) Django Software Foundation and individual contributors. | |
2 | # All rights reserved. |
|
2 | # All rights reserved. | |
3 | # |
|
3 | # | |
4 | # Redistribution and use in source and binary forms, with or without modification, |
|
4 | # Redistribution and use in source and binary forms, with or without modification, | |
5 | # are permitted provided that the following conditions are met: |
|
5 | # are permitted provided that the following conditions are met: | |
6 | # |
|
6 | # | |
7 | # 1. Redistributions of source code must retain the above copyright notice, |
|
7 | # 1. Redistributions of source code must retain the above copyright notice, | |
8 | # this list of conditions and the following disclaimer. |
|
8 | # this list of conditions and the following disclaimer. | |
9 | # |
|
9 | # | |
10 | # 2. Redistributions in binary form must reproduce the above copyright |
|
10 | # 2. Redistributions in binary form must reproduce the above copyright | |
11 | # notice, this list of conditions and the following disclaimer in the |
|
11 | # notice, this list of conditions and the following disclaimer in the | |
12 | # documentation and/or other materials provided with the distribution. |
|
12 | # documentation and/or other materials provided with the distribution. | |
13 | # |
|
13 | # | |
14 | # 3. Neither the name of Django nor the names of its contributors may be used |
|
14 | # 3. Neither the name of Django nor the names of its contributors may be used | |
15 | # to endorse or promote products derived from this software without |
|
15 | # to endorse or promote products derived from this software without | |
16 | # specific prior written permission. |
|
16 | # specific prior written permission. | |
17 | # |
|
17 | # | |
18 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
|
18 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND | |
19 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
|
19 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | |
20 | # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
|
20 | # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
21 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR |
|
21 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR | |
22 | # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
|
22 | # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |
23 | # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
|
23 | # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |
24 | # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON |
|
24 | # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON | |
25 | # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
|
25 | # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
26 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
|
26 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | |
27 | # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
|
27 | # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
28 |
|
28 | |||
29 | """ |
|
29 | """ | |
30 | For definitions of the different versions of RSS, see: |
|
30 | For definitions of the different versions of RSS, see: | |
31 | http://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss |
|
31 | http://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss | |
32 | """ |
|
32 | """ | |
33 |
|
33 | |||
34 |
|
34 | |||
35 | import datetime |
|
35 | import datetime | |
36 |
from |
|
36 | from io import StringIO | |
37 |
|
37 | |||
38 | import pytz |
|
38 | import pytz | |
39 | from six.moves.urllib import parse as urlparse |
|
39 | from six.moves.urllib import parse as urlparse | |
40 |
|
40 | |||
41 | from rhodecode.lib.feedgenerator import datetime_safe |
|
41 | from rhodecode.lib.feedgenerator import datetime_safe | |
42 | from rhodecode.lib.feedgenerator.utils import SimplerXMLGenerator, iri_to_uri, force_text |
|
42 | from rhodecode.lib.feedgenerator.utils import SimplerXMLGenerator, iri_to_uri, force_text | |
43 |
|
43 | |||
44 |
|
44 | |||
45 | #### The following code comes from ``django.utils.feedgenerator`` #### |
|
45 | #### The following code comes from ``django.utils.feedgenerator`` #### | |
46 |
|
46 | |||
47 |
|
47 | |||
48 | def rfc2822_date(date): |
|
48 | def rfc2822_date(date): | |
49 | # We can't use strftime() because it produces locale-dependent results, so |
|
49 | # We can't use strftime() because it produces locale-dependent results, so | |
50 | # we have to map english month and day names manually |
|
50 | # we have to map english month and day names manually | |
51 | months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',) |
|
51 | months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',) | |
52 | days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') |
|
52 | days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') | |
53 | # Support datetime objects older than 1900 |
|
53 | # Support datetime objects older than 1900 | |
54 | date = datetime_safe.new_datetime(date) |
|
54 | date = datetime_safe.new_datetime(date) | |
55 | # We do this ourselves to be timezone aware, email.Utils is not tz aware. |
|
55 | # We do this ourselves to be timezone aware, email.Utils is not tz aware. | |
56 | dow = days[date.weekday()] |
|
56 | dow = days[date.weekday()] | |
57 | month = months[date.month - 1] |
|
57 | month = months[date.month - 1] | |
58 | time_str = date.strftime('%s, %%d %s %%Y %%H:%%M:%%S ' % (dow, month)) |
|
58 | time_str = date.strftime('%s, %%d %s %%Y %%H:%%M:%%S ' % (dow, month)) | |
59 |
|
59 | |||
60 | time_str = time_str.decode('utf-8') |
|
60 | time_str = time_str.decode('utf-8') | |
61 | offset = date.utcoffset() |
|
61 | offset = date.utcoffset() | |
62 | # Historically, this function assumes that naive datetimes are in UTC. |
|
62 | # Historically, this function assumes that naive datetimes are in UTC. | |
63 | if offset is None: |
|
63 | if offset is None: | |
64 | return time_str + '-0000' |
|
64 | return time_str + '-0000' | |
65 | else: |
|
65 | else: | |
66 | timezone = (offset.days * 24 * 60) + (offset.seconds // 60) |
|
66 | timezone = (offset.days * 24 * 60) + (offset.seconds // 60) | |
67 | hour, minute = divmod(timezone, 60) |
|
67 | hour, minute = divmod(timezone, 60) | |
68 | return time_str + '%+03d%02d' % (hour, minute) |
|
68 | return time_str + '%+03d%02d' % (hour, minute) | |
69 |
|
69 | |||
70 |
|
70 | |||
71 | def rfc3339_date(date): |
|
71 | def rfc3339_date(date): | |
72 | # Support datetime objects older than 1900 |
|
72 | # Support datetime objects older than 1900 | |
73 | date = datetime_safe.new_datetime(date) |
|
73 | date = datetime_safe.new_datetime(date) | |
74 | time_str = date.strftime('%Y-%m-%dT%H:%M:%S') |
|
74 | time_str = date.strftime('%Y-%m-%dT%H:%M:%S') | |
75 |
|
75 | |||
76 | time_str = time_str.decode('utf-8') |
|
76 | time_str = time_str.decode('utf-8') | |
77 | offset = date.utcoffset() |
|
77 | offset = date.utcoffset() | |
78 | # Historically, this function assumes that naive datetimes are in UTC. |
|
78 | # Historically, this function assumes that naive datetimes are in UTC. | |
79 | if offset is None: |
|
79 | if offset is None: | |
80 | return time_str + 'Z' |
|
80 | return time_str + 'Z' | |
81 | else: |
|
81 | else: | |
82 | timezone = (offset.days * 24 * 60) + (offset.seconds // 60) |
|
82 | timezone = (offset.days * 24 * 60) + (offset.seconds // 60) | |
83 | hour, minute = divmod(timezone, 60) |
|
83 | hour, minute = divmod(timezone, 60) | |
84 | return time_str + '%+03d:%02d' % (hour, minute) |
|
84 | return time_str + '%+03d:%02d' % (hour, minute) | |
85 |
|
85 | |||
86 |
|
86 | |||
87 | def get_tag_uri(url, date): |
|
87 | def get_tag_uri(url, date): | |
88 | """ |
|
88 | """ | |
89 | Creates a TagURI. |
|
89 | Creates a TagURI. | |
90 |
|
90 | |||
91 | See http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id |
|
91 | See http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id | |
92 | """ |
|
92 | """ | |
93 | bits = urlparse(url) |
|
93 | bits = urlparse(url) | |
94 | d = '' |
|
94 | d = '' | |
95 | if date is not None: |
|
95 | if date is not None: | |
96 | d = ',%s' % datetime_safe.new_datetime(date).strftime('%Y-%m-%d') |
|
96 | d = ',%s' % datetime_safe.new_datetime(date).strftime('%Y-%m-%d') | |
97 | return 'tag:%s%s:%s/%s' % (bits.hostname, d, bits.path, bits.fragment) |
|
97 | return 'tag:%s%s:%s/%s' % (bits.hostname, d, bits.path, bits.fragment) | |
98 |
|
98 | |||
99 |
|
99 | |||
100 | class SyndicationFeed(object): |
|
100 | class SyndicationFeed(object): | |
101 | """Base class for all syndication feeds. Subclasses should provide write()""" |
|
101 | """Base class for all syndication feeds. Subclasses should provide write()""" | |
102 |
|
102 | |||
103 | def __init__(self, title, link, description, language=None, author_email=None, |
|
103 | def __init__(self, title, link, description, language=None, author_email=None, | |
104 | author_name=None, author_link=None, subtitle=None, categories=None, |
|
104 | author_name=None, author_link=None, subtitle=None, categories=None, | |
105 | feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs): |
|
105 | feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs): | |
106 | def to_unicode(s): |
|
106 | def to_unicode(s): | |
107 | return force_text(s, strings_only=True) |
|
107 | return force_text(s, strings_only=True) | |
108 | if categories: |
|
108 | if categories: | |
109 | categories = [force_text(c) for c in categories] |
|
109 | categories = [force_text(c) for c in categories] | |
110 | if ttl is not None: |
|
110 | if ttl is not None: | |
111 | # Force ints to unicode |
|
111 | # Force ints to unicode | |
112 | ttl = force_text(ttl) |
|
112 | ttl = force_text(ttl) | |
113 | self.feed = { |
|
113 | self.feed = { | |
114 | 'title': to_unicode(title), |
|
114 | 'title': to_unicode(title), | |
115 | 'link': iri_to_uri(link), |
|
115 | 'link': iri_to_uri(link), | |
116 | 'description': to_unicode(description), |
|
116 | 'description': to_unicode(description), | |
117 | 'language': to_unicode(language), |
|
117 | 'language': to_unicode(language), | |
118 | 'author_email': to_unicode(author_email), |
|
118 | 'author_email': to_unicode(author_email), | |
119 | 'author_name': to_unicode(author_name), |
|
119 | 'author_name': to_unicode(author_name), | |
120 | 'author_link': iri_to_uri(author_link), |
|
120 | 'author_link': iri_to_uri(author_link), | |
121 | 'subtitle': to_unicode(subtitle), |
|
121 | 'subtitle': to_unicode(subtitle), | |
122 | 'categories': categories or (), |
|
122 | 'categories': categories or (), | |
123 | 'feed_url': iri_to_uri(feed_url), |
|
123 | 'feed_url': iri_to_uri(feed_url), | |
124 | 'feed_copyright': to_unicode(feed_copyright), |
|
124 | 'feed_copyright': to_unicode(feed_copyright), | |
125 | 'id': feed_guid or link, |
|
125 | 'id': feed_guid or link, | |
126 | 'ttl': ttl, |
|
126 | 'ttl': ttl, | |
127 | } |
|
127 | } | |
128 | self.feed.update(kwargs) |
|
128 | self.feed.update(kwargs) | |
129 | self.items = [] |
|
129 | self.items = [] | |
130 |
|
130 | |||
131 | def add_item(self, title, link, description, author_email=None, |
|
131 | def add_item(self, title, link, description, author_email=None, | |
132 | author_name=None, author_link=None, pubdate=None, comments=None, |
|
132 | author_name=None, author_link=None, pubdate=None, comments=None, | |
133 | unique_id=None, unique_id_is_permalink=None, enclosure=None, |
|
133 | unique_id=None, unique_id_is_permalink=None, enclosure=None, | |
134 | categories=(), item_copyright=None, ttl=None, updateddate=None, |
|
134 | categories=(), item_copyright=None, ttl=None, updateddate=None, | |
135 | enclosures=None, **kwargs): |
|
135 | enclosures=None, **kwargs): | |
136 | """ |
|
136 | """ | |
137 | Adds an item to the feed. All args are expected to be Python Unicode |
|
137 | Adds an item to the feed. All args are expected to be Python Unicode | |
138 | objects except pubdate and updateddate, which are datetime.datetime |
|
138 | objects except pubdate and updateddate, which are datetime.datetime | |
139 | objects, and enclosures, which is an iterable of instances of the |
|
139 | objects, and enclosures, which is an iterable of instances of the | |
140 | Enclosure class. |
|
140 | Enclosure class. | |
141 | """ |
|
141 | """ | |
142 | def to_unicode(s): |
|
142 | def to_unicode(s): | |
143 | return force_text(s, strings_only=True) |
|
143 | return force_text(s, strings_only=True) | |
144 | if categories: |
|
144 | if categories: | |
145 | categories = [to_unicode(c) for c in categories] |
|
145 | categories = [to_unicode(c) for c in categories] | |
146 | if ttl is not None: |
|
146 | if ttl is not None: | |
147 | # Force ints to unicode |
|
147 | # Force ints to unicode | |
148 | ttl = force_text(ttl) |
|
148 | ttl = force_text(ttl) | |
149 | if enclosure is None: |
|
149 | if enclosure is None: | |
150 | enclosures = [] if enclosures is None else enclosures |
|
150 | enclosures = [] if enclosures is None else enclosures | |
151 |
|
151 | |||
152 | item = { |
|
152 | item = { | |
153 | 'title': to_unicode(title), |
|
153 | 'title': to_unicode(title), | |
154 | 'link': iri_to_uri(link), |
|
154 | 'link': iri_to_uri(link), | |
155 | 'description': to_unicode(description), |
|
155 | 'description': to_unicode(description), | |
156 | 'author_email': to_unicode(author_email), |
|
156 | 'author_email': to_unicode(author_email), | |
157 | 'author_name': to_unicode(author_name), |
|
157 | 'author_name': to_unicode(author_name), | |
158 | 'author_link': iri_to_uri(author_link), |
|
158 | 'author_link': iri_to_uri(author_link), | |
159 | 'pubdate': pubdate, |
|
159 | 'pubdate': pubdate, | |
160 | 'updateddate': updateddate, |
|
160 | 'updateddate': updateddate, | |
161 | 'comments': to_unicode(comments), |
|
161 | 'comments': to_unicode(comments), | |
162 | 'unique_id': to_unicode(unique_id), |
|
162 | 'unique_id': to_unicode(unique_id), | |
163 | 'unique_id_is_permalink': unique_id_is_permalink, |
|
163 | 'unique_id_is_permalink': unique_id_is_permalink, | |
164 | 'enclosures': enclosures, |
|
164 | 'enclosures': enclosures, | |
165 | 'categories': categories or (), |
|
165 | 'categories': categories or (), | |
166 | 'item_copyright': to_unicode(item_copyright), |
|
166 | 'item_copyright': to_unicode(item_copyright), | |
167 | 'ttl': ttl, |
|
167 | 'ttl': ttl, | |
168 | } |
|
168 | } | |
169 | item.update(kwargs) |
|
169 | item.update(kwargs) | |
170 | self.items.append(item) |
|
170 | self.items.append(item) | |
171 |
|
171 | |||
172 | def num_items(self): |
|
172 | def num_items(self): | |
173 | return len(self.items) |
|
173 | return len(self.items) | |
174 |
|
174 | |||
175 | def root_attributes(self): |
|
175 | def root_attributes(self): | |
176 | """ |
|
176 | """ | |
177 | Return extra attributes to place on the root (i.e. feed/channel) element. |
|
177 | Return extra attributes to place on the root (i.e. feed/channel) element. | |
178 | Called from write(). |
|
178 | Called from write(). | |
179 | """ |
|
179 | """ | |
180 | return {} |
|
180 | return {} | |
181 |
|
181 | |||
182 | def add_root_elements(self, handler): |
|
182 | def add_root_elements(self, handler): | |
183 | """ |
|
183 | """ | |
184 | Add elements in the root (i.e. feed/channel) element. Called |
|
184 | Add elements in the root (i.e. feed/channel) element. Called | |
185 | from write(). |
|
185 | from write(). | |
186 | """ |
|
186 | """ | |
187 | pass |
|
187 | pass | |
188 |
|
188 | |||
189 | def item_attributes(self, item): |
|
189 | def item_attributes(self, item): | |
190 | """ |
|
190 | """ | |
191 | Return extra attributes to place on each item (i.e. item/entry) element. |
|
191 | Return extra attributes to place on each item (i.e. item/entry) element. | |
192 | """ |
|
192 | """ | |
193 | return {} |
|
193 | return {} | |
194 |
|
194 | |||
195 | def add_item_elements(self, handler, item): |
|
195 | def add_item_elements(self, handler, item): | |
196 | """ |
|
196 | """ | |
197 | Add elements on each item (i.e. item/entry) element. |
|
197 | Add elements on each item (i.e. item/entry) element. | |
198 | """ |
|
198 | """ | |
199 | pass |
|
199 | pass | |
200 |
|
200 | |||
201 | def write(self, outfile, encoding): |
|
201 | def write(self, outfile, encoding): | |
202 | """ |
|
202 | """ | |
203 | Outputs the feed in the given encoding to outfile, which is a file-like |
|
203 | Outputs the feed in the given encoding to outfile, which is a file-like | |
204 | object. Subclasses should override this. |
|
204 | object. Subclasses should override this. | |
205 | """ |
|
205 | """ | |
206 | raise NotImplementedError('subclasses of SyndicationFeed must provide a write() method') |
|
206 | raise NotImplementedError('subclasses of SyndicationFeed must provide a write() method') | |
207 |
|
207 | |||
208 | def writeString(self, encoding): |
|
208 | def writeString(self, encoding): | |
209 | """ |
|
209 | """ | |
210 | Returns the feed in the given encoding as a string. |
|
210 | Returns the feed in the given encoding as a string. | |
211 | """ |
|
211 | """ | |
212 | s = StringIO() |
|
212 | s = StringIO() | |
213 | self.write(s, encoding) |
|
213 | self.write(s, encoding) | |
214 | return s.getvalue() |
|
214 | return s.getvalue() | |
215 |
|
215 | |||
216 | def latest_post_date(self): |
|
216 | def latest_post_date(self): | |
217 | """ |
|
217 | """ | |
218 | Returns the latest item's pubdate or updateddate. If no items |
|
218 | Returns the latest item's pubdate or updateddate. If no items | |
219 | have either of these attributes this returns the current UTC date/time. |
|
219 | have either of these attributes this returns the current UTC date/time. | |
220 | """ |
|
220 | """ | |
221 | latest_date = None |
|
221 | latest_date = None | |
222 | date_keys = ('updateddate', 'pubdate') |
|
222 | date_keys = ('updateddate', 'pubdate') | |
223 |
|
223 | |||
224 | for item in self.items: |
|
224 | for item in self.items: | |
225 | for date_key in date_keys: |
|
225 | for date_key in date_keys: | |
226 | item_date = item.get(date_key) |
|
226 | item_date = item.get(date_key) | |
227 | if item_date: |
|
227 | if item_date: | |
228 | if latest_date is None or item_date > latest_date: |
|
228 | if latest_date is None or item_date > latest_date: | |
229 | latest_date = item_date |
|
229 | latest_date = item_date | |
230 |
|
230 | |||
231 | # datetime.now(tz=utc) is slower, as documented in django.utils.timezone.now |
|
231 | # datetime.now(tz=utc) is slower, as documented in django.utils.timezone.now | |
232 | return latest_date or datetime.datetime.utcnow().replace(tzinfo=pytz.utc) |
|
232 | return latest_date or datetime.datetime.utcnow().replace(tzinfo=pytz.utc) | |
233 |
|
233 | |||
234 |
|
234 | |||
235 | class Enclosure(object): |
|
235 | class Enclosure(object): | |
236 | """Represents an RSS enclosure""" |
|
236 | """Represents an RSS enclosure""" | |
237 | def __init__(self, url, length, mime_type): |
|
237 | def __init__(self, url, length, mime_type): | |
238 | """All args are expected to be Python Unicode objects""" |
|
238 | """All args are expected to be Python Unicode objects""" | |
239 | self.length, self.mime_type = length, mime_type |
|
239 | self.length, self.mime_type = length, mime_type | |
240 | self.url = iri_to_uri(url) |
|
240 | self.url = iri_to_uri(url) | |
241 |
|
241 | |||
242 |
|
242 | |||
243 | class RssFeed(SyndicationFeed): |
|
243 | class RssFeed(SyndicationFeed): | |
244 | content_type = 'application/rss+xml; charset=utf-8' |
|
244 | content_type = 'application/rss+xml; charset=utf-8' | |
245 |
|
245 | |||
246 | def write(self, outfile, encoding): |
|
246 | def write(self, outfile, encoding): | |
247 | handler = SimplerXMLGenerator(outfile, encoding) |
|
247 | handler = SimplerXMLGenerator(outfile, encoding) | |
248 | handler.startDocument() |
|
248 | handler.startDocument() | |
249 | handler.startElement("rss", self.rss_attributes()) |
|
249 | handler.startElement("rss", self.rss_attributes()) | |
250 | handler.startElement("channel", self.root_attributes()) |
|
250 | handler.startElement("channel", self.root_attributes()) | |
251 | self.add_root_elements(handler) |
|
251 | self.add_root_elements(handler) | |
252 | self.write_items(handler) |
|
252 | self.write_items(handler) | |
253 | self.endChannelElement(handler) |
|
253 | self.endChannelElement(handler) | |
254 | handler.endElement("rss") |
|
254 | handler.endElement("rss") | |
255 |
|
255 | |||
256 | def rss_attributes(self): |
|
256 | def rss_attributes(self): | |
257 | return {"version": self._version, |
|
257 | return {"version": self._version, | |
258 | "xmlns:atom": "http://www.w3.org/2005/Atom"} |
|
258 | "xmlns:atom": "http://www.w3.org/2005/Atom"} | |
259 |
|
259 | |||
260 | def write_items(self, handler): |
|
260 | def write_items(self, handler): | |
261 | for item in self.items: |
|
261 | for item in self.items: | |
262 | handler.startElement('item', self.item_attributes(item)) |
|
262 | handler.startElement('item', self.item_attributes(item)) | |
263 | self.add_item_elements(handler, item) |
|
263 | self.add_item_elements(handler, item) | |
264 | handler.endElement("item") |
|
264 | handler.endElement("item") | |
265 |
|
265 | |||
266 | def add_root_elements(self, handler): |
|
266 | def add_root_elements(self, handler): | |
267 | handler.addQuickElement("title", self.feed['title']) |
|
267 | handler.addQuickElement("title", self.feed['title']) | |
268 | handler.addQuickElement("link", self.feed['link']) |
|
268 | handler.addQuickElement("link", self.feed['link']) | |
269 | handler.addQuickElement("description", self.feed['description']) |
|
269 | handler.addQuickElement("description", self.feed['description']) | |
270 | if self.feed['feed_url'] is not None: |
|
270 | if self.feed['feed_url'] is not None: | |
271 | handler.addQuickElement("atom:link", None, {"rel": "self", "href": self.feed['feed_url']}) |
|
271 | handler.addQuickElement("atom:link", None, {"rel": "self", "href": self.feed['feed_url']}) | |
272 | if self.feed['language'] is not None: |
|
272 | if self.feed['language'] is not None: | |
273 | handler.addQuickElement("language", self.feed['language']) |
|
273 | handler.addQuickElement("language", self.feed['language']) | |
274 | for cat in self.feed['categories']: |
|
274 | for cat in self.feed['categories']: | |
275 | handler.addQuickElement("category", cat) |
|
275 | handler.addQuickElement("category", cat) | |
276 | if self.feed['feed_copyright'] is not None: |
|
276 | if self.feed['feed_copyright'] is not None: | |
277 | handler.addQuickElement("copyright", self.feed['feed_copyright']) |
|
277 | handler.addQuickElement("copyright", self.feed['feed_copyright']) | |
278 | handler.addQuickElement("lastBuildDate", rfc2822_date(self.latest_post_date())) |
|
278 | handler.addQuickElement("lastBuildDate", rfc2822_date(self.latest_post_date())) | |
279 | if self.feed['ttl'] is not None: |
|
279 | if self.feed['ttl'] is not None: | |
280 | handler.addQuickElement("ttl", self.feed['ttl']) |
|
280 | handler.addQuickElement("ttl", self.feed['ttl']) | |
281 |
|
281 | |||
282 | def endChannelElement(self, handler): |
|
282 | def endChannelElement(self, handler): | |
283 | handler.endElement("channel") |
|
283 | handler.endElement("channel") | |
284 |
|
284 | |||
285 |
|
285 | |||
286 | class RssUserland091Feed(RssFeed): |
|
286 | class RssUserland091Feed(RssFeed): | |
287 | _version = "0.91" |
|
287 | _version = "0.91" | |
288 |
|
288 | |||
289 | def add_item_elements(self, handler, item): |
|
289 | def add_item_elements(self, handler, item): | |
290 | handler.addQuickElement("title", item['title']) |
|
290 | handler.addQuickElement("title", item['title']) | |
291 | handler.addQuickElement("link", item['link']) |
|
291 | handler.addQuickElement("link", item['link']) | |
292 | if item['description'] is not None: |
|
292 | if item['description'] is not None: | |
293 | handler.addQuickElement("description", item['description']) |
|
293 | handler.addQuickElement("description", item['description']) | |
294 |
|
294 | |||
295 |
|
295 | |||
296 | class Rss201rev2Feed(RssFeed): |
|
296 | class Rss201rev2Feed(RssFeed): | |
297 | # Spec: http://blogs.law.harvard.edu/tech/rss |
|
297 | # Spec: http://blogs.law.harvard.edu/tech/rss | |
298 | _version = "2.0" |
|
298 | _version = "2.0" | |
299 |
|
299 | |||
300 | def add_item_elements(self, handler, item): |
|
300 | def add_item_elements(self, handler, item): | |
301 | handler.addQuickElement("title", item['title']) |
|
301 | handler.addQuickElement("title", item['title']) | |
302 | handler.addQuickElement("link", item['link']) |
|
302 | handler.addQuickElement("link", item['link']) | |
303 | if item['description'] is not None: |
|
303 | if item['description'] is not None: | |
304 | handler.addQuickElement("description", item['description']) |
|
304 | handler.addQuickElement("description", item['description']) | |
305 |
|
305 | |||
306 | # Author information. |
|
306 | # Author information. | |
307 | if item["author_name"] and item["author_email"]: |
|
307 | if item["author_name"] and item["author_email"]: | |
308 | handler.addQuickElement("author", "%s (%s)" % (item['author_email'], item['author_name'])) |
|
308 | handler.addQuickElement("author", "%s (%s)" % (item['author_email'], item['author_name'])) | |
309 | elif item["author_email"]: |
|
309 | elif item["author_email"]: | |
310 | handler.addQuickElement("author", item["author_email"]) |
|
310 | handler.addQuickElement("author", item["author_email"]) | |
311 | elif item["author_name"]: |
|
311 | elif item["author_name"]: | |
312 | handler.addQuickElement( |
|
312 | handler.addQuickElement( | |
313 | "dc:creator", item["author_name"], {"xmlns:dc": "http://purl.org/dc/elements/1.1/"} |
|
313 | "dc:creator", item["author_name"], {"xmlns:dc": "http://purl.org/dc/elements/1.1/"} | |
314 | ) |
|
314 | ) | |
315 |
|
315 | |||
316 | if item['pubdate'] is not None: |
|
316 | if item['pubdate'] is not None: | |
317 | handler.addQuickElement("pubDate", rfc2822_date(item['pubdate'])) |
|
317 | handler.addQuickElement("pubDate", rfc2822_date(item['pubdate'])) | |
318 | if item['comments'] is not None: |
|
318 | if item['comments'] is not None: | |
319 | handler.addQuickElement("comments", item['comments']) |
|
319 | handler.addQuickElement("comments", item['comments']) | |
320 | if item['unique_id'] is not None: |
|
320 | if item['unique_id'] is not None: | |
321 | guid_attrs = {} |
|
321 | guid_attrs = {} | |
322 | if isinstance(item.get('unique_id_is_permalink'), bool): |
|
322 | if isinstance(item.get('unique_id_is_permalink'), bool): | |
323 | guid_attrs['isPermaLink'] = str(item['unique_id_is_permalink']).lower() |
|
323 | guid_attrs['isPermaLink'] = str(item['unique_id_is_permalink']).lower() | |
324 | handler.addQuickElement("guid", item['unique_id'], guid_attrs) |
|
324 | handler.addQuickElement("guid", item['unique_id'], guid_attrs) | |
325 | if item['ttl'] is not None: |
|
325 | if item['ttl'] is not None: | |
326 | handler.addQuickElement("ttl", item['ttl']) |
|
326 | handler.addQuickElement("ttl", item['ttl']) | |
327 |
|
327 | |||
328 | # Enclosure. |
|
328 | # Enclosure. | |
329 | if item['enclosures']: |
|
329 | if item['enclosures']: | |
330 | enclosures = list(item['enclosures']) |
|
330 | enclosures = list(item['enclosures']) | |
331 | if len(enclosures) > 1: |
|
331 | if len(enclosures) > 1: | |
332 | raise ValueError( |
|
332 | raise ValueError( | |
333 | "RSS feed items may only have one enclosure, see " |
|
333 | "RSS feed items may only have one enclosure, see " | |
334 | "http://www.rssboard.org/rss-profile#element-channel-item-enclosure" |
|
334 | "http://www.rssboard.org/rss-profile#element-channel-item-enclosure" | |
335 | ) |
|
335 | ) | |
336 | enclosure = enclosures[0] |
|
336 | enclosure = enclosures[0] | |
337 | handler.addQuickElement('enclosure', '', { |
|
337 | handler.addQuickElement('enclosure', '', { | |
338 | 'url': enclosure.url, |
|
338 | 'url': enclosure.url, | |
339 | 'length': enclosure.length, |
|
339 | 'length': enclosure.length, | |
340 | 'type': enclosure.mime_type, |
|
340 | 'type': enclosure.mime_type, | |
341 | }) |
|
341 | }) | |
342 |
|
342 | |||
343 | # Categories. |
|
343 | # Categories. | |
344 | for cat in item['categories']: |
|
344 | for cat in item['categories']: | |
345 | handler.addQuickElement("category", cat) |
|
345 | handler.addQuickElement("category", cat) | |
346 |
|
346 | |||
347 |
|
347 | |||
348 | class Atom1Feed(SyndicationFeed): |
|
348 | class Atom1Feed(SyndicationFeed): | |
349 | # Spec: https://tools.ietf.org/html/rfc4287 |
|
349 | # Spec: https://tools.ietf.org/html/rfc4287 | |
350 | content_type = 'application/atom+xml; charset=utf-8' |
|
350 | content_type = 'application/atom+xml; charset=utf-8' | |
351 | ns = "http://www.w3.org/2005/Atom" |
|
351 | ns = "http://www.w3.org/2005/Atom" | |
352 |
|
352 | |||
353 | def write(self, outfile, encoding): |
|
353 | def write(self, outfile, encoding): | |
354 | handler = SimplerXMLGenerator(outfile, encoding) |
|
354 | handler = SimplerXMLGenerator(outfile, encoding) | |
355 | handler.startDocument() |
|
355 | handler.startDocument() | |
356 | handler.startElement('feed', self.root_attributes()) |
|
356 | handler.startElement('feed', self.root_attributes()) | |
357 | self.add_root_elements(handler) |
|
357 | self.add_root_elements(handler) | |
358 | self.write_items(handler) |
|
358 | self.write_items(handler) | |
359 | handler.endElement("feed") |
|
359 | handler.endElement("feed") | |
360 |
|
360 | |||
361 | def root_attributes(self): |
|
361 | def root_attributes(self): | |
362 | if self.feed['language'] is not None: |
|
362 | if self.feed['language'] is not None: | |
363 | return {"xmlns": self.ns, "xml:lang": self.feed['language']} |
|
363 | return {"xmlns": self.ns, "xml:lang": self.feed['language']} | |
364 | else: |
|
364 | else: | |
365 | return {"xmlns": self.ns} |
|
365 | return {"xmlns": self.ns} | |
366 |
|
366 | |||
367 | def add_root_elements(self, handler): |
|
367 | def add_root_elements(self, handler): | |
368 | handler.addQuickElement("title", self.feed['title']) |
|
368 | handler.addQuickElement("title", self.feed['title']) | |
369 | handler.addQuickElement("link", "", {"rel": "alternate", "href": self.feed['link']}) |
|
369 | handler.addQuickElement("link", "", {"rel": "alternate", "href": self.feed['link']}) | |
370 | if self.feed['feed_url'] is not None: |
|
370 | if self.feed['feed_url'] is not None: | |
371 | handler.addQuickElement("link", "", {"rel": "self", "href": self.feed['feed_url']}) |
|
371 | handler.addQuickElement("link", "", {"rel": "self", "href": self.feed['feed_url']}) | |
372 | handler.addQuickElement("id", self.feed['id']) |
|
372 | handler.addQuickElement("id", self.feed['id']) | |
373 | handler.addQuickElement("updated", rfc3339_date(self.latest_post_date())) |
|
373 | handler.addQuickElement("updated", rfc3339_date(self.latest_post_date())) | |
374 | if self.feed['author_name'] is not None: |
|
374 | if self.feed['author_name'] is not None: | |
375 | handler.startElement("author", {}) |
|
375 | handler.startElement("author", {}) | |
376 | handler.addQuickElement("name", self.feed['author_name']) |
|
376 | handler.addQuickElement("name", self.feed['author_name']) | |
377 | if self.feed['author_email'] is not None: |
|
377 | if self.feed['author_email'] is not None: | |
378 | handler.addQuickElement("email", self.feed['author_email']) |
|
378 | handler.addQuickElement("email", self.feed['author_email']) | |
379 | if self.feed['author_link'] is not None: |
|
379 | if self.feed['author_link'] is not None: | |
380 | handler.addQuickElement("uri", self.feed['author_link']) |
|
380 | handler.addQuickElement("uri", self.feed['author_link']) | |
381 | handler.endElement("author") |
|
381 | handler.endElement("author") | |
382 | if self.feed['subtitle'] is not None: |
|
382 | if self.feed['subtitle'] is not None: | |
383 | handler.addQuickElement("subtitle", self.feed['subtitle']) |
|
383 | handler.addQuickElement("subtitle", self.feed['subtitle']) | |
384 | for cat in self.feed['categories']: |
|
384 | for cat in self.feed['categories']: | |
385 | handler.addQuickElement("category", "", {"term": cat}) |
|
385 | handler.addQuickElement("category", "", {"term": cat}) | |
386 | if self.feed['feed_copyright'] is not None: |
|
386 | if self.feed['feed_copyright'] is not None: | |
387 | handler.addQuickElement("rights", self.feed['feed_copyright']) |
|
387 | handler.addQuickElement("rights", self.feed['feed_copyright']) | |
388 |
|
388 | |||
389 | def write_items(self, handler): |
|
389 | def write_items(self, handler): | |
390 | for item in self.items: |
|
390 | for item in self.items: | |
391 | handler.startElement("entry", self.item_attributes(item)) |
|
391 | handler.startElement("entry", self.item_attributes(item)) | |
392 | self.add_item_elements(handler, item) |
|
392 | self.add_item_elements(handler, item) | |
393 | handler.endElement("entry") |
|
393 | handler.endElement("entry") | |
394 |
|
394 | |||
395 | def add_item_elements(self, handler, item): |
|
395 | def add_item_elements(self, handler, item): | |
396 | handler.addQuickElement("title", item['title']) |
|
396 | handler.addQuickElement("title", item['title']) | |
397 | handler.addQuickElement("link", "", {"href": item['link'], "rel": "alternate"}) |
|
397 | handler.addQuickElement("link", "", {"href": item['link'], "rel": "alternate"}) | |
398 |
|
398 | |||
399 | if item['pubdate'] is not None: |
|
399 | if item['pubdate'] is not None: | |
400 | handler.addQuickElement('published', rfc3339_date(item['pubdate'])) |
|
400 | handler.addQuickElement('published', rfc3339_date(item['pubdate'])) | |
401 |
|
401 | |||
402 | if item['updateddate'] is not None: |
|
402 | if item['updateddate'] is not None: | |
403 | handler.addQuickElement('updated', rfc3339_date(item['updateddate'])) |
|
403 | handler.addQuickElement('updated', rfc3339_date(item['updateddate'])) | |
404 |
|
404 | |||
405 | # Author information. |
|
405 | # Author information. | |
406 | if item['author_name'] is not None: |
|
406 | if item['author_name'] is not None: | |
407 | handler.startElement("author", {}) |
|
407 | handler.startElement("author", {}) | |
408 | handler.addQuickElement("name", item['author_name']) |
|
408 | handler.addQuickElement("name", item['author_name']) | |
409 | if item['author_email'] is not None: |
|
409 | if item['author_email'] is not None: | |
410 | handler.addQuickElement("email", item['author_email']) |
|
410 | handler.addQuickElement("email", item['author_email']) | |
411 | if item['author_link'] is not None: |
|
411 | if item['author_link'] is not None: | |
412 | handler.addQuickElement("uri", item['author_link']) |
|
412 | handler.addQuickElement("uri", item['author_link']) | |
413 | handler.endElement("author") |
|
413 | handler.endElement("author") | |
414 |
|
414 | |||
415 | # Unique ID. |
|
415 | # Unique ID. | |
416 | if item['unique_id'] is not None: |
|
416 | if item['unique_id'] is not None: | |
417 | unique_id = item['unique_id'] |
|
417 | unique_id = item['unique_id'] | |
418 | else: |
|
418 | else: | |
419 | unique_id = get_tag_uri(item['link'], item['pubdate']) |
|
419 | unique_id = get_tag_uri(item['link'], item['pubdate']) | |
420 | handler.addQuickElement("id", unique_id) |
|
420 | handler.addQuickElement("id", unique_id) | |
421 |
|
421 | |||
422 | # Summary. |
|
422 | # Summary. | |
423 | if item['description'] is not None: |
|
423 | if item['description'] is not None: | |
424 | handler.addQuickElement("summary", item['description'], {"type": "html"}) |
|
424 | handler.addQuickElement("summary", item['description'], {"type": "html"}) | |
425 |
|
425 | |||
426 | # Enclosures. |
|
426 | # Enclosures. | |
427 | for enclosure in item['enclosures']: |
|
427 | for enclosure in item['enclosures']: | |
428 | handler.addQuickElement('link', '', { |
|
428 | handler.addQuickElement('link', '', { | |
429 | 'rel': 'enclosure', |
|
429 | 'rel': 'enclosure', | |
430 | 'href': enclosure.url, |
|
430 | 'href': enclosure.url, | |
431 | 'length': enclosure.length, |
|
431 | 'length': enclosure.length, | |
432 | 'type': enclosure.mime_type, |
|
432 | 'type': enclosure.mime_type, | |
433 | }) |
|
433 | }) | |
434 |
|
434 | |||
435 | # Categories. |
|
435 | # Categories. | |
436 | for cat in item['categories']: |
|
436 | for cat in item['categories']: | |
437 | handler.addQuickElement("category", "", {"term": cat}) |
|
437 | handler.addQuickElement("category", "", {"term": cat}) | |
438 |
|
438 | |||
439 | # Rights. |
|
439 | # Rights. | |
440 | if item['item_copyright'] is not None: |
|
440 | if item['item_copyright'] is not None: | |
441 | handler.addQuickElement("rights", item['item_copyright']) |
|
441 | handler.addQuickElement("rights", item['item_copyright']) | |
442 |
|
442 | |||
443 |
|
443 | |||
444 | # This isolates the decision of what the system default is, so calling code can |
|
444 | # This isolates the decision of what the system default is, so calling code can | |
445 | # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed". |
|
445 | # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed". | |
446 | DefaultFeed = Rss201rev2Feed No newline at end of file |
|
446 | DefaultFeed = Rss201rev2Feed |
@@ -1,2155 +1,2155 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
|
2 | |||
3 | # Copyright (C) 2010-2020 RhodeCode GmbH |
|
3 | # Copyright (C) 2010-2020 RhodeCode GmbH | |
4 | # |
|
4 | # | |
5 | # This program is free software: you can redistribute it and/or modify |
|
5 | # This program is free software: you can redistribute it and/or modify | |
6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
6 | # it under the terms of the GNU Affero General Public License, version 3 | |
7 | # (only), as published by the Free Software Foundation. |
|
7 | # (only), as published by the Free Software Foundation. | |
8 | # |
|
8 | # | |
9 | # This program is distributed in the hope that it will be useful, |
|
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. |
|
12 | # GNU General Public License for more details. | |
13 | # |
|
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License |
|
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | # |
|
16 | # | |
17 | # This program is dual-licensed. If you wish to learn more about the |
|
17 | # This program is dual-licensed. If you wish to learn more about the | |
18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |
20 |
|
20 | |||
21 | """ |
|
21 | """ | |
22 | Helper functions |
|
22 | Helper functions | |
23 |
|
23 | |||
24 | Consists of functions to typically be used within templates, but also |
|
24 | Consists of functions to typically be used within templates, but also | |
25 | available to Controllers. This module is available to both as 'h'. |
|
25 | available to Controllers. This module is available to both as 'h'. | |
26 | """ |
|
26 | """ | |
27 | import base64 |
|
27 | import base64 | |
28 | import collections |
|
28 | import collections | |
29 |
|
29 | |||
30 | import os |
|
30 | import os | |
31 | import random |
|
31 | import random | |
32 | import hashlib |
|
32 | import hashlib | |
33 | import StringIO |
|
33 | from io import StringIO | |
34 | import textwrap |
|
34 | import textwrap | |
35 | import urllib.request, urllib.parse, urllib.error |
|
35 | import urllib.request, urllib.parse, urllib.error | |
36 | import math |
|
36 | import math | |
37 | import logging |
|
37 | import logging | |
38 | import re |
|
38 | import re | |
39 | import time |
|
39 | import time | |
40 | import string |
|
40 | import string | |
41 | import hashlib |
|
41 | import hashlib | |
42 | import regex |
|
42 | import regex | |
43 | from collections import OrderedDict |
|
43 | from collections import OrderedDict | |
44 |
|
44 | |||
45 | import pygments |
|
45 | import pygments | |
46 | import itertools |
|
46 | import itertools | |
47 | import fnmatch |
|
47 | import fnmatch | |
48 | import bleach |
|
48 | import bleach | |
49 |
|
49 | |||
50 | from datetime import datetime |
|
50 | from datetime import datetime | |
51 | from functools import partial |
|
51 | from functools import partial | |
52 | from pygments.formatters.html import HtmlFormatter |
|
52 | from pygments.formatters.html import HtmlFormatter | |
53 | from pygments.lexers import ( |
|
53 | from pygments.lexers import ( | |
54 | get_lexer_by_name, get_lexer_for_filename, get_lexer_for_mimetype) |
|
54 | get_lexer_by_name, get_lexer_for_filename, get_lexer_for_mimetype) | |
55 |
|
55 | |||
56 | from pyramid.threadlocal import get_current_request |
|
56 | from pyramid.threadlocal import get_current_request | |
57 | from tempita import looper |
|
57 | from tempita import looper | |
58 | from webhelpers2.html import literal, HTML, escape |
|
58 | from webhelpers2.html import literal, HTML, escape | |
59 | from webhelpers2.html._autolink import _auto_link_urls |
|
59 | from webhelpers2.html._autolink import _auto_link_urls | |
60 | from webhelpers2.html.tools import ( |
|
60 | from webhelpers2.html.tools import ( | |
61 | button_to, highlight, js_obfuscate, strip_links, strip_tags) |
|
61 | button_to, highlight, js_obfuscate, strip_links, strip_tags) | |
62 |
|
62 | |||
63 | from webhelpers2.text import ( |
|
63 | from webhelpers2.text import ( | |
64 | chop_at, collapse, convert_accented_entities, |
|
64 | chop_at, collapse, convert_accented_entities, | |
65 | convert_misc_entities, lchop, plural, rchop, remove_formatting, |
|
65 | convert_misc_entities, lchop, plural, rchop, remove_formatting, | |
66 | replace_whitespace, urlify, truncate, wrap_paragraphs) |
|
66 | replace_whitespace, urlify, truncate, wrap_paragraphs) | |
67 | from webhelpers2.date import time_ago_in_words |
|
67 | from webhelpers2.date import time_ago_in_words | |
68 |
|
68 | |||
69 | from webhelpers2.html.tags import ( |
|
69 | from webhelpers2.html.tags import ( | |
70 | _input, NotGiven, _make_safe_id_component as safeid, |
|
70 | _input, NotGiven, _make_safe_id_component as safeid, | |
71 | form as insecure_form, |
|
71 | form as insecure_form, | |
72 | auto_discovery_link, checkbox, end_form, file, |
|
72 | auto_discovery_link, checkbox, end_form, file, | |
73 | hidden, image, javascript_link, link_to, link_to_if, link_to_unless, ol, |
|
73 | hidden, image, javascript_link, link_to, link_to_if, link_to_unless, ol, | |
74 | select as raw_select, stylesheet_link, submit, text, password, textarea, |
|
74 | select as raw_select, stylesheet_link, submit, text, password, textarea, | |
75 | ul, radio, Options) |
|
75 | ul, radio, Options) | |
76 |
|
76 | |||
77 | from webhelpers2.number import format_byte_size |
|
77 | from webhelpers2.number import format_byte_size | |
78 |
|
78 | |||
79 | from rhodecode.lib.action_parser import action_parser |
|
79 | from rhodecode.lib.action_parser import action_parser | |
80 | from rhodecode.lib.pagination import Page, RepoPage, SqlPage |
|
80 | from rhodecode.lib.pagination import Page, RepoPage, SqlPage | |
81 | from rhodecode.lib.ext_json import json |
|
81 | from rhodecode.lib.ext_json import json | |
82 | from rhodecode.lib.utils import repo_name_slug, get_custom_lexer |
|
82 | from rhodecode.lib.utils import repo_name_slug, get_custom_lexer | |
83 | from rhodecode.lib.utils2 import ( |
|
83 | from rhodecode.lib.utils2 import ( | |
84 | str2bool, safe_unicode, safe_str, |
|
84 | str2bool, safe_unicode, safe_str, | |
85 | get_commit_safe, datetime_to_time, time_to_datetime, time_to_utcdatetime, |
|
85 | get_commit_safe, datetime_to_time, time_to_datetime, time_to_utcdatetime, | |
86 | AttributeDict, safe_int, md5, md5_safe, get_host_info) |
|
86 | AttributeDict, safe_int, md5, md5_safe, get_host_info) | |
87 | from rhodecode.lib.markup_renderer import MarkupRenderer, relative_links |
|
87 | from rhodecode.lib.markup_renderer import MarkupRenderer, relative_links | |
88 | from rhodecode.lib.vcs.exceptions import CommitDoesNotExistError |
|
88 | from rhodecode.lib.vcs.exceptions import CommitDoesNotExistError | |
89 | from rhodecode.lib.vcs.backends.base import BaseChangeset, EmptyCommit |
|
89 | from rhodecode.lib.vcs.backends.base import BaseChangeset, EmptyCommit | |
90 | from rhodecode.lib.vcs.conf.settings import ARCHIVE_SPECS |
|
90 | from rhodecode.lib.vcs.conf.settings import ARCHIVE_SPECS | |
91 | from rhodecode.lib.index.search_utils import get_matching_line_offsets |
|
91 | from rhodecode.lib.index.search_utils import get_matching_line_offsets | |
92 | from rhodecode.config.conf import DATE_FORMAT, DATETIME_FORMAT |
|
92 | from rhodecode.config.conf import DATE_FORMAT, DATETIME_FORMAT | |
93 | from rhodecode.model.changeset_status import ChangesetStatusModel |
|
93 | from rhodecode.model.changeset_status import ChangesetStatusModel | |
94 | from rhodecode.model.db import Permission, User, Repository, UserApiKeys, FileStore |
|
94 | from rhodecode.model.db import Permission, User, Repository, UserApiKeys, FileStore | |
95 | from rhodecode.model.repo_group import RepoGroupModel |
|
95 | from rhodecode.model.repo_group import RepoGroupModel | |
96 | from rhodecode.model.settings import IssueTrackerSettingsModel |
|
96 | from rhodecode.model.settings import IssueTrackerSettingsModel | |
97 |
|
97 | |||
98 |
|
98 | |||
99 | log = logging.getLogger(__name__) |
|
99 | log = logging.getLogger(__name__) | |
100 |
|
100 | |||
101 |
|
101 | |||
102 | DEFAULT_USER = User.DEFAULT_USER |
|
102 | DEFAULT_USER = User.DEFAULT_USER | |
103 | DEFAULT_USER_EMAIL = User.DEFAULT_USER_EMAIL |
|
103 | DEFAULT_USER_EMAIL = User.DEFAULT_USER_EMAIL | |
104 |
|
104 | |||
105 |
|
105 | |||
106 | def asset(path, ver=None, **kwargs): |
|
106 | def asset(path, ver=None, **kwargs): | |
107 | """ |
|
107 | """ | |
108 | Helper to generate a static asset file path for rhodecode assets |
|
108 | Helper to generate a static asset file path for rhodecode assets | |
109 |
|
109 | |||
110 | eg. h.asset('images/image.png', ver='3923') |
|
110 | eg. h.asset('images/image.png', ver='3923') | |
111 |
|
111 | |||
112 | :param path: path of asset |
|
112 | :param path: path of asset | |
113 | :param ver: optional version query param to append as ?ver= |
|
113 | :param ver: optional version query param to append as ?ver= | |
114 | """ |
|
114 | """ | |
115 | request = get_current_request() |
|
115 | request = get_current_request() | |
116 | query = {} |
|
116 | query = {} | |
117 | query.update(kwargs) |
|
117 | query.update(kwargs) | |
118 | if ver: |
|
118 | if ver: | |
119 | query = {'ver': ver} |
|
119 | query = {'ver': ver} | |
120 | return request.static_path( |
|
120 | return request.static_path( | |
121 | 'rhodecode:public/{}'.format(path), _query=query) |
|
121 | 'rhodecode:public/{}'.format(path), _query=query) | |
122 |
|
122 | |||
123 |
|
123 | |||
124 | default_html_escape_table = { |
|
124 | default_html_escape_table = { | |
125 | ord('&'): u'&', |
|
125 | ord('&'): u'&', | |
126 | ord('<'): u'<', |
|
126 | ord('<'): u'<', | |
127 | ord('>'): u'>', |
|
127 | ord('>'): u'>', | |
128 | ord('"'): u'"', |
|
128 | ord('"'): u'"', | |
129 | ord("'"): u''', |
|
129 | ord("'"): u''', | |
130 | } |
|
130 | } | |
131 |
|
131 | |||
132 |
|
132 | |||
133 | def html_escape(text, html_escape_table=default_html_escape_table): |
|
133 | def html_escape(text, html_escape_table=default_html_escape_table): | |
134 | """Produce entities within text.""" |
|
134 | """Produce entities within text.""" | |
135 | return text.translate(html_escape_table) |
|
135 | return text.translate(html_escape_table) | |
136 |
|
136 | |||
137 |
|
137 | |||
138 | def chop_at_smart(s, sub, inclusive=False, suffix_if_chopped=None): |
|
138 | def chop_at_smart(s, sub, inclusive=False, suffix_if_chopped=None): | |
139 | """ |
|
139 | """ | |
140 | Truncate string ``s`` at the first occurrence of ``sub``. |
|
140 | Truncate string ``s`` at the first occurrence of ``sub``. | |
141 |
|
141 | |||
142 | If ``inclusive`` is true, truncate just after ``sub`` rather than at it. |
|
142 | If ``inclusive`` is true, truncate just after ``sub`` rather than at it. | |
143 | """ |
|
143 | """ | |
144 | suffix_if_chopped = suffix_if_chopped or '' |
|
144 | suffix_if_chopped = suffix_if_chopped or '' | |
145 | pos = s.find(sub) |
|
145 | pos = s.find(sub) | |
146 | if pos == -1: |
|
146 | if pos == -1: | |
147 | return s |
|
147 | return s | |
148 |
|
148 | |||
149 | if inclusive: |
|
149 | if inclusive: | |
150 | pos += len(sub) |
|
150 | pos += len(sub) | |
151 |
|
151 | |||
152 | chopped = s[:pos] |
|
152 | chopped = s[:pos] | |
153 | left = s[pos:].strip() |
|
153 | left = s[pos:].strip() | |
154 |
|
154 | |||
155 | if left and suffix_if_chopped: |
|
155 | if left and suffix_if_chopped: | |
156 | chopped += suffix_if_chopped |
|
156 | chopped += suffix_if_chopped | |
157 |
|
157 | |||
158 | return chopped |
|
158 | return chopped | |
159 |
|
159 | |||
160 |
|
160 | |||
161 | def shorter(text, size=20, prefix=False): |
|
161 | def shorter(text, size=20, prefix=False): | |
162 | postfix = '...' |
|
162 | postfix = '...' | |
163 | if len(text) > size: |
|
163 | if len(text) > size: | |
164 | if prefix: |
|
164 | if prefix: | |
165 | # shorten in front |
|
165 | # shorten in front | |
166 | return postfix + text[-(size - len(postfix)):] |
|
166 | return postfix + text[-(size - len(postfix)):] | |
167 | else: |
|
167 | else: | |
168 | return text[:size - len(postfix)] + postfix |
|
168 | return text[:size - len(postfix)] + postfix | |
169 | return text |
|
169 | return text | |
170 |
|
170 | |||
171 |
|
171 | |||
172 | def reset(name, value=None, id=NotGiven, type="reset", **attrs): |
|
172 | def reset(name, value=None, id=NotGiven, type="reset", **attrs): | |
173 | """ |
|
173 | """ | |
174 | Reset button |
|
174 | Reset button | |
175 | """ |
|
175 | """ | |
176 | return _input(type, name, value, id, attrs) |
|
176 | return _input(type, name, value, id, attrs) | |
177 |
|
177 | |||
178 |
|
178 | |||
179 | def select(name, selected_values, options, id=NotGiven, **attrs): |
|
179 | def select(name, selected_values, options, id=NotGiven, **attrs): | |
180 |
|
180 | |||
181 | if isinstance(options, (list, tuple)): |
|
181 | if isinstance(options, (list, tuple)): | |
182 | options_iter = options |
|
182 | options_iter = options | |
183 | # Handle old value,label lists ... where value also can be value,label lists |
|
183 | # Handle old value,label lists ... where value also can be value,label lists | |
184 | options = Options() |
|
184 | options = Options() | |
185 | for opt in options_iter: |
|
185 | for opt in options_iter: | |
186 | if isinstance(opt, tuple) and len(opt) == 2: |
|
186 | if isinstance(opt, tuple) and len(opt) == 2: | |
187 | value, label = opt |
|
187 | value, label = opt | |
188 | elif isinstance(opt, str): |
|
188 | elif isinstance(opt, str): | |
189 | value = label = opt |
|
189 | value = label = opt | |
190 | else: |
|
190 | else: | |
191 | raise ValueError('invalid select option type %r' % type(opt)) |
|
191 | raise ValueError('invalid select option type %r' % type(opt)) | |
192 |
|
192 | |||
193 | if isinstance(value, (list, tuple)): |
|
193 | if isinstance(value, (list, tuple)): | |
194 | option_group = options.add_optgroup(label) |
|
194 | option_group = options.add_optgroup(label) | |
195 | for opt2 in value: |
|
195 | for opt2 in value: | |
196 | if isinstance(opt2, tuple) and len(opt2) == 2: |
|
196 | if isinstance(opt2, tuple) and len(opt2) == 2: | |
197 | group_value, group_label = opt2 |
|
197 | group_value, group_label = opt2 | |
198 | elif isinstance(opt2, str): |
|
198 | elif isinstance(opt2, str): | |
199 | group_value = group_label = opt2 |
|
199 | group_value = group_label = opt2 | |
200 | else: |
|
200 | else: | |
201 | raise ValueError('invalid select option type %r' % type(opt2)) |
|
201 | raise ValueError('invalid select option type %r' % type(opt2)) | |
202 |
|
202 | |||
203 | option_group.add_option(group_label, group_value) |
|
203 | option_group.add_option(group_label, group_value) | |
204 | else: |
|
204 | else: | |
205 | options.add_option(label, value) |
|
205 | options.add_option(label, value) | |
206 |
|
206 | |||
207 | return raw_select(name, selected_values, options, id=id, **attrs) |
|
207 | return raw_select(name, selected_values, options, id=id, **attrs) | |
208 |
|
208 | |||
209 |
|
209 | |||
210 | def branding(name, length=40): |
|
210 | def branding(name, length=40): | |
211 | return truncate(name, length, indicator="") |
|
211 | return truncate(name, length, indicator="") | |
212 |
|
212 | |||
213 |
|
213 | |||
214 | def FID(raw_id, path): |
|
214 | def FID(raw_id, path): | |
215 | """ |
|
215 | """ | |
216 | Creates a unique ID for filenode based on it's hash of path and commit |
|
216 | Creates a unique ID for filenode based on it's hash of path and commit | |
217 | it's safe to use in urls |
|
217 | it's safe to use in urls | |
218 |
|
218 | |||
219 | :param raw_id: |
|
219 | :param raw_id: | |
220 | :param path: |
|
220 | :param path: | |
221 | """ |
|
221 | """ | |
222 |
|
222 | |||
223 | return 'c-%s-%s' % (short_id(raw_id), md5_safe(path)[:12]) |
|
223 | return 'c-%s-%s' % (short_id(raw_id), md5_safe(path)[:12]) | |
224 |
|
224 | |||
225 |
|
225 | |||
226 | class _GetError(object): |
|
226 | class _GetError(object): | |
227 | """Get error from form_errors, and represent it as span wrapped error |
|
227 | """Get error from form_errors, and represent it as span wrapped error | |
228 | message |
|
228 | message | |
229 |
|
229 | |||
230 | :param field_name: field to fetch errors for |
|
230 | :param field_name: field to fetch errors for | |
231 | :param form_errors: form errors dict |
|
231 | :param form_errors: form errors dict | |
232 | """ |
|
232 | """ | |
233 |
|
233 | |||
234 | def __call__(self, field_name, form_errors): |
|
234 | def __call__(self, field_name, form_errors): | |
235 | tmpl = """<span class="error_msg">%s</span>""" |
|
235 | tmpl = """<span class="error_msg">%s</span>""" | |
236 | if form_errors and field_name in form_errors: |
|
236 | if form_errors and field_name in form_errors: | |
237 | return literal(tmpl % form_errors.get(field_name)) |
|
237 | return literal(tmpl % form_errors.get(field_name)) | |
238 |
|
238 | |||
239 |
|
239 | |||
240 | get_error = _GetError() |
|
240 | get_error = _GetError() | |
241 |
|
241 | |||
242 |
|
242 | |||
243 | class _ToolTip(object): |
|
243 | class _ToolTip(object): | |
244 |
|
244 | |||
245 | def __call__(self, tooltip_title, trim_at=50): |
|
245 | def __call__(self, tooltip_title, trim_at=50): | |
246 | """ |
|
246 | """ | |
247 | Special function just to wrap our text into nice formatted |
|
247 | Special function just to wrap our text into nice formatted | |
248 | autowrapped text |
|
248 | autowrapped text | |
249 |
|
249 | |||
250 | :param tooltip_title: |
|
250 | :param tooltip_title: | |
251 | """ |
|
251 | """ | |
252 | tooltip_title = escape(tooltip_title) |
|
252 | tooltip_title = escape(tooltip_title) | |
253 | tooltip_title = tooltip_title.replace('<', '<').replace('>', '>') |
|
253 | tooltip_title = tooltip_title.replace('<', '<').replace('>', '>') | |
254 | return tooltip_title |
|
254 | return tooltip_title | |
255 |
|
255 | |||
256 |
|
256 | |||
257 | tooltip = _ToolTip() |
|
257 | tooltip = _ToolTip() | |
258 |
|
258 | |||
259 | files_icon = u'<i class="file-breadcrumb-copy tooltip icon-clipboard clipboard-action" data-clipboard-text="{}" title="Copy file path"></i>' |
|
259 | files_icon = u'<i class="file-breadcrumb-copy tooltip icon-clipboard clipboard-action" data-clipboard-text="{}" title="Copy file path"></i>' | |
260 |
|
260 | |||
261 |
|
261 | |||
262 | def files_breadcrumbs(repo_name, repo_type, commit_id, file_path, landing_ref_name=None, at_ref=None, |
|
262 | def files_breadcrumbs(repo_name, repo_type, commit_id, file_path, landing_ref_name=None, at_ref=None, | |
263 | limit_items=False, linkify_last_item=False, hide_last_item=False, |
|
263 | limit_items=False, linkify_last_item=False, hide_last_item=False, | |
264 | copy_path_icon=True): |
|
264 | copy_path_icon=True): | |
265 | if isinstance(file_path, str): |
|
265 | if isinstance(file_path, str): | |
266 | file_path = safe_unicode(file_path) |
|
266 | file_path = safe_unicode(file_path) | |
267 |
|
267 | |||
268 | if at_ref: |
|
268 | if at_ref: | |
269 | route_qry = {'at': at_ref} |
|
269 | route_qry = {'at': at_ref} | |
270 | default_landing_ref = at_ref or landing_ref_name or commit_id |
|
270 | default_landing_ref = at_ref or landing_ref_name or commit_id | |
271 | else: |
|
271 | else: | |
272 | route_qry = None |
|
272 | route_qry = None | |
273 | default_landing_ref = commit_id |
|
273 | default_landing_ref = commit_id | |
274 |
|
274 | |||
275 | # first segment is a `HOME` link to repo files root location |
|
275 | # first segment is a `HOME` link to repo files root location | |
276 | root_name = literal(u'<i class="icon-home"></i>') |
|
276 | root_name = literal(u'<i class="icon-home"></i>') | |
277 |
|
277 | |||
278 | url_segments = [ |
|
278 | url_segments = [ | |
279 | link_to( |
|
279 | link_to( | |
280 | root_name, |
|
280 | root_name, | |
281 | repo_files_by_ref_url( |
|
281 | repo_files_by_ref_url( | |
282 | repo_name, |
|
282 | repo_name, | |
283 | repo_type, |
|
283 | repo_type, | |
284 | f_path=None, # None here is a special case for SVN repos, |
|
284 | f_path=None, # None here is a special case for SVN repos, | |
285 | # that won't prefix with a ref |
|
285 | # that won't prefix with a ref | |
286 | ref_name=default_landing_ref, |
|
286 | ref_name=default_landing_ref, | |
287 | commit_id=commit_id, |
|
287 | commit_id=commit_id, | |
288 | query=route_qry |
|
288 | query=route_qry | |
289 | ) |
|
289 | ) | |
290 | )] |
|
290 | )] | |
291 |
|
291 | |||
292 | path_segments = file_path.split('/') |
|
292 | path_segments = file_path.split('/') | |
293 | last_cnt = len(path_segments) - 1 |
|
293 | last_cnt = len(path_segments) - 1 | |
294 | for cnt, segment in enumerate(path_segments): |
|
294 | for cnt, segment in enumerate(path_segments): | |
295 | if not segment: |
|
295 | if not segment: | |
296 | continue |
|
296 | continue | |
297 | segment_html = escape(segment) |
|
297 | segment_html = escape(segment) | |
298 |
|
298 | |||
299 | last_item = cnt == last_cnt |
|
299 | last_item = cnt == last_cnt | |
300 |
|
300 | |||
301 | if last_item and hide_last_item: |
|
301 | if last_item and hide_last_item: | |
302 | # iterate over and hide last element |
|
302 | # iterate over and hide last element | |
303 | continue |
|
303 | continue | |
304 |
|
304 | |||
305 | if last_item and linkify_last_item is False: |
|
305 | if last_item and linkify_last_item is False: | |
306 | # plain version |
|
306 | # plain version | |
307 | url_segments.append(segment_html) |
|
307 | url_segments.append(segment_html) | |
308 | else: |
|
308 | else: | |
309 | url_segments.append( |
|
309 | url_segments.append( | |
310 | link_to( |
|
310 | link_to( | |
311 | segment_html, |
|
311 | segment_html, | |
312 | repo_files_by_ref_url( |
|
312 | repo_files_by_ref_url( | |
313 | repo_name, |
|
313 | repo_name, | |
314 | repo_type, |
|
314 | repo_type, | |
315 | f_path='/'.join(path_segments[:cnt + 1]), |
|
315 | f_path='/'.join(path_segments[:cnt + 1]), | |
316 | ref_name=default_landing_ref, |
|
316 | ref_name=default_landing_ref, | |
317 | commit_id=commit_id, |
|
317 | commit_id=commit_id, | |
318 | query=route_qry |
|
318 | query=route_qry | |
319 | ), |
|
319 | ), | |
320 | )) |
|
320 | )) | |
321 |
|
321 | |||
322 | limited_url_segments = url_segments[:1] + ['...'] + url_segments[-5:] |
|
322 | limited_url_segments = url_segments[:1] + ['...'] + url_segments[-5:] | |
323 | if limit_items and len(limited_url_segments) < len(url_segments): |
|
323 | if limit_items and len(limited_url_segments) < len(url_segments): | |
324 | url_segments = limited_url_segments |
|
324 | url_segments = limited_url_segments | |
325 |
|
325 | |||
326 | full_path = file_path |
|
326 | full_path = file_path | |
327 | if copy_path_icon: |
|
327 | if copy_path_icon: | |
328 | icon = files_icon.format(escape(full_path)) |
|
328 | icon = files_icon.format(escape(full_path)) | |
329 | else: |
|
329 | else: | |
330 | icon = '' |
|
330 | icon = '' | |
331 |
|
331 | |||
332 | if file_path == '': |
|
332 | if file_path == '': | |
333 | return root_name |
|
333 | return root_name | |
334 | else: |
|
334 | else: | |
335 | return literal(' / '.join(url_segments) + icon) |
|
335 | return literal(' / '.join(url_segments) + icon) | |
336 |
|
336 | |||
337 |
|
337 | |||
338 | def files_url_data(request): |
|
338 | def files_url_data(request): | |
339 | import urllib.request, urllib.parse, urllib.error |
|
339 | import urllib.request, urllib.parse, urllib.error | |
340 | matchdict = request.matchdict |
|
340 | matchdict = request.matchdict | |
341 |
|
341 | |||
342 | if 'f_path' not in matchdict: |
|
342 | if 'f_path' not in matchdict: | |
343 | matchdict['f_path'] = '' |
|
343 | matchdict['f_path'] = '' | |
344 | else: |
|
344 | else: | |
345 | matchdict['f_path'] = urllib.parse.quote(safe_str(matchdict['f_path'])) |
|
345 | matchdict['f_path'] = urllib.parse.quote(safe_str(matchdict['f_path'])) | |
346 | if 'commit_id' not in matchdict: |
|
346 | if 'commit_id' not in matchdict: | |
347 | matchdict['commit_id'] = 'tip' |
|
347 | matchdict['commit_id'] = 'tip' | |
348 |
|
348 | |||
349 | return json.dumps(matchdict) |
|
349 | return json.dumps(matchdict) | |
350 |
|
350 | |||
351 |
|
351 | |||
352 | def repo_files_by_ref_url(db_repo_name, db_repo_type, f_path, ref_name, commit_id, query=None, ): |
|
352 | def repo_files_by_ref_url(db_repo_name, db_repo_type, f_path, ref_name, commit_id, query=None, ): | |
353 | _is_svn = is_svn(db_repo_type) |
|
353 | _is_svn = is_svn(db_repo_type) | |
354 | final_f_path = f_path |
|
354 | final_f_path = f_path | |
355 |
|
355 | |||
356 | if _is_svn: |
|
356 | if _is_svn: | |
357 | """ |
|
357 | """ | |
358 | For SVN the ref_name cannot be used as a commit_id, it needs to be prefixed with |
|
358 | For SVN the ref_name cannot be used as a commit_id, it needs to be prefixed with | |
359 | actually commit_id followed by the ref_name. This should be done only in case |
|
359 | actually commit_id followed by the ref_name. This should be done only in case | |
360 | This is a initial landing url, without additional paths. |
|
360 | This is a initial landing url, without additional paths. | |
361 |
|
361 | |||
362 | like: /1000/tags/1.0.0/?at=tags/1.0.0 |
|
362 | like: /1000/tags/1.0.0/?at=tags/1.0.0 | |
363 | """ |
|
363 | """ | |
364 |
|
364 | |||
365 | if ref_name and ref_name != 'tip': |
|
365 | if ref_name and ref_name != 'tip': | |
366 | # NOTE(marcink): for svn the ref_name is actually the stored path, so we prefix it |
|
366 | # NOTE(marcink): for svn the ref_name is actually the stored path, so we prefix it | |
367 | # for SVN we only do this magic prefix if it's root, .eg landing revision |
|
367 | # for SVN we only do this magic prefix if it's root, .eg landing revision | |
368 | # of files link. If we are in the tree we don't need this since we traverse the url |
|
368 | # of files link. If we are in the tree we don't need this since we traverse the url | |
369 | # that has everything stored |
|
369 | # that has everything stored | |
370 | if f_path in ['', '/']: |
|
370 | if f_path in ['', '/']: | |
371 | final_f_path = '/'.join([ref_name, f_path]) |
|
371 | final_f_path = '/'.join([ref_name, f_path]) | |
372 |
|
372 | |||
373 | # SVN always needs a commit_id explicitly, without a named REF |
|
373 | # SVN always needs a commit_id explicitly, without a named REF | |
374 | default_commit_id = commit_id |
|
374 | default_commit_id = commit_id | |
375 | else: |
|
375 | else: | |
376 | """ |
|
376 | """ | |
377 | For git and mercurial we construct a new URL using the names instead of commit_id |
|
377 | For git and mercurial we construct a new URL using the names instead of commit_id | |
378 | like: /master/some_path?at=master |
|
378 | like: /master/some_path?at=master | |
379 | """ |
|
379 | """ | |
380 | # We currently do not support branches with slashes |
|
380 | # We currently do not support branches with slashes | |
381 | if '/' in ref_name: |
|
381 | if '/' in ref_name: | |
382 | default_commit_id = commit_id |
|
382 | default_commit_id = commit_id | |
383 | else: |
|
383 | else: | |
384 | default_commit_id = ref_name |
|
384 | default_commit_id = ref_name | |
385 |
|
385 | |||
386 | # sometimes we pass f_path as None, to indicate explicit no prefix, |
|
386 | # sometimes we pass f_path as None, to indicate explicit no prefix, | |
387 | # we translate it to string to not have None |
|
387 | # we translate it to string to not have None | |
388 | final_f_path = final_f_path or '' |
|
388 | final_f_path = final_f_path or '' | |
389 |
|
389 | |||
390 | files_url = route_path( |
|
390 | files_url = route_path( | |
391 | 'repo_files', |
|
391 | 'repo_files', | |
392 | repo_name=db_repo_name, |
|
392 | repo_name=db_repo_name, | |
393 | commit_id=default_commit_id, |
|
393 | commit_id=default_commit_id, | |
394 | f_path=final_f_path, |
|
394 | f_path=final_f_path, | |
395 | _query=query |
|
395 | _query=query | |
396 | ) |
|
396 | ) | |
397 | return files_url |
|
397 | return files_url | |
398 |
|
398 | |||
399 |
|
399 | |||
400 | def code_highlight(code, lexer, formatter, use_hl_filter=False): |
|
400 | def code_highlight(code, lexer, formatter, use_hl_filter=False): | |
401 | """ |
|
401 | """ | |
402 | Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``. |
|
402 | Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``. | |
403 |
|
403 | |||
404 | If ``outfile`` is given and a valid file object (an object |
|
404 | If ``outfile`` is given and a valid file object (an object | |
405 | with a ``write`` method), the result will be written to it, otherwise |
|
405 | with a ``write`` method), the result will be written to it, otherwise | |
406 | it is returned as a string. |
|
406 | it is returned as a string. | |
407 | """ |
|
407 | """ | |
408 | if use_hl_filter: |
|
408 | if use_hl_filter: | |
409 | # add HL filter |
|
409 | # add HL filter | |
410 | from rhodecode.lib.index import search_utils |
|
410 | from rhodecode.lib.index import search_utils | |
411 | lexer.add_filter(search_utils.ElasticSearchHLFilter()) |
|
411 | lexer.add_filter(search_utils.ElasticSearchHLFilter()) | |
412 | return pygments.format(pygments.lex(code, lexer), formatter) |
|
412 | return pygments.format(pygments.lex(code, lexer), formatter) | |
413 |
|
413 | |||
414 |
|
414 | |||
415 | class CodeHtmlFormatter(HtmlFormatter): |
|
415 | class CodeHtmlFormatter(HtmlFormatter): | |
416 | """ |
|
416 | """ | |
417 | My code Html Formatter for source codes |
|
417 | My code Html Formatter for source codes | |
418 | """ |
|
418 | """ | |
419 |
|
419 | |||
420 | def wrap(self, source, outfile): |
|
420 | def wrap(self, source, outfile): | |
421 | return self._wrap_div(self._wrap_pre(self._wrap_code(source))) |
|
421 | return self._wrap_div(self._wrap_pre(self._wrap_code(source))) | |
422 |
|
422 | |||
423 | def _wrap_code(self, source): |
|
423 | def _wrap_code(self, source): | |
424 | for cnt, it in enumerate(source): |
|
424 | for cnt, it in enumerate(source): | |
425 | i, t = it |
|
425 | i, t = it | |
426 | t = '<div id="L%s">%s</div>' % (cnt + 1, t) |
|
426 | t = '<div id="L%s">%s</div>' % (cnt + 1, t) | |
427 | yield i, t |
|
427 | yield i, t | |
428 |
|
428 | |||
429 | def _wrap_tablelinenos(self, inner): |
|
429 | def _wrap_tablelinenos(self, inner): | |
430 | dummyoutfile = StringIO.StringIO() |
|
430 | dummyoutfile = StringIO.StringIO() | |
431 | lncount = 0 |
|
431 | lncount = 0 | |
432 | for t, line in inner: |
|
432 | for t, line in inner: | |
433 | if t: |
|
433 | if t: | |
434 | lncount += 1 |
|
434 | lncount += 1 | |
435 | dummyoutfile.write(line) |
|
435 | dummyoutfile.write(line) | |
436 |
|
436 | |||
437 | fl = self.linenostart |
|
437 | fl = self.linenostart | |
438 | mw = len(str(lncount + fl - 1)) |
|
438 | mw = len(str(lncount + fl - 1)) | |
439 | sp = self.linenospecial |
|
439 | sp = self.linenospecial | |
440 | st = self.linenostep |
|
440 | st = self.linenostep | |
441 | la = self.lineanchors |
|
441 | la = self.lineanchors | |
442 | aln = self.anchorlinenos |
|
442 | aln = self.anchorlinenos | |
443 | nocls = self.noclasses |
|
443 | nocls = self.noclasses | |
444 | if sp: |
|
444 | if sp: | |
445 | lines = [] |
|
445 | lines = [] | |
446 |
|
446 | |||
447 | for i in range(fl, fl + lncount): |
|
447 | for i in range(fl, fl + lncount): | |
448 | if i % st == 0: |
|
448 | if i % st == 0: | |
449 | if i % sp == 0: |
|
449 | if i % sp == 0: | |
450 | if aln: |
|
450 | if aln: | |
451 | lines.append('<a href="#%s%d" class="special">%*d</a>' % |
|
451 | lines.append('<a href="#%s%d" class="special">%*d</a>' % | |
452 | (la, i, mw, i)) |
|
452 | (la, i, mw, i)) | |
453 | else: |
|
453 | else: | |
454 | lines.append('<span class="special">%*d</span>' % (mw, i)) |
|
454 | lines.append('<span class="special">%*d</span>' % (mw, i)) | |
455 | else: |
|
455 | else: | |
456 | if aln: |
|
456 | if aln: | |
457 | lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i)) |
|
457 | lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i)) | |
458 | else: |
|
458 | else: | |
459 | lines.append('%*d' % (mw, i)) |
|
459 | lines.append('%*d' % (mw, i)) | |
460 | else: |
|
460 | else: | |
461 | lines.append('') |
|
461 | lines.append('') | |
462 | ls = '\n'.join(lines) |
|
462 | ls = '\n'.join(lines) | |
463 | else: |
|
463 | else: | |
464 | lines = [] |
|
464 | lines = [] | |
465 | for i in range(fl, fl + lncount): |
|
465 | for i in range(fl, fl + lncount): | |
466 | if i % st == 0: |
|
466 | if i % st == 0: | |
467 | if aln: |
|
467 | if aln: | |
468 | lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i)) |
|
468 | lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i)) | |
469 | else: |
|
469 | else: | |
470 | lines.append('%*d' % (mw, i)) |
|
470 | lines.append('%*d' % (mw, i)) | |
471 | else: |
|
471 | else: | |
472 | lines.append('') |
|
472 | lines.append('') | |
473 | ls = '\n'.join(lines) |
|
473 | ls = '\n'.join(lines) | |
474 |
|
474 | |||
475 | # in case you wonder about the seemingly redundant <div> here: since the |
|
475 | # in case you wonder about the seemingly redundant <div> here: since the | |
476 | # content in the other cell also is wrapped in a div, some browsers in |
|
476 | # content in the other cell also is wrapped in a div, some browsers in | |
477 | # some configurations seem to mess up the formatting... |
|
477 | # some configurations seem to mess up the formatting... | |
478 | if nocls: |
|
478 | if nocls: | |
479 | yield 0, ('<table class="%stable">' % self.cssclass + |
|
479 | yield 0, ('<table class="%stable">' % self.cssclass + | |
480 | '<tr><td><div class="linenodiv" ' |
|
480 | '<tr><td><div class="linenodiv" ' | |
481 | 'style="background-color: #f0f0f0; padding-right: 10px">' |
|
481 | 'style="background-color: #f0f0f0; padding-right: 10px">' | |
482 | '<pre style="line-height: 125%">' + |
|
482 | '<pre style="line-height: 125%">' + | |
483 | ls + '</pre></div></td><td id="hlcode" class="code">') |
|
483 | ls + '</pre></div></td><td id="hlcode" class="code">') | |
484 | else: |
|
484 | else: | |
485 | yield 0, ('<table class="%stable">' % self.cssclass + |
|
485 | yield 0, ('<table class="%stable">' % self.cssclass + | |
486 | '<tr><td class="linenos"><div class="linenodiv"><pre>' + |
|
486 | '<tr><td class="linenos"><div class="linenodiv"><pre>' + | |
487 | ls + '</pre></div></td><td id="hlcode" class="code">') |
|
487 | ls + '</pre></div></td><td id="hlcode" class="code">') | |
488 | yield 0, dummyoutfile.getvalue() |
|
488 | yield 0, dummyoutfile.getvalue() | |
489 | yield 0, '</td></tr></table>' |
|
489 | yield 0, '</td></tr></table>' | |
490 |
|
490 | |||
491 |
|
491 | |||
492 | class SearchContentCodeHtmlFormatter(CodeHtmlFormatter): |
|
492 | class SearchContentCodeHtmlFormatter(CodeHtmlFormatter): | |
493 | def __init__(self, **kw): |
|
493 | def __init__(self, **kw): | |
494 | # only show these line numbers if set |
|
494 | # only show these line numbers if set | |
495 | self.only_lines = kw.pop('only_line_numbers', []) |
|
495 | self.only_lines = kw.pop('only_line_numbers', []) | |
496 | self.query_terms = kw.pop('query_terms', []) |
|
496 | self.query_terms = kw.pop('query_terms', []) | |
497 | self.max_lines = kw.pop('max_lines', 5) |
|
497 | self.max_lines = kw.pop('max_lines', 5) | |
498 | self.line_context = kw.pop('line_context', 3) |
|
498 | self.line_context = kw.pop('line_context', 3) | |
499 | self.url = kw.pop('url', None) |
|
499 | self.url = kw.pop('url', None) | |
500 |
|
500 | |||
501 | super(CodeHtmlFormatter, self).__init__(**kw) |
|
501 | super(CodeHtmlFormatter, self).__init__(**kw) | |
502 |
|
502 | |||
503 | def _wrap_code(self, source): |
|
503 | def _wrap_code(self, source): | |
504 | for cnt, it in enumerate(source): |
|
504 | for cnt, it in enumerate(source): | |
505 | i, t = it |
|
505 | i, t = it | |
506 | t = '<pre>%s</pre>' % t |
|
506 | t = '<pre>%s</pre>' % t | |
507 | yield i, t |
|
507 | yield i, t | |
508 |
|
508 | |||
509 | def _wrap_tablelinenos(self, inner): |
|
509 | def _wrap_tablelinenos(self, inner): | |
510 | yield 0, '<table class="code-highlight %stable">' % self.cssclass |
|
510 | yield 0, '<table class="code-highlight %stable">' % self.cssclass | |
511 |
|
511 | |||
512 | last_shown_line_number = 0 |
|
512 | last_shown_line_number = 0 | |
513 | current_line_number = 1 |
|
513 | current_line_number = 1 | |
514 |
|
514 | |||
515 | for t, line in inner: |
|
515 | for t, line in inner: | |
516 | if not t: |
|
516 | if not t: | |
517 | yield t, line |
|
517 | yield t, line | |
518 | continue |
|
518 | continue | |
519 |
|
519 | |||
520 | if current_line_number in self.only_lines: |
|
520 | if current_line_number in self.only_lines: | |
521 | if last_shown_line_number + 1 != current_line_number: |
|
521 | if last_shown_line_number + 1 != current_line_number: | |
522 | yield 0, '<tr>' |
|
522 | yield 0, '<tr>' | |
523 | yield 0, '<td class="line">...</td>' |
|
523 | yield 0, '<td class="line">...</td>' | |
524 | yield 0, '<td id="hlcode" class="code"></td>' |
|
524 | yield 0, '<td id="hlcode" class="code"></td>' | |
525 | yield 0, '</tr>' |
|
525 | yield 0, '</tr>' | |
526 |
|
526 | |||
527 | yield 0, '<tr>' |
|
527 | yield 0, '<tr>' | |
528 | if self.url: |
|
528 | if self.url: | |
529 | yield 0, '<td class="line"><a href="%s#L%i">%i</a></td>' % ( |
|
529 | yield 0, '<td class="line"><a href="%s#L%i">%i</a></td>' % ( | |
530 | self.url, current_line_number, current_line_number) |
|
530 | self.url, current_line_number, current_line_number) | |
531 | else: |
|
531 | else: | |
532 | yield 0, '<td class="line"><a href="">%i</a></td>' % ( |
|
532 | yield 0, '<td class="line"><a href="">%i</a></td>' % ( | |
533 | current_line_number) |
|
533 | current_line_number) | |
534 | yield 0, '<td id="hlcode" class="code">' + line + '</td>' |
|
534 | yield 0, '<td id="hlcode" class="code">' + line + '</td>' | |
535 | yield 0, '</tr>' |
|
535 | yield 0, '</tr>' | |
536 |
|
536 | |||
537 | last_shown_line_number = current_line_number |
|
537 | last_shown_line_number = current_line_number | |
538 |
|
538 | |||
539 | current_line_number += 1 |
|
539 | current_line_number += 1 | |
540 |
|
540 | |||
541 | yield 0, '</table>' |
|
541 | yield 0, '</table>' | |
542 |
|
542 | |||
543 |
|
543 | |||
544 | def hsv_to_rgb(h, s, v): |
|
544 | def hsv_to_rgb(h, s, v): | |
545 | """ Convert hsv color values to rgb """ |
|
545 | """ Convert hsv color values to rgb """ | |
546 |
|
546 | |||
547 | if s == 0.0: |
|
547 | if s == 0.0: | |
548 | return v, v, v |
|
548 | return v, v, v | |
549 | i = int(h * 6.0) # XXX assume int() truncates! |
|
549 | i = int(h * 6.0) # XXX assume int() truncates! | |
550 | f = (h * 6.0) - i |
|
550 | f = (h * 6.0) - i | |
551 | p = v * (1.0 - s) |
|
551 | p = v * (1.0 - s) | |
552 | q = v * (1.0 - s * f) |
|
552 | q = v * (1.0 - s * f) | |
553 | t = v * (1.0 - s * (1.0 - f)) |
|
553 | t = v * (1.0 - s * (1.0 - f)) | |
554 | i = i % 6 |
|
554 | i = i % 6 | |
555 | if i == 0: |
|
555 | if i == 0: | |
556 | return v, t, p |
|
556 | return v, t, p | |
557 | if i == 1: |
|
557 | if i == 1: | |
558 | return q, v, p |
|
558 | return q, v, p | |
559 | if i == 2: |
|
559 | if i == 2: | |
560 | return p, v, t |
|
560 | return p, v, t | |
561 | if i == 3: |
|
561 | if i == 3: | |
562 | return p, q, v |
|
562 | return p, q, v | |
563 | if i == 4: |
|
563 | if i == 4: | |
564 | return t, p, v |
|
564 | return t, p, v | |
565 | if i == 5: |
|
565 | if i == 5: | |
566 | return v, p, q |
|
566 | return v, p, q | |
567 |
|
567 | |||
568 |
|
568 | |||
569 | def unique_color_generator(n=10000, saturation=0.10, lightness=0.95): |
|
569 | def unique_color_generator(n=10000, saturation=0.10, lightness=0.95): | |
570 | """ |
|
570 | """ | |
571 | Generator for getting n of evenly distributed colors using |
|
571 | Generator for getting n of evenly distributed colors using | |
572 | hsv color and golden ratio. It always return same order of colors |
|
572 | hsv color and golden ratio. It always return same order of colors | |
573 |
|
573 | |||
574 | :param n: number of colors to generate |
|
574 | :param n: number of colors to generate | |
575 | :param saturation: saturation of returned colors |
|
575 | :param saturation: saturation of returned colors | |
576 | :param lightness: lightness of returned colors |
|
576 | :param lightness: lightness of returned colors | |
577 | :returns: RGB tuple |
|
577 | :returns: RGB tuple | |
578 | """ |
|
578 | """ | |
579 |
|
579 | |||
580 | golden_ratio = 0.618033988749895 |
|
580 | golden_ratio = 0.618033988749895 | |
581 | h = 0.22717784590367374 |
|
581 | h = 0.22717784590367374 | |
582 |
|
582 | |||
583 | for _ in range(n): |
|
583 | for _ in range(n): | |
584 | h += golden_ratio |
|
584 | h += golden_ratio | |
585 | h %= 1 |
|
585 | h %= 1 | |
586 | HSV_tuple = [h, saturation, lightness] |
|
586 | HSV_tuple = [h, saturation, lightness] | |
587 | RGB_tuple = hsv_to_rgb(*HSV_tuple) |
|
587 | RGB_tuple = hsv_to_rgb(*HSV_tuple) | |
588 | yield map(lambda x: str(int(x * 256)), RGB_tuple) |
|
588 | yield map(lambda x: str(int(x * 256)), RGB_tuple) | |
589 |
|
589 | |||
590 |
|
590 | |||
591 | def color_hasher(n=10000, saturation=0.10, lightness=0.95): |
|
591 | def color_hasher(n=10000, saturation=0.10, lightness=0.95): | |
592 | """ |
|
592 | """ | |
593 | Returns a function which when called with an argument returns a unique |
|
593 | Returns a function which when called with an argument returns a unique | |
594 | color for that argument, eg. |
|
594 | color for that argument, eg. | |
595 |
|
595 | |||
596 | :param n: number of colors to generate |
|
596 | :param n: number of colors to generate | |
597 | :param saturation: saturation of returned colors |
|
597 | :param saturation: saturation of returned colors | |
598 | :param lightness: lightness of returned colors |
|
598 | :param lightness: lightness of returned colors | |
599 | :returns: css RGB string |
|
599 | :returns: css RGB string | |
600 |
|
600 | |||
601 | >>> color_hash = color_hasher() |
|
601 | >>> color_hash = color_hasher() | |
602 | >>> color_hash('hello') |
|
602 | >>> color_hash('hello') | |
603 | 'rgb(34, 12, 59)' |
|
603 | 'rgb(34, 12, 59)' | |
604 | >>> color_hash('hello') |
|
604 | >>> color_hash('hello') | |
605 | 'rgb(34, 12, 59)' |
|
605 | 'rgb(34, 12, 59)' | |
606 | >>> color_hash('other') |
|
606 | >>> color_hash('other') | |
607 | 'rgb(90, 224, 159)' |
|
607 | 'rgb(90, 224, 159)' | |
608 | """ |
|
608 | """ | |
609 |
|
609 | |||
610 | color_dict = {} |
|
610 | color_dict = {} | |
611 | cgenerator = unique_color_generator( |
|
611 | cgenerator = unique_color_generator( | |
612 | saturation=saturation, lightness=lightness) |
|
612 | saturation=saturation, lightness=lightness) | |
613 |
|
613 | |||
614 | def get_color_string(thing): |
|
614 | def get_color_string(thing): | |
615 | if thing in color_dict: |
|
615 | if thing in color_dict: | |
616 | col = color_dict[thing] |
|
616 | col = color_dict[thing] | |
617 | else: |
|
617 | else: | |
618 | col = color_dict[thing] = cgenerator.next() |
|
618 | col = color_dict[thing] = cgenerator.next() | |
619 | return "rgb(%s)" % (', '.join(col)) |
|
619 | return "rgb(%s)" % (', '.join(col)) | |
620 |
|
620 | |||
621 | return get_color_string |
|
621 | return get_color_string | |
622 |
|
622 | |||
623 |
|
623 | |||
624 | def get_lexer_safe(mimetype=None, filepath=None): |
|
624 | def get_lexer_safe(mimetype=None, filepath=None): | |
625 | """ |
|
625 | """ | |
626 | Tries to return a relevant pygments lexer using mimetype/filepath name, |
|
626 | Tries to return a relevant pygments lexer using mimetype/filepath name, | |
627 | defaulting to plain text if none could be found |
|
627 | defaulting to plain text if none could be found | |
628 | """ |
|
628 | """ | |
629 | lexer = None |
|
629 | lexer = None | |
630 | try: |
|
630 | try: | |
631 | if mimetype: |
|
631 | if mimetype: | |
632 | lexer = get_lexer_for_mimetype(mimetype) |
|
632 | lexer = get_lexer_for_mimetype(mimetype) | |
633 | if not lexer: |
|
633 | if not lexer: | |
634 | lexer = get_lexer_for_filename(filepath) |
|
634 | lexer = get_lexer_for_filename(filepath) | |
635 | except pygments.util.ClassNotFound: |
|
635 | except pygments.util.ClassNotFound: | |
636 | pass |
|
636 | pass | |
637 |
|
637 | |||
638 | if not lexer: |
|
638 | if not lexer: | |
639 | lexer = get_lexer_by_name('text') |
|
639 | lexer = get_lexer_by_name('text') | |
640 |
|
640 | |||
641 | return lexer |
|
641 | return lexer | |
642 |
|
642 | |||
643 |
|
643 | |||
644 | def get_lexer_for_filenode(filenode): |
|
644 | def get_lexer_for_filenode(filenode): | |
645 | lexer = get_custom_lexer(filenode.extension) or filenode.lexer |
|
645 | lexer = get_custom_lexer(filenode.extension) or filenode.lexer | |
646 | return lexer |
|
646 | return lexer | |
647 |
|
647 | |||
648 |
|
648 | |||
649 | def pygmentize(filenode, **kwargs): |
|
649 | def pygmentize(filenode, **kwargs): | |
650 | """ |
|
650 | """ | |
651 | pygmentize function using pygments |
|
651 | pygmentize function using pygments | |
652 |
|
652 | |||
653 | :param filenode: |
|
653 | :param filenode: | |
654 | """ |
|
654 | """ | |
655 | lexer = get_lexer_for_filenode(filenode) |
|
655 | lexer = get_lexer_for_filenode(filenode) | |
656 | return literal(code_highlight(filenode.content, lexer, |
|
656 | return literal(code_highlight(filenode.content, lexer, | |
657 | CodeHtmlFormatter(**kwargs))) |
|
657 | CodeHtmlFormatter(**kwargs))) | |
658 |
|
658 | |||
659 |
|
659 | |||
660 | def is_following_repo(repo_name, user_id): |
|
660 | def is_following_repo(repo_name, user_id): | |
661 | from rhodecode.model.scm import ScmModel |
|
661 | from rhodecode.model.scm import ScmModel | |
662 | return ScmModel().is_following_repo(repo_name, user_id) |
|
662 | return ScmModel().is_following_repo(repo_name, user_id) | |
663 |
|
663 | |||
664 |
|
664 | |||
665 | class _Message(object): |
|
665 | class _Message(object): | |
666 | """A message returned by ``Flash.pop_messages()``. |
|
666 | """A message returned by ``Flash.pop_messages()``. | |
667 |
|
667 | |||
668 | Converting the message to a string returns the message text. Instances |
|
668 | Converting the message to a string returns the message text. Instances | |
669 | also have the following attributes: |
|
669 | also have the following attributes: | |
670 |
|
670 | |||
671 | * ``message``: the message text. |
|
671 | * ``message``: the message text. | |
672 | * ``category``: the category specified when the message was created. |
|
672 | * ``category``: the category specified when the message was created. | |
673 | """ |
|
673 | """ | |
674 |
|
674 | |||
675 | def __init__(self, category, message, sub_data=None): |
|
675 | def __init__(self, category, message, sub_data=None): | |
676 | self.category = category |
|
676 | self.category = category | |
677 | self.message = message |
|
677 | self.message = message | |
678 | self.sub_data = sub_data or {} |
|
678 | self.sub_data = sub_data or {} | |
679 |
|
679 | |||
680 | def __str__(self): |
|
680 | def __str__(self): | |
681 | return self.message |
|
681 | return self.message | |
682 |
|
682 | |||
683 | __unicode__ = __str__ |
|
683 | __unicode__ = __str__ | |
684 |
|
684 | |||
685 | def __html__(self): |
|
685 | def __html__(self): | |
686 | return escape(safe_unicode(self.message)) |
|
686 | return escape(safe_unicode(self.message)) | |
687 |
|
687 | |||
688 |
|
688 | |||
689 | class Flash(object): |
|
689 | class Flash(object): | |
690 | # List of allowed categories. If None, allow any category. |
|
690 | # List of allowed categories. If None, allow any category. | |
691 | categories = ["warning", "notice", "error", "success"] |
|
691 | categories = ["warning", "notice", "error", "success"] | |
692 |
|
692 | |||
693 | # Default category if none is specified. |
|
693 | # Default category if none is specified. | |
694 | default_category = "notice" |
|
694 | default_category = "notice" | |
695 |
|
695 | |||
696 | def __init__(self, session_key="flash", categories=None, |
|
696 | def __init__(self, session_key="flash", categories=None, | |
697 | default_category=None): |
|
697 | default_category=None): | |
698 | """ |
|
698 | """ | |
699 | Instantiate a ``Flash`` object. |
|
699 | Instantiate a ``Flash`` object. | |
700 |
|
700 | |||
701 | ``session_key`` is the key to save the messages under in the user's |
|
701 | ``session_key`` is the key to save the messages under in the user's | |
702 | session. |
|
702 | session. | |
703 |
|
703 | |||
704 | ``categories`` is an optional list which overrides the default list |
|
704 | ``categories`` is an optional list which overrides the default list | |
705 | of categories. |
|
705 | of categories. | |
706 |
|
706 | |||
707 | ``default_category`` overrides the default category used for messages |
|
707 | ``default_category`` overrides the default category used for messages | |
708 | when none is specified. |
|
708 | when none is specified. | |
709 | """ |
|
709 | """ | |
710 | self.session_key = session_key |
|
710 | self.session_key = session_key | |
711 | if categories is not None: |
|
711 | if categories is not None: | |
712 | self.categories = categories |
|
712 | self.categories = categories | |
713 | if default_category is not None: |
|
713 | if default_category is not None: | |
714 | self.default_category = default_category |
|
714 | self.default_category = default_category | |
715 | if self.categories and self.default_category not in self.categories: |
|
715 | if self.categories and self.default_category not in self.categories: | |
716 | raise ValueError( |
|
716 | raise ValueError( | |
717 | "unrecognized default category %r" % (self.default_category,)) |
|
717 | "unrecognized default category %r" % (self.default_category,)) | |
718 |
|
718 | |||
719 | def pop_messages(self, session=None, request=None): |
|
719 | def pop_messages(self, session=None, request=None): | |
720 | """ |
|
720 | """ | |
721 | Return all accumulated messages and delete them from the session. |
|
721 | Return all accumulated messages and delete them from the session. | |
722 |
|
722 | |||
723 | The return value is a list of ``Message`` objects. |
|
723 | The return value is a list of ``Message`` objects. | |
724 | """ |
|
724 | """ | |
725 | messages = [] |
|
725 | messages = [] | |
726 |
|
726 | |||
727 | if not session: |
|
727 | if not session: | |
728 | if not request: |
|
728 | if not request: | |
729 | request = get_current_request() |
|
729 | request = get_current_request() | |
730 | session = request.session |
|
730 | session = request.session | |
731 |
|
731 | |||
732 | # Pop the 'old' pylons flash messages. They are tuples of the form |
|
732 | # Pop the 'old' pylons flash messages. They are tuples of the form | |
733 | # (category, message) |
|
733 | # (category, message) | |
734 | for cat, msg in session.pop(self.session_key, []): |
|
734 | for cat, msg in session.pop(self.session_key, []): | |
735 | messages.append(_Message(cat, msg)) |
|
735 | messages.append(_Message(cat, msg)) | |
736 |
|
736 | |||
737 | # Pop the 'new' pyramid flash messages for each category as list |
|
737 | # Pop the 'new' pyramid flash messages for each category as list | |
738 | # of strings. |
|
738 | # of strings. | |
739 | for cat in self.categories: |
|
739 | for cat in self.categories: | |
740 | for msg in session.pop_flash(queue=cat): |
|
740 | for msg in session.pop_flash(queue=cat): | |
741 | sub_data = {} |
|
741 | sub_data = {} | |
742 | if hasattr(msg, 'rsplit'): |
|
742 | if hasattr(msg, 'rsplit'): | |
743 | flash_data = msg.rsplit('|DELIM|', 1) |
|
743 | flash_data = msg.rsplit('|DELIM|', 1) | |
744 | org_message = flash_data[0] |
|
744 | org_message = flash_data[0] | |
745 | if len(flash_data) > 1: |
|
745 | if len(flash_data) > 1: | |
746 | sub_data = json.loads(flash_data[1]) |
|
746 | sub_data = json.loads(flash_data[1]) | |
747 | else: |
|
747 | else: | |
748 | org_message = msg |
|
748 | org_message = msg | |
749 |
|
749 | |||
750 | messages.append(_Message(cat, org_message, sub_data=sub_data)) |
|
750 | messages.append(_Message(cat, org_message, sub_data=sub_data)) | |
751 |
|
751 | |||
752 | # Map messages from the default queue to the 'notice' category. |
|
752 | # Map messages from the default queue to the 'notice' category. | |
753 | for msg in session.pop_flash(): |
|
753 | for msg in session.pop_flash(): | |
754 | messages.append(_Message('notice', msg)) |
|
754 | messages.append(_Message('notice', msg)) | |
755 |
|
755 | |||
756 | session.save() |
|
756 | session.save() | |
757 | return messages |
|
757 | return messages | |
758 |
|
758 | |||
759 | def json_alerts(self, session=None, request=None): |
|
759 | def json_alerts(self, session=None, request=None): | |
760 | payloads = [] |
|
760 | payloads = [] | |
761 | messages = flash.pop_messages(session=session, request=request) or [] |
|
761 | messages = flash.pop_messages(session=session, request=request) or [] | |
762 | for message in messages: |
|
762 | for message in messages: | |
763 | payloads.append({ |
|
763 | payloads.append({ | |
764 | 'message': { |
|
764 | 'message': { | |
765 | 'message': u'{}'.format(message.message), |
|
765 | 'message': u'{}'.format(message.message), | |
766 | 'level': message.category, |
|
766 | 'level': message.category, | |
767 | 'force': True, |
|
767 | 'force': True, | |
768 | 'subdata': message.sub_data |
|
768 | 'subdata': message.sub_data | |
769 | } |
|
769 | } | |
770 | }) |
|
770 | }) | |
771 | return json.dumps(payloads) |
|
771 | return json.dumps(payloads) | |
772 |
|
772 | |||
773 | def __call__(self, message, category=None, ignore_duplicate=True, |
|
773 | def __call__(self, message, category=None, ignore_duplicate=True, | |
774 | session=None, request=None): |
|
774 | session=None, request=None): | |
775 |
|
775 | |||
776 | if not session: |
|
776 | if not session: | |
777 | if not request: |
|
777 | if not request: | |
778 | request = get_current_request() |
|
778 | request = get_current_request() | |
779 | session = request.session |
|
779 | session = request.session | |
780 |
|
780 | |||
781 | session.flash( |
|
781 | session.flash( | |
782 | message, queue=category, allow_duplicate=not ignore_duplicate) |
|
782 | message, queue=category, allow_duplicate=not ignore_duplicate) | |
783 |
|
783 | |||
784 |
|
784 | |||
785 | flash = Flash() |
|
785 | flash = Flash() | |
786 |
|
786 | |||
787 | #============================================================================== |
|
787 | #============================================================================== | |
788 | # SCM FILTERS available via h. |
|
788 | # SCM FILTERS available via h. | |
789 | #============================================================================== |
|
789 | #============================================================================== | |
790 | from rhodecode.lib.vcs.utils import author_name, author_email |
|
790 | from rhodecode.lib.vcs.utils import author_name, author_email | |
791 | from rhodecode.lib.utils2 import age, age_from_seconds |
|
791 | from rhodecode.lib.utils2 import age, age_from_seconds | |
792 | from rhodecode.model.db import User, ChangesetStatus |
|
792 | from rhodecode.model.db import User, ChangesetStatus | |
793 |
|
793 | |||
794 |
|
794 | |||
795 | email = author_email |
|
795 | email = author_email | |
796 |
|
796 | |||
797 |
|
797 | |||
798 | def capitalize(raw_text): |
|
798 | def capitalize(raw_text): | |
799 | return raw_text.capitalize() |
|
799 | return raw_text.capitalize() | |
800 |
|
800 | |||
801 |
|
801 | |||
802 | def short_id(long_id): |
|
802 | def short_id(long_id): | |
803 | return long_id[:12] |
|
803 | return long_id[:12] | |
804 |
|
804 | |||
805 |
|
805 | |||
806 | def hide_credentials(url): |
|
806 | def hide_credentials(url): | |
807 | from rhodecode.lib.utils2 import credentials_filter |
|
807 | from rhodecode.lib.utils2 import credentials_filter | |
808 | return credentials_filter(url) |
|
808 | return credentials_filter(url) | |
809 |
|
809 | |||
810 |
|
810 | |||
811 | import pytz |
|
811 | import pytz | |
812 | import tzlocal |
|
812 | import tzlocal | |
813 | local_timezone = tzlocal.get_localzone() |
|
813 | local_timezone = tzlocal.get_localzone() | |
814 |
|
814 | |||
815 |
|
815 | |||
816 | def get_timezone(datetime_iso, time_is_local=False): |
|
816 | def get_timezone(datetime_iso, time_is_local=False): | |
817 | tzinfo = '+00:00' |
|
817 | tzinfo = '+00:00' | |
818 |
|
818 | |||
819 | # detect if we have a timezone info, otherwise, add it |
|
819 | # detect if we have a timezone info, otherwise, add it | |
820 | if time_is_local and isinstance(datetime_iso, datetime) and not datetime_iso.tzinfo: |
|
820 | if time_is_local and isinstance(datetime_iso, datetime) and not datetime_iso.tzinfo: | |
821 | force_timezone = os.environ.get('RC_TIMEZONE', '') |
|
821 | force_timezone = os.environ.get('RC_TIMEZONE', '') | |
822 | if force_timezone: |
|
822 | if force_timezone: | |
823 | force_timezone = pytz.timezone(force_timezone) |
|
823 | force_timezone = pytz.timezone(force_timezone) | |
824 | timezone = force_timezone or local_timezone |
|
824 | timezone = force_timezone or local_timezone | |
825 | offset = timezone.localize(datetime_iso).strftime('%z') |
|
825 | offset = timezone.localize(datetime_iso).strftime('%z') | |
826 | tzinfo = '{}:{}'.format(offset[:-2], offset[-2:]) |
|
826 | tzinfo = '{}:{}'.format(offset[:-2], offset[-2:]) | |
827 | return tzinfo |
|
827 | return tzinfo | |
828 |
|
828 | |||
829 |
|
829 | |||
830 | def age_component(datetime_iso, value=None, time_is_local=False, tooltip=True): |
|
830 | def age_component(datetime_iso, value=None, time_is_local=False, tooltip=True): | |
831 | title = value or format_date(datetime_iso) |
|
831 | title = value or format_date(datetime_iso) | |
832 | tzinfo = get_timezone(datetime_iso, time_is_local=time_is_local) |
|
832 | tzinfo = get_timezone(datetime_iso, time_is_local=time_is_local) | |
833 |
|
833 | |||
834 | return literal( |
|
834 | return literal( | |
835 | '<time class="timeago {cls}" title="{tt_title}" datetime="{dt}{tzinfo}">{title}</time>'.format( |
|
835 | '<time class="timeago {cls}" title="{tt_title}" datetime="{dt}{tzinfo}">{title}</time>'.format( | |
836 | cls='tooltip' if tooltip else '', |
|
836 | cls='tooltip' if tooltip else '', | |
837 | tt_title=('{title}{tzinfo}'.format(title=title, tzinfo=tzinfo)) if tooltip else '', |
|
837 | tt_title=('{title}{tzinfo}'.format(title=title, tzinfo=tzinfo)) if tooltip else '', | |
838 | title=title, dt=datetime_iso, tzinfo=tzinfo |
|
838 | title=title, dt=datetime_iso, tzinfo=tzinfo | |
839 | )) |
|
839 | )) | |
840 |
|
840 | |||
841 |
|
841 | |||
842 | def _shorten_commit_id(commit_id, commit_len=None): |
|
842 | def _shorten_commit_id(commit_id, commit_len=None): | |
843 | if commit_len is None: |
|
843 | if commit_len is None: | |
844 | request = get_current_request() |
|
844 | request = get_current_request() | |
845 | commit_len = request.call_context.visual.show_sha_length |
|
845 | commit_len = request.call_context.visual.show_sha_length | |
846 | return commit_id[:commit_len] |
|
846 | return commit_id[:commit_len] | |
847 |
|
847 | |||
848 |
|
848 | |||
849 | def show_id(commit, show_idx=None, commit_len=None): |
|
849 | def show_id(commit, show_idx=None, commit_len=None): | |
850 | """ |
|
850 | """ | |
851 | Configurable function that shows ID |
|
851 | Configurable function that shows ID | |
852 | by default it's r123:fffeeefffeee |
|
852 | by default it's r123:fffeeefffeee | |
853 |
|
853 | |||
854 | :param commit: commit instance |
|
854 | :param commit: commit instance | |
855 | """ |
|
855 | """ | |
856 | if show_idx is None: |
|
856 | if show_idx is None: | |
857 | request = get_current_request() |
|
857 | request = get_current_request() | |
858 | show_idx = request.call_context.visual.show_revision_number |
|
858 | show_idx = request.call_context.visual.show_revision_number | |
859 |
|
859 | |||
860 | raw_id = _shorten_commit_id(commit.raw_id, commit_len=commit_len) |
|
860 | raw_id = _shorten_commit_id(commit.raw_id, commit_len=commit_len) | |
861 | if show_idx: |
|
861 | if show_idx: | |
862 | return 'r%s:%s' % (commit.idx, raw_id) |
|
862 | return 'r%s:%s' % (commit.idx, raw_id) | |
863 | else: |
|
863 | else: | |
864 | return '%s' % (raw_id, ) |
|
864 | return '%s' % (raw_id, ) | |
865 |
|
865 | |||
866 |
|
866 | |||
867 | def format_date(date): |
|
867 | def format_date(date): | |
868 | """ |
|
868 | """ | |
869 | use a standardized formatting for dates used in RhodeCode |
|
869 | use a standardized formatting for dates used in RhodeCode | |
870 |
|
870 | |||
871 | :param date: date/datetime object |
|
871 | :param date: date/datetime object | |
872 | :return: formatted date |
|
872 | :return: formatted date | |
873 | """ |
|
873 | """ | |
874 |
|
874 | |||
875 | if date: |
|
875 | if date: | |
876 | _fmt = "%a, %d %b %Y %H:%M:%S" |
|
876 | _fmt = "%a, %d %b %Y %H:%M:%S" | |
877 | return safe_unicode(date.strftime(_fmt)) |
|
877 | return safe_unicode(date.strftime(_fmt)) | |
878 |
|
878 | |||
879 | return u"" |
|
879 | return u"" | |
880 |
|
880 | |||
881 |
|
881 | |||
882 | class _RepoChecker(object): |
|
882 | class _RepoChecker(object): | |
883 |
|
883 | |||
884 | def __init__(self, backend_alias): |
|
884 | def __init__(self, backend_alias): | |
885 | self._backend_alias = backend_alias |
|
885 | self._backend_alias = backend_alias | |
886 |
|
886 | |||
887 | def __call__(self, repository): |
|
887 | def __call__(self, repository): | |
888 | if hasattr(repository, 'alias'): |
|
888 | if hasattr(repository, 'alias'): | |
889 | _type = repository.alias |
|
889 | _type = repository.alias | |
890 | elif hasattr(repository, 'repo_type'): |
|
890 | elif hasattr(repository, 'repo_type'): | |
891 | _type = repository.repo_type |
|
891 | _type = repository.repo_type | |
892 | else: |
|
892 | else: | |
893 | _type = repository |
|
893 | _type = repository | |
894 | return _type == self._backend_alias |
|
894 | return _type == self._backend_alias | |
895 |
|
895 | |||
896 |
|
896 | |||
897 | is_git = _RepoChecker('git') |
|
897 | is_git = _RepoChecker('git') | |
898 | is_hg = _RepoChecker('hg') |
|
898 | is_hg = _RepoChecker('hg') | |
899 | is_svn = _RepoChecker('svn') |
|
899 | is_svn = _RepoChecker('svn') | |
900 |
|
900 | |||
901 |
|
901 | |||
902 | def get_repo_type_by_name(repo_name): |
|
902 | def get_repo_type_by_name(repo_name): | |
903 | repo = Repository.get_by_repo_name(repo_name) |
|
903 | repo = Repository.get_by_repo_name(repo_name) | |
904 | if repo: |
|
904 | if repo: | |
905 | return repo.repo_type |
|
905 | return repo.repo_type | |
906 |
|
906 | |||
907 |
|
907 | |||
908 | def is_svn_without_proxy(repository): |
|
908 | def is_svn_without_proxy(repository): | |
909 | if is_svn(repository): |
|
909 | if is_svn(repository): | |
910 | from rhodecode.model.settings import VcsSettingsModel |
|
910 | from rhodecode.model.settings import VcsSettingsModel | |
911 | conf = VcsSettingsModel().get_ui_settings_as_config_obj() |
|
911 | conf = VcsSettingsModel().get_ui_settings_as_config_obj() | |
912 | return not str2bool(conf.get('vcs_svn_proxy', 'http_requests_enabled')) |
|
912 | return not str2bool(conf.get('vcs_svn_proxy', 'http_requests_enabled')) | |
913 | return False |
|
913 | return False | |
914 |
|
914 | |||
915 |
|
915 | |||
916 | def discover_user(author): |
|
916 | def discover_user(author): | |
917 | """ |
|
917 | """ | |
918 | Tries to discover RhodeCode User based on the author string. Author string |
|
918 | Tries to discover RhodeCode User based on the author string. Author string | |
919 | is typically `FirstName LastName <email@address.com>` |
|
919 | is typically `FirstName LastName <email@address.com>` | |
920 | """ |
|
920 | """ | |
921 |
|
921 | |||
922 | # if author is already an instance use it for extraction |
|
922 | # if author is already an instance use it for extraction | |
923 | if isinstance(author, User): |
|
923 | if isinstance(author, User): | |
924 | return author |
|
924 | return author | |
925 |
|
925 | |||
926 | # Valid email in the attribute passed, see if they're in the system |
|
926 | # Valid email in the attribute passed, see if they're in the system | |
927 | _email = author_email(author) |
|
927 | _email = author_email(author) | |
928 | if _email != '': |
|
928 | if _email != '': | |
929 | user = User.get_by_email(_email, case_insensitive=True, cache=True) |
|
929 | user = User.get_by_email(_email, case_insensitive=True, cache=True) | |
930 | if user is not None: |
|
930 | if user is not None: | |
931 | return user |
|
931 | return user | |
932 |
|
932 | |||
933 | # Maybe it's a username, we try to extract it and fetch by username ? |
|
933 | # Maybe it's a username, we try to extract it and fetch by username ? | |
934 | _author = author_name(author) |
|
934 | _author = author_name(author) | |
935 | user = User.get_by_username(_author, case_insensitive=True, cache=True) |
|
935 | user = User.get_by_username(_author, case_insensitive=True, cache=True) | |
936 | if user is not None: |
|
936 | if user is not None: | |
937 | return user |
|
937 | return user | |
938 |
|
938 | |||
939 | return None |
|
939 | return None | |
940 |
|
940 | |||
941 |
|
941 | |||
942 | def email_or_none(author): |
|
942 | def email_or_none(author): | |
943 | # extract email from the commit string |
|
943 | # extract email from the commit string | |
944 | _email = author_email(author) |
|
944 | _email = author_email(author) | |
945 |
|
945 | |||
946 | # If we have an email, use it, otherwise |
|
946 | # If we have an email, use it, otherwise | |
947 | # see if it contains a username we can get an email from |
|
947 | # see if it contains a username we can get an email from | |
948 | if _email != '': |
|
948 | if _email != '': | |
949 | return _email |
|
949 | return _email | |
950 | else: |
|
950 | else: | |
951 | user = User.get_by_username( |
|
951 | user = User.get_by_username( | |
952 | author_name(author), case_insensitive=True, cache=True) |
|
952 | author_name(author), case_insensitive=True, cache=True) | |
953 |
|
953 | |||
954 | if user is not None: |
|
954 | if user is not None: | |
955 | return user.email |
|
955 | return user.email | |
956 |
|
956 | |||
957 | # No valid email, not a valid user in the system, none! |
|
957 | # No valid email, not a valid user in the system, none! | |
958 | return None |
|
958 | return None | |
959 |
|
959 | |||
960 |
|
960 | |||
961 | def link_to_user(author, length=0, **kwargs): |
|
961 | def link_to_user(author, length=0, **kwargs): | |
962 | user = discover_user(author) |
|
962 | user = discover_user(author) | |
963 | # user can be None, but if we have it already it means we can re-use it |
|
963 | # user can be None, but if we have it already it means we can re-use it | |
964 | # in the person() function, so we save 1 intensive-query |
|
964 | # in the person() function, so we save 1 intensive-query | |
965 | if user: |
|
965 | if user: | |
966 | author = user |
|
966 | author = user | |
967 |
|
967 | |||
968 | display_person = person(author, 'username_or_name_or_email') |
|
968 | display_person = person(author, 'username_or_name_or_email') | |
969 | if length: |
|
969 | if length: | |
970 | display_person = shorter(display_person, length) |
|
970 | display_person = shorter(display_person, length) | |
971 |
|
971 | |||
972 | if user and user.username != user.DEFAULT_USER: |
|
972 | if user and user.username != user.DEFAULT_USER: | |
973 | return link_to( |
|
973 | return link_to( | |
974 | escape(display_person), |
|
974 | escape(display_person), | |
975 | route_path('user_profile', username=user.username), |
|
975 | route_path('user_profile', username=user.username), | |
976 | **kwargs) |
|
976 | **kwargs) | |
977 | else: |
|
977 | else: | |
978 | return escape(display_person) |
|
978 | return escape(display_person) | |
979 |
|
979 | |||
980 |
|
980 | |||
981 | def link_to_group(users_group_name, **kwargs): |
|
981 | def link_to_group(users_group_name, **kwargs): | |
982 | return link_to( |
|
982 | return link_to( | |
983 | escape(users_group_name), |
|
983 | escape(users_group_name), | |
984 | route_path('user_group_profile', user_group_name=users_group_name), |
|
984 | route_path('user_group_profile', user_group_name=users_group_name), | |
985 | **kwargs) |
|
985 | **kwargs) | |
986 |
|
986 | |||
987 |
|
987 | |||
988 | def person(author, show_attr="username_and_name"): |
|
988 | def person(author, show_attr="username_and_name"): | |
989 | user = discover_user(author) |
|
989 | user = discover_user(author) | |
990 | if user: |
|
990 | if user: | |
991 | return getattr(user, show_attr) |
|
991 | return getattr(user, show_attr) | |
992 | else: |
|
992 | else: | |
993 | _author = author_name(author) |
|
993 | _author = author_name(author) | |
994 | _email = email(author) |
|
994 | _email = email(author) | |
995 | return _author or _email |
|
995 | return _author or _email | |
996 |
|
996 | |||
997 |
|
997 | |||
998 | def author_string(email): |
|
998 | def author_string(email): | |
999 | if email: |
|
999 | if email: | |
1000 | user = User.get_by_email(email, case_insensitive=True, cache=True) |
|
1000 | user = User.get_by_email(email, case_insensitive=True, cache=True) | |
1001 | if user: |
|
1001 | if user: | |
1002 | if user.first_name or user.last_name: |
|
1002 | if user.first_name or user.last_name: | |
1003 | return '%s %s <%s>' % ( |
|
1003 | return '%s %s <%s>' % ( | |
1004 | user.first_name, user.last_name, email) |
|
1004 | user.first_name, user.last_name, email) | |
1005 | else: |
|
1005 | else: | |
1006 | return email |
|
1006 | return email | |
1007 | else: |
|
1007 | else: | |
1008 | return email |
|
1008 | return email | |
1009 | else: |
|
1009 | else: | |
1010 | return None |
|
1010 | return None | |
1011 |
|
1011 | |||
1012 |
|
1012 | |||
1013 | def person_by_id(id_, show_attr="username_and_name"): |
|
1013 | def person_by_id(id_, show_attr="username_and_name"): | |
1014 | # attr to return from fetched user |
|
1014 | # attr to return from fetched user | |
1015 | person_getter = lambda usr: getattr(usr, show_attr) |
|
1015 | person_getter = lambda usr: getattr(usr, show_attr) | |
1016 |
|
1016 | |||
1017 | #maybe it's an ID ? |
|
1017 | #maybe it's an ID ? | |
1018 | if str(id_).isdigit() or isinstance(id_, int): |
|
1018 | if str(id_).isdigit() or isinstance(id_, int): | |
1019 | id_ = int(id_) |
|
1019 | id_ = int(id_) | |
1020 | user = User.get(id_) |
|
1020 | user = User.get(id_) | |
1021 | if user is not None: |
|
1021 | if user is not None: | |
1022 | return person_getter(user) |
|
1022 | return person_getter(user) | |
1023 | return id_ |
|
1023 | return id_ | |
1024 |
|
1024 | |||
1025 |
|
1025 | |||
1026 | def gravatar_with_user(request, author, show_disabled=False, tooltip=False): |
|
1026 | def gravatar_with_user(request, author, show_disabled=False, tooltip=False): | |
1027 | _render = request.get_partial_renderer('rhodecode:templates/base/base.mako') |
|
1027 | _render = request.get_partial_renderer('rhodecode:templates/base/base.mako') | |
1028 | return _render('gravatar_with_user', author, show_disabled=show_disabled, tooltip=tooltip) |
|
1028 | return _render('gravatar_with_user', author, show_disabled=show_disabled, tooltip=tooltip) | |
1029 |
|
1029 | |||
1030 |
|
1030 | |||
1031 | tags_paterns = OrderedDict(( |
|
1031 | tags_paterns = OrderedDict(( | |
1032 | ('lang', (re.compile(r'\[(lang|language)\ \=\>\ *([a-zA-Z\-\/\#\+\.]*)\]'), |
|
1032 | ('lang', (re.compile(r'\[(lang|language)\ \=\>\ *([a-zA-Z\-\/\#\+\.]*)\]'), | |
1033 | '<div class="metatag" tag="lang">\\2</div>')), |
|
1033 | '<div class="metatag" tag="lang">\\2</div>')), | |
1034 |
|
1034 | |||
1035 | ('see', (re.compile(r'\[see\ \=\>\ *([a-zA-Z0-9\/\=\?\&\ \:\/\.\-]*)\]'), |
|
1035 | ('see', (re.compile(r'\[see\ \=\>\ *([a-zA-Z0-9\/\=\?\&\ \:\/\.\-]*)\]'), | |
1036 | '<div class="metatag" tag="see">see: \\1 </div>')), |
|
1036 | '<div class="metatag" tag="see">see: \\1 </div>')), | |
1037 |
|
1037 | |||
1038 | ('url', (re.compile(r'\[url\ \=\>\ \[([a-zA-Z0-9\ \.\-\_]+)\]\((http://|https://|/)(.*?)\)\]'), |
|
1038 | ('url', (re.compile(r'\[url\ \=\>\ \[([a-zA-Z0-9\ \.\-\_]+)\]\((http://|https://|/)(.*?)\)\]'), | |
1039 | '<div class="metatag" tag="url"> <a href="\\2\\3">\\1</a> </div>')), |
|
1039 | '<div class="metatag" tag="url"> <a href="\\2\\3">\\1</a> </div>')), | |
1040 |
|
1040 | |||
1041 | ('license', (re.compile(r'\[license\ \=\>\ *([a-zA-Z0-9\/\=\?\&\ \:\/\.\-]*)\]'), |
|
1041 | ('license', (re.compile(r'\[license\ \=\>\ *([a-zA-Z0-9\/\=\?\&\ \:\/\.\-]*)\]'), | |
1042 | '<div class="metatag" tag="license"><a href="http:\/\/www.opensource.org/licenses/\\1">\\1</a></div>')), |
|
1042 | '<div class="metatag" tag="license"><a href="http:\/\/www.opensource.org/licenses/\\1">\\1</a></div>')), | |
1043 |
|
1043 | |||
1044 | ('ref', (re.compile(r'\[(requires|recommends|conflicts|base)\ \=\>\ *([a-zA-Z0-9\-\/]*)\]'), |
|
1044 | ('ref', (re.compile(r'\[(requires|recommends|conflicts|base)\ \=\>\ *([a-zA-Z0-9\-\/]*)\]'), | |
1045 | '<div class="metatag" tag="ref \\1">\\1: <a href="/\\2">\\2</a></div>')), |
|
1045 | '<div class="metatag" tag="ref \\1">\\1: <a href="/\\2">\\2</a></div>')), | |
1046 |
|
1046 | |||
1047 | ('state', (re.compile(r'\[(stable|featured|stale|dead|dev|deprecated)\]'), |
|
1047 | ('state', (re.compile(r'\[(stable|featured|stale|dead|dev|deprecated)\]'), | |
1048 | '<div class="metatag" tag="state \\1">\\1</div>')), |
|
1048 | '<div class="metatag" tag="state \\1">\\1</div>')), | |
1049 |
|
1049 | |||
1050 | # label in grey |
|
1050 | # label in grey | |
1051 | ('label', (re.compile(r'\[([a-z]+)\]'), |
|
1051 | ('label', (re.compile(r'\[([a-z]+)\]'), | |
1052 | '<div class="metatag" tag="label">\\1</div>')), |
|
1052 | '<div class="metatag" tag="label">\\1</div>')), | |
1053 |
|
1053 | |||
1054 | # generic catch all in grey |
|
1054 | # generic catch all in grey | |
1055 | ('generic', (re.compile(r'\[([a-zA-Z0-9\.\-\_]+)\]'), |
|
1055 | ('generic', (re.compile(r'\[([a-zA-Z0-9\.\-\_]+)\]'), | |
1056 | '<div class="metatag" tag="generic">\\1</div>')), |
|
1056 | '<div class="metatag" tag="generic">\\1</div>')), | |
1057 | )) |
|
1057 | )) | |
1058 |
|
1058 | |||
1059 |
|
1059 | |||
1060 | def extract_metatags(value): |
|
1060 | def extract_metatags(value): | |
1061 | """ |
|
1061 | """ | |
1062 | Extract supported meta-tags from given text value |
|
1062 | Extract supported meta-tags from given text value | |
1063 | """ |
|
1063 | """ | |
1064 | tags = [] |
|
1064 | tags = [] | |
1065 | if not value: |
|
1065 | if not value: | |
1066 | return tags, '' |
|
1066 | return tags, '' | |
1067 |
|
1067 | |||
1068 | for key, val in tags_paterns.items(): |
|
1068 | for key, val in tags_paterns.items(): | |
1069 | pat, replace_html = val |
|
1069 | pat, replace_html = val | |
1070 | tags.extend([(key, x.group()) for x in pat.finditer(value)]) |
|
1070 | tags.extend([(key, x.group()) for x in pat.finditer(value)]) | |
1071 | value = pat.sub('', value) |
|
1071 | value = pat.sub('', value) | |
1072 |
|
1072 | |||
1073 | return tags, value |
|
1073 | return tags, value | |
1074 |
|
1074 | |||
1075 |
|
1075 | |||
1076 | def style_metatag(tag_type, value): |
|
1076 | def style_metatag(tag_type, value): | |
1077 | """ |
|
1077 | """ | |
1078 | converts tags from value into html equivalent |
|
1078 | converts tags from value into html equivalent | |
1079 | """ |
|
1079 | """ | |
1080 | if not value: |
|
1080 | if not value: | |
1081 | return '' |
|
1081 | return '' | |
1082 |
|
1082 | |||
1083 | html_value = value |
|
1083 | html_value = value | |
1084 | tag_data = tags_paterns.get(tag_type) |
|
1084 | tag_data = tags_paterns.get(tag_type) | |
1085 | if tag_data: |
|
1085 | if tag_data: | |
1086 | pat, replace_html = tag_data |
|
1086 | pat, replace_html = tag_data | |
1087 | # convert to plain `unicode` instead of a markup tag to be used in |
|
1087 | # convert to plain `unicode` instead of a markup tag to be used in | |
1088 | # regex expressions. safe_unicode doesn't work here |
|
1088 | # regex expressions. safe_unicode doesn't work here | |
1089 | html_value = pat.sub(replace_html, unicode(value)) |
|
1089 | html_value = pat.sub(replace_html, unicode(value)) | |
1090 |
|
1090 | |||
1091 | return html_value |
|
1091 | return html_value | |
1092 |
|
1092 | |||
1093 |
|
1093 | |||
1094 | def bool2icon(value, show_at_false=True): |
|
1094 | def bool2icon(value, show_at_false=True): | |
1095 | """ |
|
1095 | """ | |
1096 | Returns boolean value of a given value, represented as html element with |
|
1096 | Returns boolean value of a given value, represented as html element with | |
1097 | classes that will represent icons |
|
1097 | classes that will represent icons | |
1098 |
|
1098 | |||
1099 | :param value: given value to convert to html node |
|
1099 | :param value: given value to convert to html node | |
1100 | """ |
|
1100 | """ | |
1101 |
|
1101 | |||
1102 | if value: # does bool conversion |
|
1102 | if value: # does bool conversion | |
1103 | return HTML.tag('i', class_="icon-true", title='True') |
|
1103 | return HTML.tag('i', class_="icon-true", title='True') | |
1104 | else: # not true as bool |
|
1104 | else: # not true as bool | |
1105 | if show_at_false: |
|
1105 | if show_at_false: | |
1106 | return HTML.tag('i', class_="icon-false", title='False') |
|
1106 | return HTML.tag('i', class_="icon-false", title='False') | |
1107 | return HTML.tag('i') |
|
1107 | return HTML.tag('i') | |
1108 |
|
1108 | |||
1109 |
|
1109 | |||
1110 | def b64(inp): |
|
1110 | def b64(inp): | |
1111 | return base64.b64encode(inp) |
|
1111 | return base64.b64encode(inp) | |
1112 |
|
1112 | |||
1113 | #============================================================================== |
|
1113 | #============================================================================== | |
1114 | # PERMS |
|
1114 | # PERMS | |
1115 | #============================================================================== |
|
1115 | #============================================================================== | |
1116 | from rhodecode.lib.auth import ( |
|
1116 | from rhodecode.lib.auth import ( | |
1117 | HasPermissionAny, HasPermissionAll, |
|
1117 | HasPermissionAny, HasPermissionAll, | |
1118 | HasRepoPermissionAny, HasRepoPermissionAll, HasRepoGroupPermissionAll, |
|
1118 | HasRepoPermissionAny, HasRepoPermissionAll, HasRepoGroupPermissionAll, | |
1119 | HasRepoGroupPermissionAny, HasRepoPermissionAnyApi, get_csrf_token, |
|
1119 | HasRepoGroupPermissionAny, HasRepoPermissionAnyApi, get_csrf_token, | |
1120 | csrf_token_key, AuthUser) |
|
1120 | csrf_token_key, AuthUser) | |
1121 |
|
1121 | |||
1122 |
|
1122 | |||
1123 | #============================================================================== |
|
1123 | #============================================================================== | |
1124 | # GRAVATAR URL |
|
1124 | # GRAVATAR URL | |
1125 | #============================================================================== |
|
1125 | #============================================================================== | |
1126 | class InitialsGravatar(object): |
|
1126 | class InitialsGravatar(object): | |
1127 | def __init__(self, email_address, first_name, last_name, size=30, |
|
1127 | def __init__(self, email_address, first_name, last_name, size=30, | |
1128 | background=None, text_color='#fff'): |
|
1128 | background=None, text_color='#fff'): | |
1129 | self.size = size |
|
1129 | self.size = size | |
1130 | self.first_name = first_name |
|
1130 | self.first_name = first_name | |
1131 | self.last_name = last_name |
|
1131 | self.last_name = last_name | |
1132 | self.email_address = email_address |
|
1132 | self.email_address = email_address | |
1133 | self.background = background or self.str2color(email_address) |
|
1133 | self.background = background or self.str2color(email_address) | |
1134 | self.text_color = text_color |
|
1134 | self.text_color = text_color | |
1135 |
|
1135 | |||
1136 | def get_color_bank(self): |
|
1136 | def get_color_bank(self): | |
1137 | """ |
|
1137 | """ | |
1138 | returns a predefined list of colors that gravatars can use. |
|
1138 | returns a predefined list of colors that gravatars can use. | |
1139 | Those are randomized distinct colors that guarantee readability and |
|
1139 | Those are randomized distinct colors that guarantee readability and | |
1140 | uniqueness. |
|
1140 | uniqueness. | |
1141 |
|
1141 | |||
1142 | generated with: http://phrogz.net/css/distinct-colors.html |
|
1142 | generated with: http://phrogz.net/css/distinct-colors.html | |
1143 | """ |
|
1143 | """ | |
1144 | return [ |
|
1144 | return [ | |
1145 | '#bf3030', '#a67f53', '#00ff00', '#5989b3', '#392040', '#d90000', |
|
1145 | '#bf3030', '#a67f53', '#00ff00', '#5989b3', '#392040', '#d90000', | |
1146 | '#402910', '#204020', '#79baf2', '#a700b3', '#bf6060', '#7f5320', |
|
1146 | '#402910', '#204020', '#79baf2', '#a700b3', '#bf6060', '#7f5320', | |
1147 | '#008000', '#003059', '#ee00ff', '#ff0000', '#8c4b00', '#007300', |
|
1147 | '#008000', '#003059', '#ee00ff', '#ff0000', '#8c4b00', '#007300', | |
1148 | '#005fb3', '#de73e6', '#ff4040', '#ffaa00', '#3df255', '#203140', |
|
1148 | '#005fb3', '#de73e6', '#ff4040', '#ffaa00', '#3df255', '#203140', | |
1149 | '#47004d', '#591616', '#664400', '#59b365', '#0d2133', '#83008c', |
|
1149 | '#47004d', '#591616', '#664400', '#59b365', '#0d2133', '#83008c', | |
1150 | '#592d2d', '#bf9f60', '#73e682', '#1d3f73', '#73006b', '#402020', |
|
1150 | '#592d2d', '#bf9f60', '#73e682', '#1d3f73', '#73006b', '#402020', | |
1151 | '#b2862d', '#397341', '#597db3', '#e600d6', '#a60000', '#736039', |
|
1151 | '#b2862d', '#397341', '#597db3', '#e600d6', '#a60000', '#736039', | |
1152 | '#00b318', '#79aaf2', '#330d30', '#ff8080', '#403010', '#16591f', |
|
1152 | '#00b318', '#79aaf2', '#330d30', '#ff8080', '#403010', '#16591f', | |
1153 | '#002459', '#8c4688', '#e50000', '#ffbf40', '#00732e', '#102340', |
|
1153 | '#002459', '#8c4688', '#e50000', '#ffbf40', '#00732e', '#102340', | |
1154 | '#bf60ac', '#8c4646', '#cc8800', '#00a642', '#1d3473', '#b32d98', |
|
1154 | '#bf60ac', '#8c4646', '#cc8800', '#00a642', '#1d3473', '#b32d98', | |
1155 | '#660e00', '#ffd580', '#80ffb2', '#7391e6', '#733967', '#d97b6c', |
|
1155 | '#660e00', '#ffd580', '#80ffb2', '#7391e6', '#733967', '#d97b6c', | |
1156 | '#8c5e00', '#59b389', '#3967e6', '#590047', '#73281d', '#665200', |
|
1156 | '#8c5e00', '#59b389', '#3967e6', '#590047', '#73281d', '#665200', | |
1157 | '#00e67a', '#2d50b3', '#8c2377', '#734139', '#b2982d', '#16593a', |
|
1157 | '#00e67a', '#2d50b3', '#8c2377', '#734139', '#b2982d', '#16593a', | |
1158 | '#001859', '#ff00aa', '#a65e53', '#ffcc00', '#0d3321', '#2d3959', |
|
1158 | '#001859', '#ff00aa', '#a65e53', '#ffcc00', '#0d3321', '#2d3959', | |
1159 | '#731d56', '#401610', '#4c3d00', '#468c6c', '#002ca6', '#d936a3', |
|
1159 | '#731d56', '#401610', '#4c3d00', '#468c6c', '#002ca6', '#d936a3', | |
1160 | '#d94c36', '#403920', '#36d9a3', '#0d1733', '#592d4a', '#993626', |
|
1160 | '#d94c36', '#403920', '#36d9a3', '#0d1733', '#592d4a', '#993626', | |
1161 | '#cca300', '#00734d', '#46598c', '#8c005e', '#7f1100', '#8c7000', |
|
1161 | '#cca300', '#00734d', '#46598c', '#8c005e', '#7f1100', '#8c7000', | |
1162 | '#00a66f', '#7382e6', '#b32d74', '#d9896c', '#ffe680', '#1d7362', |
|
1162 | '#00a66f', '#7382e6', '#b32d74', '#d9896c', '#ffe680', '#1d7362', | |
1163 | '#364cd9', '#73003d', '#d93a00', '#998a4d', '#59b3a1', '#5965b3', |
|
1163 | '#364cd9', '#73003d', '#d93a00', '#998a4d', '#59b3a1', '#5965b3', | |
1164 | '#e5007a', '#73341d', '#665f00', '#00b38f', '#0018b3', '#59163a', |
|
1164 | '#e5007a', '#73341d', '#665f00', '#00b38f', '#0018b3', '#59163a', | |
1165 | '#b2502d', '#bfb960', '#00ffcc', '#23318c', '#a6537f', '#734939', |
|
1165 | '#b2502d', '#bfb960', '#00ffcc', '#23318c', '#a6537f', '#734939', | |
1166 | '#b2a700', '#104036', '#3d3df2', '#402031', '#e56739', '#736f39', |
|
1166 | '#b2a700', '#104036', '#3d3df2', '#402031', '#e56739', '#736f39', | |
1167 | '#79f2ea', '#000059', '#401029', '#4c1400', '#ffee00', '#005953', |
|
1167 | '#79f2ea', '#000059', '#401029', '#4c1400', '#ffee00', '#005953', | |
1168 | '#101040', '#990052', '#402820', '#403d10', '#00ffee', '#0000d9', |
|
1168 | '#101040', '#990052', '#402820', '#403d10', '#00ffee', '#0000d9', | |
1169 | '#ff80c4', '#a66953', '#eeff00', '#00ccbe', '#8080ff', '#e673a1', |
|
1169 | '#ff80c4', '#a66953', '#eeff00', '#00ccbe', '#8080ff', '#e673a1', | |
1170 | '#a62c00', '#474d00', '#1a3331', '#46468c', '#733950', '#662900', |
|
1170 | '#a62c00', '#474d00', '#1a3331', '#46468c', '#733950', '#662900', | |
1171 | '#858c23', '#238c85', '#0f0073', '#b20047', '#d9986c', '#becc00', |
|
1171 | '#858c23', '#238c85', '#0f0073', '#b20047', '#d9986c', '#becc00', | |
1172 | '#396f73', '#281d73', '#ff0066', '#ff6600', '#dee673', '#59adb3', |
|
1172 | '#396f73', '#281d73', '#ff0066', '#ff6600', '#dee673', '#59adb3', | |
1173 | '#6559b3', '#590024', '#b2622d', '#98b32d', '#36ced9', '#332d59', |
|
1173 | '#6559b3', '#590024', '#b2622d', '#98b32d', '#36ced9', '#332d59', | |
1174 | '#40001a', '#733f1d', '#526600', '#005359', '#242040', '#bf6079', |
|
1174 | '#40001a', '#733f1d', '#526600', '#005359', '#242040', '#bf6079', | |
1175 | '#735039', '#cef23d', '#007780', '#5630bf', '#66001b', '#b24700', |
|
1175 | '#735039', '#cef23d', '#007780', '#5630bf', '#66001b', '#b24700', | |
1176 | '#acbf60', '#1d6273', '#25008c', '#731d34', '#a67453', '#50592d', |
|
1176 | '#acbf60', '#1d6273', '#25008c', '#731d34', '#a67453', '#50592d', | |
1177 | '#00ccff', '#6600ff', '#ff0044', '#4c1f00', '#8a994d', '#79daf2', |
|
1177 | '#00ccff', '#6600ff', '#ff0044', '#4c1f00', '#8a994d', '#79daf2', | |
1178 | '#a173e6', '#d93662', '#402310', '#aaff00', '#2d98b3', '#8c40ff', |
|
1178 | '#a173e6', '#d93662', '#402310', '#aaff00', '#2d98b3', '#8c40ff', | |
1179 | '#592d39', '#ff8c40', '#354020', '#103640', '#1a0040', '#331a20', |
|
1179 | '#592d39', '#ff8c40', '#354020', '#103640', '#1a0040', '#331a20', | |
1180 | '#331400', '#334d00', '#1d5673', '#583973', '#7f0022', '#4c3626', |
|
1180 | '#331400', '#334d00', '#1d5673', '#583973', '#7f0022', '#4c3626', | |
1181 | '#88cc00', '#36a3d9', '#3d0073', '#d9364c', '#33241a', '#698c23', |
|
1181 | '#88cc00', '#36a3d9', '#3d0073', '#d9364c', '#33241a', '#698c23', | |
1182 | '#5995b3', '#300059', '#e57382', '#7f3300', '#366600', '#00aaff', |
|
1182 | '#5995b3', '#300059', '#e57382', '#7f3300', '#366600', '#00aaff', | |
1183 | '#3a1659', '#733941', '#663600', '#74b32d', '#003c59', '#7f53a6', |
|
1183 | '#3a1659', '#733941', '#663600', '#74b32d', '#003c59', '#7f53a6', | |
1184 | '#73000f', '#ff8800', '#baf279', '#79caf2', '#291040', '#a6293a', |
|
1184 | '#73000f', '#ff8800', '#baf279', '#79caf2', '#291040', '#a6293a', | |
1185 | '#b2742d', '#587339', '#0077b3', '#632699', '#400009', '#d9a66c', |
|
1185 | '#b2742d', '#587339', '#0077b3', '#632699', '#400009', '#d9a66c', | |
1186 | '#294010', '#2d4a59', '#aa00ff', '#4c131b', '#b25f00', '#5ce600', |
|
1186 | '#294010', '#2d4a59', '#aa00ff', '#4c131b', '#b25f00', '#5ce600', | |
1187 | '#267399', '#a336d9', '#990014', '#664e33', '#86bf60', '#0088ff', |
|
1187 | '#267399', '#a336d9', '#990014', '#664e33', '#86bf60', '#0088ff', | |
1188 | '#7700b3', '#593a16', '#073300', '#1d4b73', '#ac60bf', '#e59539', |
|
1188 | '#7700b3', '#593a16', '#073300', '#1d4b73', '#ac60bf', '#e59539', | |
1189 | '#4f8c46', '#368dd9', '#5c0073' |
|
1189 | '#4f8c46', '#368dd9', '#5c0073' | |
1190 | ] |
|
1190 | ] | |
1191 |
|
1191 | |||
1192 | def rgb_to_hex_color(self, rgb_tuple): |
|
1192 | def rgb_to_hex_color(self, rgb_tuple): | |
1193 | """ |
|
1193 | """ | |
1194 | Converts an rgb_tuple passed to an hex color. |
|
1194 | Converts an rgb_tuple passed to an hex color. | |
1195 |
|
1195 | |||
1196 | :param rgb_tuple: tuple with 3 ints represents rgb color space |
|
1196 | :param rgb_tuple: tuple with 3 ints represents rgb color space | |
1197 | """ |
|
1197 | """ | |
1198 | return '#' + ("".join(map(chr, rgb_tuple)).encode('hex')) |
|
1198 | return '#' + ("".join(map(chr, rgb_tuple)).encode('hex')) | |
1199 |
|
1199 | |||
1200 | def email_to_int_list(self, email_str): |
|
1200 | def email_to_int_list(self, email_str): | |
1201 | """ |
|
1201 | """ | |
1202 | Get every byte of the hex digest value of email and turn it to integer. |
|
1202 | Get every byte of the hex digest value of email and turn it to integer. | |
1203 | It's going to be always between 0-255 |
|
1203 | It's going to be always between 0-255 | |
1204 | """ |
|
1204 | """ | |
1205 | digest = md5_safe(email_str.lower()) |
|
1205 | digest = md5_safe(email_str.lower()) | |
1206 | return [int(digest[i * 2:i * 2 + 2], 16) for i in range(16)] |
|
1206 | return [int(digest[i * 2:i * 2 + 2], 16) for i in range(16)] | |
1207 |
|
1207 | |||
1208 | def pick_color_bank_index(self, email_str, color_bank): |
|
1208 | def pick_color_bank_index(self, email_str, color_bank): | |
1209 | return self.email_to_int_list(email_str)[0] % len(color_bank) |
|
1209 | return self.email_to_int_list(email_str)[0] % len(color_bank) | |
1210 |
|
1210 | |||
1211 | def str2color(self, email_str): |
|
1211 | def str2color(self, email_str): | |
1212 | """ |
|
1212 | """ | |
1213 | Tries to map in a stable algorithm an email to color |
|
1213 | Tries to map in a stable algorithm an email to color | |
1214 |
|
1214 | |||
1215 | :param email_str: |
|
1215 | :param email_str: | |
1216 | """ |
|
1216 | """ | |
1217 | color_bank = self.get_color_bank() |
|
1217 | color_bank = self.get_color_bank() | |
1218 | # pick position (module it's length so we always find it in the |
|
1218 | # pick position (module it's length so we always find it in the | |
1219 | # bank even if it's smaller than 256 values |
|
1219 | # bank even if it's smaller than 256 values | |
1220 | pos = self.pick_color_bank_index(email_str, color_bank) |
|
1220 | pos = self.pick_color_bank_index(email_str, color_bank) | |
1221 | return color_bank[pos] |
|
1221 | return color_bank[pos] | |
1222 |
|
1222 | |||
1223 | def normalize_email(self, email_address): |
|
1223 | def normalize_email(self, email_address): | |
1224 | import unicodedata |
|
1224 | import unicodedata | |
1225 | # default host used to fill in the fake/missing email |
|
1225 | # default host used to fill in the fake/missing email | |
1226 | default_host = u'localhost' |
|
1226 | default_host = u'localhost' | |
1227 |
|
1227 | |||
1228 | if not email_address: |
|
1228 | if not email_address: | |
1229 | email_address = u'%s@%s' % (User.DEFAULT_USER, default_host) |
|
1229 | email_address = u'%s@%s' % (User.DEFAULT_USER, default_host) | |
1230 |
|
1230 | |||
1231 | email_address = safe_unicode(email_address) |
|
1231 | email_address = safe_unicode(email_address) | |
1232 |
|
1232 | |||
1233 | if u'@' not in email_address: |
|
1233 | if u'@' not in email_address: | |
1234 | email_address = u'%s@%s' % (email_address, default_host) |
|
1234 | email_address = u'%s@%s' % (email_address, default_host) | |
1235 |
|
1235 | |||
1236 | if email_address.endswith(u'@'): |
|
1236 | if email_address.endswith(u'@'): | |
1237 | email_address = u'%s%s' % (email_address, default_host) |
|
1237 | email_address = u'%s%s' % (email_address, default_host) | |
1238 |
|
1238 | |||
1239 | email_address = unicodedata.normalize('NFKD', email_address)\ |
|
1239 | email_address = unicodedata.normalize('NFKD', email_address)\ | |
1240 | .encode('ascii', 'ignore') |
|
1240 | .encode('ascii', 'ignore') | |
1241 | return email_address |
|
1241 | return email_address | |
1242 |
|
1242 | |||
1243 | def get_initials(self): |
|
1243 | def get_initials(self): | |
1244 | """ |
|
1244 | """ | |
1245 | Returns 2 letter initials calculated based on the input. |
|
1245 | Returns 2 letter initials calculated based on the input. | |
1246 | The algorithm picks first given email address, and takes first letter |
|
1246 | The algorithm picks first given email address, and takes first letter | |
1247 | of part before @, and then the first letter of server name. In case |
|
1247 | of part before @, and then the first letter of server name. In case | |
1248 | the part before @ is in a format of `somestring.somestring2` it replaces |
|
1248 | the part before @ is in a format of `somestring.somestring2` it replaces | |
1249 | the server letter with first letter of somestring2 |
|
1249 | the server letter with first letter of somestring2 | |
1250 |
|
1250 | |||
1251 | In case function was initialized with both first and lastname, this |
|
1251 | In case function was initialized with both first and lastname, this | |
1252 | overrides the extraction from email by first letter of the first and |
|
1252 | overrides the extraction from email by first letter of the first and | |
1253 | last name. We add special logic to that functionality, In case Full name |
|
1253 | last name. We add special logic to that functionality, In case Full name | |
1254 | is compound, like Guido Von Rossum, we use last part of the last name |
|
1254 | is compound, like Guido Von Rossum, we use last part of the last name | |
1255 | (Von Rossum) picking `R`. |
|
1255 | (Von Rossum) picking `R`. | |
1256 |
|
1256 | |||
1257 | Function also normalizes the non-ascii characters to they ascii |
|
1257 | Function also normalizes the non-ascii characters to they ascii | |
1258 | representation, eg Ą => A |
|
1258 | representation, eg Ą => A | |
1259 | """ |
|
1259 | """ | |
1260 | import unicodedata |
|
1260 | import unicodedata | |
1261 | # replace non-ascii to ascii |
|
1261 | # replace non-ascii to ascii | |
1262 | first_name = unicodedata.normalize( |
|
1262 | first_name = unicodedata.normalize( | |
1263 | 'NFKD', safe_unicode(self.first_name)).encode('ascii', 'ignore') |
|
1263 | 'NFKD', safe_unicode(self.first_name)).encode('ascii', 'ignore') | |
1264 | last_name = unicodedata.normalize( |
|
1264 | last_name = unicodedata.normalize( | |
1265 | 'NFKD', safe_unicode(self.last_name)).encode('ascii', 'ignore') |
|
1265 | 'NFKD', safe_unicode(self.last_name)).encode('ascii', 'ignore') | |
1266 |
|
1266 | |||
1267 | # do NFKD encoding, and also make sure email has proper format |
|
1267 | # do NFKD encoding, and also make sure email has proper format | |
1268 | email_address = self.normalize_email(self.email_address) |
|
1268 | email_address = self.normalize_email(self.email_address) | |
1269 |
|
1269 | |||
1270 | # first push the email initials |
|
1270 | # first push the email initials | |
1271 | prefix, server = email_address.split('@', 1) |
|
1271 | prefix, server = email_address.split('@', 1) | |
1272 |
|
1272 | |||
1273 | # check if prefix is maybe a 'first_name.last_name' syntax |
|
1273 | # check if prefix is maybe a 'first_name.last_name' syntax | |
1274 | _dot_split = prefix.rsplit('.', 1) |
|
1274 | _dot_split = prefix.rsplit('.', 1) | |
1275 | if len(_dot_split) == 2 and _dot_split[1]: |
|
1275 | if len(_dot_split) == 2 and _dot_split[1]: | |
1276 | initials = [_dot_split[0][0], _dot_split[1][0]] |
|
1276 | initials = [_dot_split[0][0], _dot_split[1][0]] | |
1277 | else: |
|
1277 | else: | |
1278 | initials = [prefix[0], server[0]] |
|
1278 | initials = [prefix[0], server[0]] | |
1279 |
|
1279 | |||
1280 | # then try to replace either first_name or last_name |
|
1280 | # then try to replace either first_name or last_name | |
1281 | fn_letter = (first_name or " ")[0].strip() |
|
1281 | fn_letter = (first_name or " ")[0].strip() | |
1282 | ln_letter = (last_name.split(' ', 1)[-1] or " ")[0].strip() |
|
1282 | ln_letter = (last_name.split(' ', 1)[-1] or " ")[0].strip() | |
1283 |
|
1283 | |||
1284 | if fn_letter: |
|
1284 | if fn_letter: | |
1285 | initials[0] = fn_letter |
|
1285 | initials[0] = fn_letter | |
1286 |
|
1286 | |||
1287 | if ln_letter: |
|
1287 | if ln_letter: | |
1288 | initials[1] = ln_letter |
|
1288 | initials[1] = ln_letter | |
1289 |
|
1289 | |||
1290 | return ''.join(initials).upper() |
|
1290 | return ''.join(initials).upper() | |
1291 |
|
1291 | |||
1292 | def get_img_data_by_type(self, font_family, img_type): |
|
1292 | def get_img_data_by_type(self, font_family, img_type): | |
1293 | default_user = """ |
|
1293 | default_user = """ | |
1294 | <svg xmlns="http://www.w3.org/2000/svg" |
|
1294 | <svg xmlns="http://www.w3.org/2000/svg" | |
1295 | version="1.1" x="0px" y="0px" width="{size}" height="{size}" |
|
1295 | version="1.1" x="0px" y="0px" width="{size}" height="{size}" | |
1296 | viewBox="-15 -10 439.165 429.164" |
|
1296 | viewBox="-15 -10 439.165 429.164" | |
1297 |
|
1297 | |||
1298 | xml:space="preserve" |
|
1298 | xml:space="preserve" | |
1299 | style="background:{background};" > |
|
1299 | style="background:{background};" > | |
1300 |
|
1300 | |||
1301 | <path d="M204.583,216.671c50.664,0,91.74-48.075, |
|
1301 | <path d="M204.583,216.671c50.664,0,91.74-48.075, | |
1302 | 91.74-107.378c0-82.237-41.074-107.377-91.74-107.377 |
|
1302 | 91.74-107.378c0-82.237-41.074-107.377-91.74-107.377 | |
1303 | c-50.668,0-91.74,25.14-91.74,107.377C112.844, |
|
1303 | c-50.668,0-91.74,25.14-91.74,107.377C112.844, | |
1304 | 168.596,153.916,216.671, |
|
1304 | 168.596,153.916,216.671, | |
1305 | 204.583,216.671z" fill="{text_color}"/> |
|
1305 | 204.583,216.671z" fill="{text_color}"/> | |
1306 | <path d="M407.164,374.717L360.88, |
|
1306 | <path d="M407.164,374.717L360.88, | |
1307 | 270.454c-2.117-4.771-5.836-8.728-10.465-11.138l-71.83-37.392 |
|
1307 | 270.454c-2.117-4.771-5.836-8.728-10.465-11.138l-71.83-37.392 | |
1308 | c-1.584-0.823-3.502-0.663-4.926,0.415c-20.316, |
|
1308 | c-1.584-0.823-3.502-0.663-4.926,0.415c-20.316, | |
1309 | 15.366-44.203,23.488-69.076,23.488c-24.877, |
|
1309 | 15.366-44.203,23.488-69.076,23.488c-24.877, | |
1310 | 0-48.762-8.122-69.078-23.488 |
|
1310 | 0-48.762-8.122-69.078-23.488 | |
1311 | c-1.428-1.078-3.346-1.238-4.93-0.415L58.75, |
|
1311 | c-1.428-1.078-3.346-1.238-4.93-0.415L58.75, | |
1312 | 259.316c-4.631,2.41-8.346,6.365-10.465,11.138L2.001,374.717 |
|
1312 | 259.316c-4.631,2.41-8.346,6.365-10.465,11.138L2.001,374.717 | |
1313 | c-3.191,7.188-2.537,15.412,1.75,22.005c4.285, |
|
1313 | c-3.191,7.188-2.537,15.412,1.75,22.005c4.285, | |
1314 | 6.592,11.537,10.526,19.4,10.526h362.861c7.863,0,15.117-3.936, |
|
1314 | 6.592,11.537,10.526,19.4,10.526h362.861c7.863,0,15.117-3.936, | |
1315 | 19.402-10.527 C409.699,390.129, |
|
1315 | 19.402-10.527 C409.699,390.129, | |
1316 | 410.355,381.902,407.164,374.717z" fill="{text_color}"/> |
|
1316 | 410.355,381.902,407.164,374.717z" fill="{text_color}"/> | |
1317 | </svg>""".format( |
|
1317 | </svg>""".format( | |
1318 | size=self.size, |
|
1318 | size=self.size, | |
1319 | background='#979797', # @grey4 |
|
1319 | background='#979797', # @grey4 | |
1320 | text_color=self.text_color, |
|
1320 | text_color=self.text_color, | |
1321 | font_family=font_family) |
|
1321 | font_family=font_family) | |
1322 |
|
1322 | |||
1323 | return { |
|
1323 | return { | |
1324 | "default_user": default_user |
|
1324 | "default_user": default_user | |
1325 | }[img_type] |
|
1325 | }[img_type] | |
1326 |
|
1326 | |||
1327 | def get_img_data(self, svg_type=None): |
|
1327 | def get_img_data(self, svg_type=None): | |
1328 | """ |
|
1328 | """ | |
1329 | generates the svg metadata for image |
|
1329 | generates the svg metadata for image | |
1330 | """ |
|
1330 | """ | |
1331 | fonts = [ |
|
1331 | fonts = [ | |
1332 | '-apple-system', |
|
1332 | '-apple-system', | |
1333 | 'BlinkMacSystemFont', |
|
1333 | 'BlinkMacSystemFont', | |
1334 | 'Segoe UI', |
|
1334 | 'Segoe UI', | |
1335 | 'Roboto', |
|
1335 | 'Roboto', | |
1336 | 'Oxygen-Sans', |
|
1336 | 'Oxygen-Sans', | |
1337 | 'Ubuntu', |
|
1337 | 'Ubuntu', | |
1338 | 'Cantarell', |
|
1338 | 'Cantarell', | |
1339 | 'Helvetica Neue', |
|
1339 | 'Helvetica Neue', | |
1340 | 'sans-serif' |
|
1340 | 'sans-serif' | |
1341 | ] |
|
1341 | ] | |
1342 | font_family = ','.join(fonts) |
|
1342 | font_family = ','.join(fonts) | |
1343 | if svg_type: |
|
1343 | if svg_type: | |
1344 | return self.get_img_data_by_type(font_family, svg_type) |
|
1344 | return self.get_img_data_by_type(font_family, svg_type) | |
1345 |
|
1345 | |||
1346 | initials = self.get_initials() |
|
1346 | initials = self.get_initials() | |
1347 | img_data = """ |
|
1347 | img_data = """ | |
1348 | <svg xmlns="http://www.w3.org/2000/svg" pointer-events="none" |
|
1348 | <svg xmlns="http://www.w3.org/2000/svg" pointer-events="none" | |
1349 | width="{size}" height="{size}" |
|
1349 | width="{size}" height="{size}" | |
1350 | style="width: 100%; height: 100%; background-color: {background}" |
|
1350 | style="width: 100%; height: 100%; background-color: {background}" | |
1351 | viewBox="0 0 {size} {size}"> |
|
1351 | viewBox="0 0 {size} {size}"> | |
1352 | <text text-anchor="middle" y="50%" x="50%" dy="0.35em" |
|
1352 | <text text-anchor="middle" y="50%" x="50%" dy="0.35em" | |
1353 | pointer-events="auto" fill="{text_color}" |
|
1353 | pointer-events="auto" fill="{text_color}" | |
1354 | font-family="{font_family}" |
|
1354 | font-family="{font_family}" | |
1355 | style="font-weight: 400; font-size: {f_size}px;">{text} |
|
1355 | style="font-weight: 400; font-size: {f_size}px;">{text} | |
1356 | </text> |
|
1356 | </text> | |
1357 | </svg>""".format( |
|
1357 | </svg>""".format( | |
1358 | size=self.size, |
|
1358 | size=self.size, | |
1359 | f_size=self.size/2.05, # scale the text inside the box nicely |
|
1359 | f_size=self.size/2.05, # scale the text inside the box nicely | |
1360 | background=self.background, |
|
1360 | background=self.background, | |
1361 | text_color=self.text_color, |
|
1361 | text_color=self.text_color, | |
1362 | text=initials.upper(), |
|
1362 | text=initials.upper(), | |
1363 | font_family=font_family) |
|
1363 | font_family=font_family) | |
1364 |
|
1364 | |||
1365 | return img_data |
|
1365 | return img_data | |
1366 |
|
1366 | |||
1367 | def generate_svg(self, svg_type=None): |
|
1367 | def generate_svg(self, svg_type=None): | |
1368 | img_data = self.get_img_data(svg_type) |
|
1368 | img_data = self.get_img_data(svg_type) | |
1369 | return "data:image/svg+xml;base64,%s" % base64.b64encode(img_data) |
|
1369 | return "data:image/svg+xml;base64,%s" % base64.b64encode(img_data) | |
1370 |
|
1370 | |||
1371 |
|
1371 | |||
1372 | def initials_gravatar(request, email_address, first_name, last_name, size=30, store_on_disk=False): |
|
1372 | def initials_gravatar(request, email_address, first_name, last_name, size=30, store_on_disk=False): | |
1373 |
|
1373 | |||
1374 | svg_type = None |
|
1374 | svg_type = None | |
1375 | if email_address == User.DEFAULT_USER_EMAIL: |
|
1375 | if email_address == User.DEFAULT_USER_EMAIL: | |
1376 | svg_type = 'default_user' |
|
1376 | svg_type = 'default_user' | |
1377 |
|
1377 | |||
1378 | klass = InitialsGravatar(email_address, first_name, last_name, size) |
|
1378 | klass = InitialsGravatar(email_address, first_name, last_name, size) | |
1379 |
|
1379 | |||
1380 | if store_on_disk: |
|
1380 | if store_on_disk: | |
1381 | from rhodecode.apps.file_store import utils as store_utils |
|
1381 | from rhodecode.apps.file_store import utils as store_utils | |
1382 | from rhodecode.apps.file_store.exceptions import FileNotAllowedException, \ |
|
1382 | from rhodecode.apps.file_store.exceptions import FileNotAllowedException, \ | |
1383 | FileOverSizeException |
|
1383 | FileOverSizeException | |
1384 | from rhodecode.model.db import Session |
|
1384 | from rhodecode.model.db import Session | |
1385 |
|
1385 | |||
1386 | image_key = md5_safe(email_address.lower() |
|
1386 | image_key = md5_safe(email_address.lower() | |
1387 | + first_name.lower() + last_name.lower()) |
|
1387 | + first_name.lower() + last_name.lower()) | |
1388 |
|
1388 | |||
1389 | storage = store_utils.get_file_storage(request.registry.settings) |
|
1389 | storage = store_utils.get_file_storage(request.registry.settings) | |
1390 | filename = '{}.svg'.format(image_key) |
|
1390 | filename = '{}.svg'.format(image_key) | |
1391 | subdir = 'gravatars' |
|
1391 | subdir = 'gravatars' | |
1392 | # since final name has a counter, we apply the 0 |
|
1392 | # since final name has a counter, we apply the 0 | |
1393 | uid = storage.apply_counter(0, store_utils.uid_filename(filename, randomized=False)) |
|
1393 | uid = storage.apply_counter(0, store_utils.uid_filename(filename, randomized=False)) | |
1394 | store_uid = os.path.join(subdir, uid) |
|
1394 | store_uid = os.path.join(subdir, uid) | |
1395 |
|
1395 | |||
1396 | db_entry = FileStore.get_by_store_uid(store_uid) |
|
1396 | db_entry = FileStore.get_by_store_uid(store_uid) | |
1397 | if db_entry: |
|
1397 | if db_entry: | |
1398 | return request.route_path('download_file', fid=store_uid) |
|
1398 | return request.route_path('download_file', fid=store_uid) | |
1399 |
|
1399 | |||
1400 | img_data = klass.get_img_data(svg_type=svg_type) |
|
1400 | img_data = klass.get_img_data(svg_type=svg_type) | |
1401 | img_file = store_utils.bytes_to_file_obj(img_data) |
|
1401 | img_file = store_utils.bytes_to_file_obj(img_data) | |
1402 |
|
1402 | |||
1403 | try: |
|
1403 | try: | |
1404 | store_uid, metadata = storage.save_file( |
|
1404 | store_uid, metadata = storage.save_file( | |
1405 | img_file, filename, directory=subdir, |
|
1405 | img_file, filename, directory=subdir, | |
1406 | extensions=['.svg'], randomized_name=False) |
|
1406 | extensions=['.svg'], randomized_name=False) | |
1407 | except (FileNotAllowedException, FileOverSizeException): |
|
1407 | except (FileNotAllowedException, FileOverSizeException): | |
1408 | raise |
|
1408 | raise | |
1409 |
|
1409 | |||
1410 | try: |
|
1410 | try: | |
1411 | entry = FileStore.create( |
|
1411 | entry = FileStore.create( | |
1412 | file_uid=store_uid, filename=metadata["filename"], |
|
1412 | file_uid=store_uid, filename=metadata["filename"], | |
1413 | file_hash=metadata["sha256"], file_size=metadata["size"], |
|
1413 | file_hash=metadata["sha256"], file_size=metadata["size"], | |
1414 | file_display_name=filename, |
|
1414 | file_display_name=filename, | |
1415 | file_description=u'user gravatar `{}`'.format(safe_unicode(filename)), |
|
1415 | file_description=u'user gravatar `{}`'.format(safe_unicode(filename)), | |
1416 | hidden=True, check_acl=False, user_id=1 |
|
1416 | hidden=True, check_acl=False, user_id=1 | |
1417 | ) |
|
1417 | ) | |
1418 | Session().add(entry) |
|
1418 | Session().add(entry) | |
1419 | Session().commit() |
|
1419 | Session().commit() | |
1420 | log.debug('Stored upload in DB as %s', entry) |
|
1420 | log.debug('Stored upload in DB as %s', entry) | |
1421 | except Exception: |
|
1421 | except Exception: | |
1422 | raise |
|
1422 | raise | |
1423 |
|
1423 | |||
1424 | return request.route_path('download_file', fid=store_uid) |
|
1424 | return request.route_path('download_file', fid=store_uid) | |
1425 |
|
1425 | |||
1426 | else: |
|
1426 | else: | |
1427 | return klass.generate_svg(svg_type=svg_type) |
|
1427 | return klass.generate_svg(svg_type=svg_type) | |
1428 |
|
1428 | |||
1429 |
|
1429 | |||
1430 | def gravatar_external(request, gravatar_url_tmpl, email_address, size=30): |
|
1430 | def gravatar_external(request, gravatar_url_tmpl, email_address, size=30): | |
1431 | return safe_str(gravatar_url_tmpl)\ |
|
1431 | return safe_str(gravatar_url_tmpl)\ | |
1432 | .replace('{email}', email_address) \ |
|
1432 | .replace('{email}', email_address) \ | |
1433 | .replace('{md5email}', md5_safe(email_address.lower())) \ |
|
1433 | .replace('{md5email}', md5_safe(email_address.lower())) \ | |
1434 | .replace('{netloc}', request.host) \ |
|
1434 | .replace('{netloc}', request.host) \ | |
1435 | .replace('{scheme}', request.scheme) \ |
|
1435 | .replace('{scheme}', request.scheme) \ | |
1436 | .replace('{size}', safe_str(size)) |
|
1436 | .replace('{size}', safe_str(size)) | |
1437 |
|
1437 | |||
1438 |
|
1438 | |||
1439 | def gravatar_url(email_address, size=30, request=None): |
|
1439 | def gravatar_url(email_address, size=30, request=None): | |
1440 | request = request or get_current_request() |
|
1440 | request = request or get_current_request() | |
1441 | _use_gravatar = request.call_context.visual.use_gravatar |
|
1441 | _use_gravatar = request.call_context.visual.use_gravatar | |
1442 |
|
1442 | |||
1443 | email_address = email_address or User.DEFAULT_USER_EMAIL |
|
1443 | email_address = email_address or User.DEFAULT_USER_EMAIL | |
1444 | if isinstance(email_address, unicode): |
|
1444 | if isinstance(email_address, unicode): | |
1445 | # hashlib crashes on unicode items |
|
1445 | # hashlib crashes on unicode items | |
1446 | email_address = safe_str(email_address) |
|
1446 | email_address = safe_str(email_address) | |
1447 |
|
1447 | |||
1448 | # empty email or default user |
|
1448 | # empty email or default user | |
1449 | if not email_address or email_address == User.DEFAULT_USER_EMAIL: |
|
1449 | if not email_address or email_address == User.DEFAULT_USER_EMAIL: | |
1450 | return initials_gravatar(request, User.DEFAULT_USER_EMAIL, '', '', size=size) |
|
1450 | return initials_gravatar(request, User.DEFAULT_USER_EMAIL, '', '', size=size) | |
1451 |
|
1451 | |||
1452 | if _use_gravatar: |
|
1452 | if _use_gravatar: | |
1453 | gravatar_url_tmpl = request.call_context.visual.gravatar_url \ |
|
1453 | gravatar_url_tmpl = request.call_context.visual.gravatar_url \ | |
1454 | or User.DEFAULT_GRAVATAR_URL |
|
1454 | or User.DEFAULT_GRAVATAR_URL | |
1455 | return gravatar_external(request, gravatar_url_tmpl, email_address, size=size) |
|
1455 | return gravatar_external(request, gravatar_url_tmpl, email_address, size=size) | |
1456 |
|
1456 | |||
1457 | else: |
|
1457 | else: | |
1458 | return initials_gravatar(request, email_address, '', '', size=size) |
|
1458 | return initials_gravatar(request, email_address, '', '', size=size) | |
1459 |
|
1459 | |||
1460 |
|
1460 | |||
1461 | def breadcrumb_repo_link(repo): |
|
1461 | def breadcrumb_repo_link(repo): | |
1462 | """ |
|
1462 | """ | |
1463 | Makes a breadcrumbs path link to repo |
|
1463 | Makes a breadcrumbs path link to repo | |
1464 |
|
1464 | |||
1465 | ex:: |
|
1465 | ex:: | |
1466 | group >> subgroup >> repo |
|
1466 | group >> subgroup >> repo | |
1467 |
|
1467 | |||
1468 | :param repo: a Repository instance |
|
1468 | :param repo: a Repository instance | |
1469 | """ |
|
1469 | """ | |
1470 |
|
1470 | |||
1471 | path = [ |
|
1471 | path = [ | |
1472 | link_to(group.name, route_path('repo_group_home', repo_group_name=group.group_name), |
|
1472 | link_to(group.name, route_path('repo_group_home', repo_group_name=group.group_name), | |
1473 | title='last change:{}'.format(format_date(group.last_commit_change))) |
|
1473 | title='last change:{}'.format(format_date(group.last_commit_change))) | |
1474 | for group in repo.groups_with_parents |
|
1474 | for group in repo.groups_with_parents | |
1475 | ] + [ |
|
1475 | ] + [ | |
1476 | link_to(repo.just_name, route_path('repo_summary', repo_name=repo.repo_name), |
|
1476 | link_to(repo.just_name, route_path('repo_summary', repo_name=repo.repo_name), | |
1477 | title='last change:{}'.format(format_date(repo.last_commit_change))) |
|
1477 | title='last change:{}'.format(format_date(repo.last_commit_change))) | |
1478 | ] |
|
1478 | ] | |
1479 |
|
1479 | |||
1480 | return literal(' » '.join(path)) |
|
1480 | return literal(' » '.join(path)) | |
1481 |
|
1481 | |||
1482 |
|
1482 | |||
1483 | def breadcrumb_repo_group_link(repo_group): |
|
1483 | def breadcrumb_repo_group_link(repo_group): | |
1484 | """ |
|
1484 | """ | |
1485 | Makes a breadcrumbs path link to repo |
|
1485 | Makes a breadcrumbs path link to repo | |
1486 |
|
1486 | |||
1487 | ex:: |
|
1487 | ex:: | |
1488 | group >> subgroup |
|
1488 | group >> subgroup | |
1489 |
|
1489 | |||
1490 | :param repo_group: a Repository Group instance |
|
1490 | :param repo_group: a Repository Group instance | |
1491 | """ |
|
1491 | """ | |
1492 |
|
1492 | |||
1493 | path = [ |
|
1493 | path = [ | |
1494 | link_to(group.name, |
|
1494 | link_to(group.name, | |
1495 | route_path('repo_group_home', repo_group_name=group.group_name), |
|
1495 | route_path('repo_group_home', repo_group_name=group.group_name), | |
1496 | title='last change:{}'.format(format_date(group.last_commit_change))) |
|
1496 | title='last change:{}'.format(format_date(group.last_commit_change))) | |
1497 | for group in repo_group.parents |
|
1497 | for group in repo_group.parents | |
1498 | ] + [ |
|
1498 | ] + [ | |
1499 | link_to(repo_group.name, |
|
1499 | link_to(repo_group.name, | |
1500 | route_path('repo_group_home', repo_group_name=repo_group.group_name), |
|
1500 | route_path('repo_group_home', repo_group_name=repo_group.group_name), | |
1501 | title='last change:{}'.format(format_date(repo_group.last_commit_change))) |
|
1501 | title='last change:{}'.format(format_date(repo_group.last_commit_change))) | |
1502 | ] |
|
1502 | ] | |
1503 |
|
1503 | |||
1504 | return literal(' » '.join(path)) |
|
1504 | return literal(' » '.join(path)) | |
1505 |
|
1505 | |||
1506 |
|
1506 | |||
1507 | def format_byte_size_binary(file_size): |
|
1507 | def format_byte_size_binary(file_size): | |
1508 | """ |
|
1508 | """ | |
1509 | Formats file/folder sizes to standard. |
|
1509 | Formats file/folder sizes to standard. | |
1510 | """ |
|
1510 | """ | |
1511 | if file_size is None: |
|
1511 | if file_size is None: | |
1512 | file_size = 0 |
|
1512 | file_size = 0 | |
1513 |
|
1513 | |||
1514 | formatted_size = format_byte_size(file_size, binary=True) |
|
1514 | formatted_size = format_byte_size(file_size, binary=True) | |
1515 | return formatted_size |
|
1515 | return formatted_size | |
1516 |
|
1516 | |||
1517 |
|
1517 | |||
1518 | def urlify_text(text_, safe=True, **href_attrs): |
|
1518 | def urlify_text(text_, safe=True, **href_attrs): | |
1519 | """ |
|
1519 | """ | |
1520 | Extract urls from text and make html links out of them |
|
1520 | Extract urls from text and make html links out of them | |
1521 | """ |
|
1521 | """ | |
1522 |
|
1522 | |||
1523 | url_pat = re.compile(r'''(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@#.&+]''' |
|
1523 | url_pat = re.compile(r'''(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@#.&+]''' | |
1524 | '''|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)''') |
|
1524 | '''|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)''') | |
1525 |
|
1525 | |||
1526 | def url_func(match_obj): |
|
1526 | def url_func(match_obj): | |
1527 | url_full = match_obj.groups()[0] |
|
1527 | url_full = match_obj.groups()[0] | |
1528 | a_options = dict(href_attrs) |
|
1528 | a_options = dict(href_attrs) | |
1529 | a_options['href'] = url_full |
|
1529 | a_options['href'] = url_full | |
1530 | a_text = url_full |
|
1530 | a_text = url_full | |
1531 | return HTML.tag("a", a_text, **a_options) |
|
1531 | return HTML.tag("a", a_text, **a_options) | |
1532 |
|
1532 | |||
1533 | _new_text = url_pat.sub(url_func, text_) |
|
1533 | _new_text = url_pat.sub(url_func, text_) | |
1534 |
|
1534 | |||
1535 | if safe: |
|
1535 | if safe: | |
1536 | return literal(_new_text) |
|
1536 | return literal(_new_text) | |
1537 | return _new_text |
|
1537 | return _new_text | |
1538 |
|
1538 | |||
1539 |
|
1539 | |||
1540 | def urlify_commits(text_, repo_name): |
|
1540 | def urlify_commits(text_, repo_name): | |
1541 | """ |
|
1541 | """ | |
1542 | Extract commit ids from text and make link from them |
|
1542 | Extract commit ids from text and make link from them | |
1543 |
|
1543 | |||
1544 | :param text_: |
|
1544 | :param text_: | |
1545 | :param repo_name: repo name to build the URL with |
|
1545 | :param repo_name: repo name to build the URL with | |
1546 | """ |
|
1546 | """ | |
1547 |
|
1547 | |||
1548 | url_pat = re.compile(r'(^|\s)([0-9a-fA-F]{12,40})($|\s)') |
|
1548 | url_pat = re.compile(r'(^|\s)([0-9a-fA-F]{12,40})($|\s)') | |
1549 |
|
1549 | |||
1550 | def url_func(match_obj): |
|
1550 | def url_func(match_obj): | |
1551 | commit_id = match_obj.groups()[1] |
|
1551 | commit_id = match_obj.groups()[1] | |
1552 | pref = match_obj.groups()[0] |
|
1552 | pref = match_obj.groups()[0] | |
1553 | suf = match_obj.groups()[2] |
|
1553 | suf = match_obj.groups()[2] | |
1554 |
|
1554 | |||
1555 | tmpl = ( |
|
1555 | tmpl = ( | |
1556 | '%(pref)s<a class="tooltip-hovercard %(cls)s" href="%(url)s" data-hovercard-alt="%(hovercard_alt)s" data-hovercard-url="%(hovercard_url)s">' |
|
1556 | '%(pref)s<a class="tooltip-hovercard %(cls)s" href="%(url)s" data-hovercard-alt="%(hovercard_alt)s" data-hovercard-url="%(hovercard_url)s">' | |
1557 | '%(commit_id)s</a>%(suf)s' |
|
1557 | '%(commit_id)s</a>%(suf)s' | |
1558 | ) |
|
1558 | ) | |
1559 | return tmpl % { |
|
1559 | return tmpl % { | |
1560 | 'pref': pref, |
|
1560 | 'pref': pref, | |
1561 | 'cls': 'revision-link', |
|
1561 | 'cls': 'revision-link', | |
1562 | 'url': route_url( |
|
1562 | 'url': route_url( | |
1563 | 'repo_commit', repo_name=repo_name, commit_id=commit_id), |
|
1563 | 'repo_commit', repo_name=repo_name, commit_id=commit_id), | |
1564 | 'commit_id': commit_id, |
|
1564 | 'commit_id': commit_id, | |
1565 | 'suf': suf, |
|
1565 | 'suf': suf, | |
1566 | 'hovercard_alt': 'Commit: {}'.format(commit_id), |
|
1566 | 'hovercard_alt': 'Commit: {}'.format(commit_id), | |
1567 | 'hovercard_url': route_url( |
|
1567 | 'hovercard_url': route_url( | |
1568 | 'hovercard_repo_commit', repo_name=repo_name, commit_id=commit_id) |
|
1568 | 'hovercard_repo_commit', repo_name=repo_name, commit_id=commit_id) | |
1569 | } |
|
1569 | } | |
1570 |
|
1570 | |||
1571 | new_text = url_pat.sub(url_func, text_) |
|
1571 | new_text = url_pat.sub(url_func, text_) | |
1572 |
|
1572 | |||
1573 | return new_text |
|
1573 | return new_text | |
1574 |
|
1574 | |||
1575 |
|
1575 | |||
1576 | def _process_url_func(match_obj, repo_name, uid, entry, |
|
1576 | def _process_url_func(match_obj, repo_name, uid, entry, | |
1577 | return_raw_data=False, link_format='html'): |
|
1577 | return_raw_data=False, link_format='html'): | |
1578 | pref = '' |
|
1578 | pref = '' | |
1579 | if match_obj.group().startswith(' '): |
|
1579 | if match_obj.group().startswith(' '): | |
1580 | pref = ' ' |
|
1580 | pref = ' ' | |
1581 |
|
1581 | |||
1582 | issue_id = ''.join(match_obj.groups()) |
|
1582 | issue_id = ''.join(match_obj.groups()) | |
1583 |
|
1583 | |||
1584 | if link_format == 'html': |
|
1584 | if link_format == 'html': | |
1585 | tmpl = ( |
|
1585 | tmpl = ( | |
1586 | '%(pref)s<a class="tooltip %(cls)s" href="%(url)s" title="%(title)s">' |
|
1586 | '%(pref)s<a class="tooltip %(cls)s" href="%(url)s" title="%(title)s">' | |
1587 | '%(issue-prefix)s%(id-repr)s' |
|
1587 | '%(issue-prefix)s%(id-repr)s' | |
1588 | '</a>') |
|
1588 | '</a>') | |
1589 | elif link_format == 'html+hovercard': |
|
1589 | elif link_format == 'html+hovercard': | |
1590 | tmpl = ( |
|
1590 | tmpl = ( | |
1591 | '%(pref)s<a class="tooltip-hovercard %(cls)s" href="%(url)s" data-hovercard-url="%(hovercard_url)s">' |
|
1591 | '%(pref)s<a class="tooltip-hovercard %(cls)s" href="%(url)s" data-hovercard-url="%(hovercard_url)s">' | |
1592 | '%(issue-prefix)s%(id-repr)s' |
|
1592 | '%(issue-prefix)s%(id-repr)s' | |
1593 | '</a>') |
|
1593 | '</a>') | |
1594 | elif link_format in ['rst', 'rst+hovercard']: |
|
1594 | elif link_format in ['rst', 'rst+hovercard']: | |
1595 | tmpl = '`%(issue-prefix)s%(id-repr)s <%(url)s>`_' |
|
1595 | tmpl = '`%(issue-prefix)s%(id-repr)s <%(url)s>`_' | |
1596 | elif link_format in ['markdown', 'markdown+hovercard']: |
|
1596 | elif link_format in ['markdown', 'markdown+hovercard']: | |
1597 | tmpl = '[%(pref)s%(issue-prefix)s%(id-repr)s](%(url)s)' |
|
1597 | tmpl = '[%(pref)s%(issue-prefix)s%(id-repr)s](%(url)s)' | |
1598 | else: |
|
1598 | else: | |
1599 | raise ValueError('Bad link_format:{}'.format(link_format)) |
|
1599 | raise ValueError('Bad link_format:{}'.format(link_format)) | |
1600 |
|
1600 | |||
1601 | (repo_name_cleaned, |
|
1601 | (repo_name_cleaned, | |
1602 | parent_group_name) = RepoGroupModel()._get_group_name_and_parent(repo_name) |
|
1602 | parent_group_name) = RepoGroupModel()._get_group_name_and_parent(repo_name) | |
1603 |
|
1603 | |||
1604 | # variables replacement |
|
1604 | # variables replacement | |
1605 | named_vars = { |
|
1605 | named_vars = { | |
1606 | 'id': issue_id, |
|
1606 | 'id': issue_id, | |
1607 | 'repo': repo_name, |
|
1607 | 'repo': repo_name, | |
1608 | 'repo_name': repo_name_cleaned, |
|
1608 | 'repo_name': repo_name_cleaned, | |
1609 | 'group_name': parent_group_name, |
|
1609 | 'group_name': parent_group_name, | |
1610 | # set dummy keys so we always have them |
|
1610 | # set dummy keys so we always have them | |
1611 | 'hostname': '', |
|
1611 | 'hostname': '', | |
1612 | 'netloc': '', |
|
1612 | 'netloc': '', | |
1613 | 'scheme': '' |
|
1613 | 'scheme': '' | |
1614 | } |
|
1614 | } | |
1615 |
|
1615 | |||
1616 | request = get_current_request() |
|
1616 | request = get_current_request() | |
1617 | if request: |
|
1617 | if request: | |
1618 | # exposes, hostname, netloc, scheme |
|
1618 | # exposes, hostname, netloc, scheme | |
1619 | host_data = get_host_info(request) |
|
1619 | host_data = get_host_info(request) | |
1620 | named_vars.update(host_data) |
|
1620 | named_vars.update(host_data) | |
1621 |
|
1621 | |||
1622 | # named regex variables |
|
1622 | # named regex variables | |
1623 | named_vars.update(match_obj.groupdict()) |
|
1623 | named_vars.update(match_obj.groupdict()) | |
1624 | _url = string.Template(entry['url']).safe_substitute(**named_vars) |
|
1624 | _url = string.Template(entry['url']).safe_substitute(**named_vars) | |
1625 | desc = string.Template(escape(entry['desc'])).safe_substitute(**named_vars) |
|
1625 | desc = string.Template(escape(entry['desc'])).safe_substitute(**named_vars) | |
1626 | hovercard_url = string.Template(entry.get('hovercard_url', '')).safe_substitute(**named_vars) |
|
1626 | hovercard_url = string.Template(entry.get('hovercard_url', '')).safe_substitute(**named_vars) | |
1627 |
|
1627 | |||
1628 | def quote_cleaner(input_str): |
|
1628 | def quote_cleaner(input_str): | |
1629 | """Remove quotes as it's HTML""" |
|
1629 | """Remove quotes as it's HTML""" | |
1630 | return input_str.replace('"', '') |
|
1630 | return input_str.replace('"', '') | |
1631 |
|
1631 | |||
1632 | data = { |
|
1632 | data = { | |
1633 | 'pref': pref, |
|
1633 | 'pref': pref, | |
1634 | 'cls': quote_cleaner('issue-tracker-link'), |
|
1634 | 'cls': quote_cleaner('issue-tracker-link'), | |
1635 | 'url': quote_cleaner(_url), |
|
1635 | 'url': quote_cleaner(_url), | |
1636 | 'id-repr': issue_id, |
|
1636 | 'id-repr': issue_id, | |
1637 | 'issue-prefix': entry['pref'], |
|
1637 | 'issue-prefix': entry['pref'], | |
1638 | 'serv': entry['url'], |
|
1638 | 'serv': entry['url'], | |
1639 | 'title': bleach.clean(desc, strip=True), |
|
1639 | 'title': bleach.clean(desc, strip=True), | |
1640 | 'hovercard_url': hovercard_url |
|
1640 | 'hovercard_url': hovercard_url | |
1641 | } |
|
1641 | } | |
1642 |
|
1642 | |||
1643 | if return_raw_data: |
|
1643 | if return_raw_data: | |
1644 | return { |
|
1644 | return { | |
1645 | 'id': issue_id, |
|
1645 | 'id': issue_id, | |
1646 | 'url': _url |
|
1646 | 'url': _url | |
1647 | } |
|
1647 | } | |
1648 | return tmpl % data |
|
1648 | return tmpl % data | |
1649 |
|
1649 | |||
1650 |
|
1650 | |||
1651 | def get_active_pattern_entries(repo_name): |
|
1651 | def get_active_pattern_entries(repo_name): | |
1652 | repo = None |
|
1652 | repo = None | |
1653 | if repo_name: |
|
1653 | if repo_name: | |
1654 | # Retrieving repo_name to avoid invalid repo_name to explode on |
|
1654 | # Retrieving repo_name to avoid invalid repo_name to explode on | |
1655 | # IssueTrackerSettingsModel but still passing invalid name further down |
|
1655 | # IssueTrackerSettingsModel but still passing invalid name further down | |
1656 | repo = Repository.get_by_repo_name(repo_name, cache=True) |
|
1656 | repo = Repository.get_by_repo_name(repo_name, cache=True) | |
1657 |
|
1657 | |||
1658 | settings_model = IssueTrackerSettingsModel(repo=repo) |
|
1658 | settings_model = IssueTrackerSettingsModel(repo=repo) | |
1659 | active_entries = settings_model.get_settings(cache=True) |
|
1659 | active_entries = settings_model.get_settings(cache=True) | |
1660 | return active_entries |
|
1660 | return active_entries | |
1661 |
|
1661 | |||
1662 |
|
1662 | |||
1663 | pr_pattern_re = regex.compile(r'(?:(?:^!)|(?: !))(\d+)') |
|
1663 | pr_pattern_re = regex.compile(r'(?:(?:^!)|(?: !))(\d+)') | |
1664 |
|
1664 | |||
1665 | allowed_link_formats = [ |
|
1665 | allowed_link_formats = [ | |
1666 | 'html', 'rst', 'markdown', 'html+hovercard', 'rst+hovercard', 'markdown+hovercard'] |
|
1666 | 'html', 'rst', 'markdown', 'html+hovercard', 'rst+hovercard', 'markdown+hovercard'] | |
1667 |
|
1667 | |||
1668 | compile_cache = { |
|
1668 | compile_cache = { | |
1669 |
|
1669 | |||
1670 | } |
|
1670 | } | |
1671 |
|
1671 | |||
1672 |
|
1672 | |||
1673 | def process_patterns(text_string, repo_name, link_format='html', active_entries=None): |
|
1673 | def process_patterns(text_string, repo_name, link_format='html', active_entries=None): | |
1674 |
|
1674 | |||
1675 | if link_format not in allowed_link_formats: |
|
1675 | if link_format not in allowed_link_formats: | |
1676 | raise ValueError('Link format can be only one of:{} got {}'.format( |
|
1676 | raise ValueError('Link format can be only one of:{} got {}'.format( | |
1677 | allowed_link_formats, link_format)) |
|
1677 | allowed_link_formats, link_format)) | |
1678 | issues_data = [] |
|
1678 | issues_data = [] | |
1679 | errors = [] |
|
1679 | errors = [] | |
1680 | new_text = text_string |
|
1680 | new_text = text_string | |
1681 |
|
1681 | |||
1682 | if active_entries is None: |
|
1682 | if active_entries is None: | |
1683 | log.debug('Fetch active issue tracker patterns for repo: %s', repo_name) |
|
1683 | log.debug('Fetch active issue tracker patterns for repo: %s', repo_name) | |
1684 | active_entries = get_active_pattern_entries(repo_name) |
|
1684 | active_entries = get_active_pattern_entries(repo_name) | |
1685 |
|
1685 | |||
1686 | log.debug('Got %s pattern entries to process', len(active_entries)) |
|
1686 | log.debug('Got %s pattern entries to process', len(active_entries)) | |
1687 |
|
1687 | |||
1688 | for uid, entry in active_entries.items(): |
|
1688 | for uid, entry in active_entries.items(): | |
1689 |
|
1689 | |||
1690 | if not (entry['pat'] and entry['url']): |
|
1690 | if not (entry['pat'] and entry['url']): | |
1691 | log.debug('skipping due to missing data') |
|
1691 | log.debug('skipping due to missing data') | |
1692 | continue |
|
1692 | continue | |
1693 |
|
1693 | |||
1694 | log.debug('issue tracker entry: uid: `%s` PAT:%s URL:%s PREFIX:%s', |
|
1694 | log.debug('issue tracker entry: uid: `%s` PAT:%s URL:%s PREFIX:%s', | |
1695 | uid, entry['pat'], entry['url'], entry['pref']) |
|
1695 | uid, entry['pat'], entry['url'], entry['pref']) | |
1696 |
|
1696 | |||
1697 | if entry.get('pat_compiled'): |
|
1697 | if entry.get('pat_compiled'): | |
1698 | pattern = entry['pat_compiled'] |
|
1698 | pattern = entry['pat_compiled'] | |
1699 | elif entry['pat'] in compile_cache: |
|
1699 | elif entry['pat'] in compile_cache: | |
1700 | pattern = compile_cache[entry['pat']] |
|
1700 | pattern = compile_cache[entry['pat']] | |
1701 | else: |
|
1701 | else: | |
1702 | try: |
|
1702 | try: | |
1703 | pattern = regex.compile(r'%s' % entry['pat']) |
|
1703 | pattern = regex.compile(r'%s' % entry['pat']) | |
1704 | except regex.error as e: |
|
1704 | except regex.error as e: | |
1705 | regex_err = ValueError('{}:{}'.format(entry['pat'], e)) |
|
1705 | regex_err = ValueError('{}:{}'.format(entry['pat'], e)) | |
1706 | log.exception('issue tracker pattern: `%s` failed to compile', regex_err) |
|
1706 | log.exception('issue tracker pattern: `%s` failed to compile', regex_err) | |
1707 | errors.append(regex_err) |
|
1707 | errors.append(regex_err) | |
1708 | continue |
|
1708 | continue | |
1709 | compile_cache[entry['pat']] = pattern |
|
1709 | compile_cache[entry['pat']] = pattern | |
1710 |
|
1710 | |||
1711 | data_func = partial( |
|
1711 | data_func = partial( | |
1712 | _process_url_func, repo_name=repo_name, entry=entry, uid=uid, |
|
1712 | _process_url_func, repo_name=repo_name, entry=entry, uid=uid, | |
1713 | return_raw_data=True) |
|
1713 | return_raw_data=True) | |
1714 |
|
1714 | |||
1715 | for match_obj in pattern.finditer(text_string): |
|
1715 | for match_obj in pattern.finditer(text_string): | |
1716 | issues_data.append(data_func(match_obj)) |
|
1716 | issues_data.append(data_func(match_obj)) | |
1717 |
|
1717 | |||
1718 | url_func = partial( |
|
1718 | url_func = partial( | |
1719 | _process_url_func, repo_name=repo_name, entry=entry, uid=uid, |
|
1719 | _process_url_func, repo_name=repo_name, entry=entry, uid=uid, | |
1720 | link_format=link_format) |
|
1720 | link_format=link_format) | |
1721 |
|
1721 | |||
1722 | new_text = pattern.sub(url_func, new_text) |
|
1722 | new_text = pattern.sub(url_func, new_text) | |
1723 | log.debug('processed prefix:uid `%s`', uid) |
|
1723 | log.debug('processed prefix:uid `%s`', uid) | |
1724 |
|
1724 | |||
1725 | # finally use global replace, eg !123 -> pr-link, those will not catch |
|
1725 | # finally use global replace, eg !123 -> pr-link, those will not catch | |
1726 | # if already similar pattern exists |
|
1726 | # if already similar pattern exists | |
1727 | server_url = '${scheme}://${netloc}' |
|
1727 | server_url = '${scheme}://${netloc}' | |
1728 | pr_entry = { |
|
1728 | pr_entry = { | |
1729 | 'pref': '!', |
|
1729 | 'pref': '!', | |
1730 | 'url': server_url + '/_admin/pull-requests/${id}', |
|
1730 | 'url': server_url + '/_admin/pull-requests/${id}', | |
1731 | 'desc': 'Pull Request !${id}', |
|
1731 | 'desc': 'Pull Request !${id}', | |
1732 | 'hovercard_url': server_url + '/_hovercard/pull_request/${id}' |
|
1732 | 'hovercard_url': server_url + '/_hovercard/pull_request/${id}' | |
1733 | } |
|
1733 | } | |
1734 | pr_url_func = partial( |
|
1734 | pr_url_func = partial( | |
1735 | _process_url_func, repo_name=repo_name, entry=pr_entry, uid=None, |
|
1735 | _process_url_func, repo_name=repo_name, entry=pr_entry, uid=None, | |
1736 | link_format=link_format+'+hovercard') |
|
1736 | link_format=link_format+'+hovercard') | |
1737 | new_text = pr_pattern_re.sub(pr_url_func, new_text) |
|
1737 | new_text = pr_pattern_re.sub(pr_url_func, new_text) | |
1738 | log.debug('processed !pr pattern') |
|
1738 | log.debug('processed !pr pattern') | |
1739 |
|
1739 | |||
1740 | return new_text, issues_data, errors |
|
1740 | return new_text, issues_data, errors | |
1741 |
|
1741 | |||
1742 |
|
1742 | |||
1743 | def urlify_commit_message(commit_text, repository=None, active_pattern_entries=None, |
|
1743 | def urlify_commit_message(commit_text, repository=None, active_pattern_entries=None, | |
1744 | issues_container_callback=None, error_container=None): |
|
1744 | issues_container_callback=None, error_container=None): | |
1745 | """ |
|
1745 | """ | |
1746 | Parses given text message and makes proper links. |
|
1746 | Parses given text message and makes proper links. | |
1747 | issues are linked to given issue-server, and rest is a commit link |
|
1747 | issues are linked to given issue-server, and rest is a commit link | |
1748 | """ |
|
1748 | """ | |
1749 |
|
1749 | |||
1750 | def escaper(_text): |
|
1750 | def escaper(_text): | |
1751 | return _text.replace('<', '<').replace('>', '>') |
|
1751 | return _text.replace('<', '<').replace('>', '>') | |
1752 |
|
1752 | |||
1753 | new_text = escaper(commit_text) |
|
1753 | new_text = escaper(commit_text) | |
1754 |
|
1754 | |||
1755 | # extract http/https links and make them real urls |
|
1755 | # extract http/https links and make them real urls | |
1756 | new_text = urlify_text(new_text, safe=False) |
|
1756 | new_text = urlify_text(new_text, safe=False) | |
1757 |
|
1757 | |||
1758 | # urlify commits - extract commit ids and make link out of them, if we have |
|
1758 | # urlify commits - extract commit ids and make link out of them, if we have | |
1759 | # the scope of repository present. |
|
1759 | # the scope of repository present. | |
1760 | if repository: |
|
1760 | if repository: | |
1761 | new_text = urlify_commits(new_text, repository) |
|
1761 | new_text = urlify_commits(new_text, repository) | |
1762 |
|
1762 | |||
1763 | # process issue tracker patterns |
|
1763 | # process issue tracker patterns | |
1764 | new_text, issues, errors = process_patterns( |
|
1764 | new_text, issues, errors = process_patterns( | |
1765 | new_text, repository or '', active_entries=active_pattern_entries) |
|
1765 | new_text, repository or '', active_entries=active_pattern_entries) | |
1766 |
|
1766 | |||
1767 | if issues_container_callback is not None: |
|
1767 | if issues_container_callback is not None: | |
1768 | for issue in issues: |
|
1768 | for issue in issues: | |
1769 | issues_container_callback(issue) |
|
1769 | issues_container_callback(issue) | |
1770 |
|
1770 | |||
1771 | if error_container is not None: |
|
1771 | if error_container is not None: | |
1772 | error_container.extend(errors) |
|
1772 | error_container.extend(errors) | |
1773 |
|
1773 | |||
1774 | return literal(new_text) |
|
1774 | return literal(new_text) | |
1775 |
|
1775 | |||
1776 |
|
1776 | |||
1777 | def render_binary(repo_name, file_obj): |
|
1777 | def render_binary(repo_name, file_obj): | |
1778 | """ |
|
1778 | """ | |
1779 | Choose how to render a binary file |
|
1779 | Choose how to render a binary file | |
1780 | """ |
|
1780 | """ | |
1781 |
|
1781 | |||
1782 | # unicode |
|
1782 | # unicode | |
1783 | filename = file_obj.name |
|
1783 | filename = file_obj.name | |
1784 |
|
1784 | |||
1785 | # images |
|
1785 | # images | |
1786 | for ext in ['*.png', '*.jpeg', '*.jpg', '*.ico', '*.gif']: |
|
1786 | for ext in ['*.png', '*.jpeg', '*.jpg', '*.ico', '*.gif']: | |
1787 | if fnmatch.fnmatch(filename, pat=ext): |
|
1787 | if fnmatch.fnmatch(filename, pat=ext): | |
1788 | src = route_path( |
|
1788 | src = route_path( | |
1789 | 'repo_file_raw', repo_name=repo_name, |
|
1789 | 'repo_file_raw', repo_name=repo_name, | |
1790 | commit_id=file_obj.commit.raw_id, |
|
1790 | commit_id=file_obj.commit.raw_id, | |
1791 | f_path=file_obj.path) |
|
1791 | f_path=file_obj.path) | |
1792 |
|
1792 | |||
1793 | return literal( |
|
1793 | return literal( | |
1794 | '<img class="rendered-binary" alt="rendered-image" src="{}">'.format(src)) |
|
1794 | '<img class="rendered-binary" alt="rendered-image" src="{}">'.format(src)) | |
1795 |
|
1795 | |||
1796 |
|
1796 | |||
1797 | def renderer_from_filename(filename, exclude=None): |
|
1797 | def renderer_from_filename(filename, exclude=None): | |
1798 | """ |
|
1798 | """ | |
1799 | choose a renderer based on filename, this works only for text based files |
|
1799 | choose a renderer based on filename, this works only for text based files | |
1800 | """ |
|
1800 | """ | |
1801 |
|
1801 | |||
1802 | # ipython |
|
1802 | # ipython | |
1803 | for ext in ['*.ipynb']: |
|
1803 | for ext in ['*.ipynb']: | |
1804 | if fnmatch.fnmatch(filename, pat=ext): |
|
1804 | if fnmatch.fnmatch(filename, pat=ext): | |
1805 | return 'jupyter' |
|
1805 | return 'jupyter' | |
1806 |
|
1806 | |||
1807 | is_markup = MarkupRenderer.renderer_from_filename(filename, exclude=exclude) |
|
1807 | is_markup = MarkupRenderer.renderer_from_filename(filename, exclude=exclude) | |
1808 | if is_markup: |
|
1808 | if is_markup: | |
1809 | return is_markup |
|
1809 | return is_markup | |
1810 | return None |
|
1810 | return None | |
1811 |
|
1811 | |||
1812 |
|
1812 | |||
1813 | def render(source, renderer='rst', mentions=False, relative_urls=None, |
|
1813 | def render(source, renderer='rst', mentions=False, relative_urls=None, | |
1814 | repo_name=None, active_pattern_entries=None, issues_container_callback=None): |
|
1814 | repo_name=None, active_pattern_entries=None, issues_container_callback=None): | |
1815 |
|
1815 | |||
1816 | def maybe_convert_relative_links(html_source): |
|
1816 | def maybe_convert_relative_links(html_source): | |
1817 | if relative_urls: |
|
1817 | if relative_urls: | |
1818 | return relative_links(html_source, relative_urls) |
|
1818 | return relative_links(html_source, relative_urls) | |
1819 | return html_source |
|
1819 | return html_source | |
1820 |
|
1820 | |||
1821 | if renderer == 'plain': |
|
1821 | if renderer == 'plain': | |
1822 | return literal( |
|
1822 | return literal( | |
1823 | MarkupRenderer.plain(source, leading_newline=False)) |
|
1823 | MarkupRenderer.plain(source, leading_newline=False)) | |
1824 |
|
1824 | |||
1825 | elif renderer == 'rst': |
|
1825 | elif renderer == 'rst': | |
1826 | if repo_name: |
|
1826 | if repo_name: | |
1827 | # process patterns on comments if we pass in repo name |
|
1827 | # process patterns on comments if we pass in repo name | |
1828 | source, issues, errors = process_patterns( |
|
1828 | source, issues, errors = process_patterns( | |
1829 | source, repo_name, link_format='rst', |
|
1829 | source, repo_name, link_format='rst', | |
1830 | active_entries=active_pattern_entries) |
|
1830 | active_entries=active_pattern_entries) | |
1831 | if issues_container_callback is not None: |
|
1831 | if issues_container_callback is not None: | |
1832 | for issue in issues: |
|
1832 | for issue in issues: | |
1833 | issues_container_callback(issue) |
|
1833 | issues_container_callback(issue) | |
1834 |
|
1834 | |||
1835 | return literal( |
|
1835 | return literal( | |
1836 | '<div class="rst-block">%s</div>' % |
|
1836 | '<div class="rst-block">%s</div>' % | |
1837 | maybe_convert_relative_links( |
|
1837 | maybe_convert_relative_links( | |
1838 | MarkupRenderer.rst(source, mentions=mentions))) |
|
1838 | MarkupRenderer.rst(source, mentions=mentions))) | |
1839 |
|
1839 | |||
1840 | elif renderer == 'markdown': |
|
1840 | elif renderer == 'markdown': | |
1841 | if repo_name: |
|
1841 | if repo_name: | |
1842 | # process patterns on comments if we pass in repo name |
|
1842 | # process patterns on comments if we pass in repo name | |
1843 | source, issues, errors = process_patterns( |
|
1843 | source, issues, errors = process_patterns( | |
1844 | source, repo_name, link_format='markdown', |
|
1844 | source, repo_name, link_format='markdown', | |
1845 | active_entries=active_pattern_entries) |
|
1845 | active_entries=active_pattern_entries) | |
1846 | if issues_container_callback is not None: |
|
1846 | if issues_container_callback is not None: | |
1847 | for issue in issues: |
|
1847 | for issue in issues: | |
1848 | issues_container_callback(issue) |
|
1848 | issues_container_callback(issue) | |
1849 |
|
1849 | |||
1850 |
|
1850 | |||
1851 | return literal( |
|
1851 | return literal( | |
1852 | '<div class="markdown-block">%s</div>' % |
|
1852 | '<div class="markdown-block">%s</div>' % | |
1853 | maybe_convert_relative_links( |
|
1853 | maybe_convert_relative_links( | |
1854 | MarkupRenderer.markdown(source, flavored=True, |
|
1854 | MarkupRenderer.markdown(source, flavored=True, | |
1855 | mentions=mentions))) |
|
1855 | mentions=mentions))) | |
1856 |
|
1856 | |||
1857 | elif renderer == 'jupyter': |
|
1857 | elif renderer == 'jupyter': | |
1858 | return literal( |
|
1858 | return literal( | |
1859 | '<div class="ipynb">%s</div>' % |
|
1859 | '<div class="ipynb">%s</div>' % | |
1860 | maybe_convert_relative_links( |
|
1860 | maybe_convert_relative_links( | |
1861 | MarkupRenderer.jupyter(source))) |
|
1861 | MarkupRenderer.jupyter(source))) | |
1862 |
|
1862 | |||
1863 | # None means just show the file-source |
|
1863 | # None means just show the file-source | |
1864 | return None |
|
1864 | return None | |
1865 |
|
1865 | |||
1866 |
|
1866 | |||
1867 | def commit_status(repo, commit_id): |
|
1867 | def commit_status(repo, commit_id): | |
1868 | return ChangesetStatusModel().get_status(repo, commit_id) |
|
1868 | return ChangesetStatusModel().get_status(repo, commit_id) | |
1869 |
|
1869 | |||
1870 |
|
1870 | |||
1871 | def commit_status_lbl(commit_status): |
|
1871 | def commit_status_lbl(commit_status): | |
1872 | return dict(ChangesetStatus.STATUSES).get(commit_status) |
|
1872 | return dict(ChangesetStatus.STATUSES).get(commit_status) | |
1873 |
|
1873 | |||
1874 |
|
1874 | |||
1875 | def commit_time(repo_name, commit_id): |
|
1875 | def commit_time(repo_name, commit_id): | |
1876 | repo = Repository.get_by_repo_name(repo_name) |
|
1876 | repo = Repository.get_by_repo_name(repo_name) | |
1877 | commit = repo.get_commit(commit_id=commit_id) |
|
1877 | commit = repo.get_commit(commit_id=commit_id) | |
1878 | return commit.date |
|
1878 | return commit.date | |
1879 |
|
1879 | |||
1880 |
|
1880 | |||
1881 | def get_permission_name(key): |
|
1881 | def get_permission_name(key): | |
1882 | return dict(Permission.PERMS).get(key) |
|
1882 | return dict(Permission.PERMS).get(key) | |
1883 |
|
1883 | |||
1884 |
|
1884 | |||
1885 | def journal_filter_help(request): |
|
1885 | def journal_filter_help(request): | |
1886 | _ = request.translate |
|
1886 | _ = request.translate | |
1887 | from rhodecode.lib.audit_logger import ACTIONS |
|
1887 | from rhodecode.lib.audit_logger import ACTIONS | |
1888 | actions = '\n'.join(textwrap.wrap(', '.join(sorted(ACTIONS.keys())), 80)) |
|
1888 | actions = '\n'.join(textwrap.wrap(', '.join(sorted(ACTIONS.keys())), 80)) | |
1889 |
|
1889 | |||
1890 | return _( |
|
1890 | return _( | |
1891 | 'Example filter terms:\n' + |
|
1891 | 'Example filter terms:\n' + | |
1892 | ' repository:vcs\n' + |
|
1892 | ' repository:vcs\n' + | |
1893 | ' username:marcin\n' + |
|
1893 | ' username:marcin\n' + | |
1894 | ' username:(NOT marcin)\n' + |
|
1894 | ' username:(NOT marcin)\n' + | |
1895 | ' action:*push*\n' + |
|
1895 | ' action:*push*\n' + | |
1896 | ' ip:127.0.0.1\n' + |
|
1896 | ' ip:127.0.0.1\n' + | |
1897 | ' date:20120101\n' + |
|
1897 | ' date:20120101\n' + | |
1898 | ' date:[20120101100000 TO 20120102]\n' + |
|
1898 | ' date:[20120101100000 TO 20120102]\n' + | |
1899 | '\n' + |
|
1899 | '\n' + | |
1900 | 'Actions: {actions}\n' + |
|
1900 | 'Actions: {actions}\n' + | |
1901 | '\n' + |
|
1901 | '\n' + | |
1902 | 'Generate wildcards using \'*\' character:\n' + |
|
1902 | 'Generate wildcards using \'*\' character:\n' + | |
1903 | ' "repository:vcs*" - search everything starting with \'vcs\'\n' + |
|
1903 | ' "repository:vcs*" - search everything starting with \'vcs\'\n' + | |
1904 | ' "repository:*vcs*" - search for repository containing \'vcs\'\n' + |
|
1904 | ' "repository:*vcs*" - search for repository containing \'vcs\'\n' + | |
1905 | '\n' + |
|
1905 | '\n' + | |
1906 | 'Optional AND / OR operators in queries\n' + |
|
1906 | 'Optional AND / OR operators in queries\n' + | |
1907 | ' "repository:vcs OR repository:test"\n' + |
|
1907 | ' "repository:vcs OR repository:test"\n' + | |
1908 | ' "username:test AND repository:test*"\n' |
|
1908 | ' "username:test AND repository:test*"\n' | |
1909 | ).format(actions=actions) |
|
1909 | ).format(actions=actions) | |
1910 |
|
1910 | |||
1911 |
|
1911 | |||
1912 | def not_mapped_error(repo_name): |
|
1912 | def not_mapped_error(repo_name): | |
1913 | from rhodecode.translation import _ |
|
1913 | from rhodecode.translation import _ | |
1914 | flash(_('%s repository is not mapped to db perhaps' |
|
1914 | flash(_('%s repository is not mapped to db perhaps' | |
1915 | ' it was created or renamed from the filesystem' |
|
1915 | ' it was created or renamed from the filesystem' | |
1916 | ' please run the application again' |
|
1916 | ' please run the application again' | |
1917 | ' in order to rescan repositories') % repo_name, category='error') |
|
1917 | ' in order to rescan repositories') % repo_name, category='error') | |
1918 |
|
1918 | |||
1919 |
|
1919 | |||
1920 | def ip_range(ip_addr): |
|
1920 | def ip_range(ip_addr): | |
1921 | from rhodecode.model.db import UserIpMap |
|
1921 | from rhodecode.model.db import UserIpMap | |
1922 | s, e = UserIpMap._get_ip_range(ip_addr) |
|
1922 | s, e = UserIpMap._get_ip_range(ip_addr) | |
1923 | return '%s - %s' % (s, e) |
|
1923 | return '%s - %s' % (s, e) | |
1924 |
|
1924 | |||
1925 |
|
1925 | |||
1926 | def form(url, method='post', needs_csrf_token=True, **attrs): |
|
1926 | def form(url, method='post', needs_csrf_token=True, **attrs): | |
1927 | """Wrapper around webhelpers.tags.form to prevent CSRF attacks.""" |
|
1927 | """Wrapper around webhelpers.tags.form to prevent CSRF attacks.""" | |
1928 | if method.lower() != 'get' and needs_csrf_token: |
|
1928 | if method.lower() != 'get' and needs_csrf_token: | |
1929 | raise Exception( |
|
1929 | raise Exception( | |
1930 | 'Forms to POST/PUT/DELETE endpoints should have (in general) a ' + |
|
1930 | 'Forms to POST/PUT/DELETE endpoints should have (in general) a ' + | |
1931 | 'CSRF token. If the endpoint does not require such token you can ' + |
|
1931 | 'CSRF token. If the endpoint does not require such token you can ' + | |
1932 | 'explicitly set the parameter needs_csrf_token to false.') |
|
1932 | 'explicitly set the parameter needs_csrf_token to false.') | |
1933 |
|
1933 | |||
1934 | return insecure_form(url, method=method, **attrs) |
|
1934 | return insecure_form(url, method=method, **attrs) | |
1935 |
|
1935 | |||
1936 |
|
1936 | |||
1937 | def secure_form(form_url, method="POST", multipart=False, **attrs): |
|
1937 | def secure_form(form_url, method="POST", multipart=False, **attrs): | |
1938 | """Start a form tag that points the action to an url. This |
|
1938 | """Start a form tag that points the action to an url. This | |
1939 | form tag will also include the hidden field containing |
|
1939 | form tag will also include the hidden field containing | |
1940 | the auth token. |
|
1940 | the auth token. | |
1941 |
|
1941 | |||
1942 | The url options should be given either as a string, or as a |
|
1942 | The url options should be given either as a string, or as a | |
1943 | ``url()`` function. The method for the form defaults to POST. |
|
1943 | ``url()`` function. The method for the form defaults to POST. | |
1944 |
|
1944 | |||
1945 | Options: |
|
1945 | Options: | |
1946 |
|
1946 | |||
1947 | ``multipart`` |
|
1947 | ``multipart`` | |
1948 | If set to True, the enctype is set to "multipart/form-data". |
|
1948 | If set to True, the enctype is set to "multipart/form-data". | |
1949 | ``method`` |
|
1949 | ``method`` | |
1950 | The method to use when submitting the form, usually either |
|
1950 | The method to use when submitting the form, usually either | |
1951 | "GET" or "POST". If "PUT", "DELETE", or another verb is used, a |
|
1951 | "GET" or "POST". If "PUT", "DELETE", or another verb is used, a | |
1952 | hidden input with name _method is added to simulate the verb |
|
1952 | hidden input with name _method is added to simulate the verb | |
1953 | over POST. |
|
1953 | over POST. | |
1954 |
|
1954 | |||
1955 | """ |
|
1955 | """ | |
1956 |
|
1956 | |||
1957 | if 'request' in attrs: |
|
1957 | if 'request' in attrs: | |
1958 | session = attrs['request'].session |
|
1958 | session = attrs['request'].session | |
1959 | del attrs['request'] |
|
1959 | del attrs['request'] | |
1960 | else: |
|
1960 | else: | |
1961 | raise ValueError( |
|
1961 | raise ValueError( | |
1962 | 'Calling this form requires request= to be passed as argument') |
|
1962 | 'Calling this form requires request= to be passed as argument') | |
1963 |
|
1963 | |||
1964 | _form = insecure_form(form_url, method, multipart, **attrs) |
|
1964 | _form = insecure_form(form_url, method, multipart, **attrs) | |
1965 | token = literal( |
|
1965 | token = literal( | |
1966 | '<input type="hidden" name="{}" value="{}">'.format( |
|
1966 | '<input type="hidden" name="{}" value="{}">'.format( | |
1967 | csrf_token_key, get_csrf_token(session))) |
|
1967 | csrf_token_key, get_csrf_token(session))) | |
1968 |
|
1968 | |||
1969 | return literal("%s\n%s" % (_form, token)) |
|
1969 | return literal("%s\n%s" % (_form, token)) | |
1970 |
|
1970 | |||
1971 |
|
1971 | |||
1972 | def dropdownmenu(name, selected, options, enable_filter=False, **attrs): |
|
1972 | def dropdownmenu(name, selected, options, enable_filter=False, **attrs): | |
1973 | select_html = select(name, selected, options, **attrs) |
|
1973 | select_html = select(name, selected, options, **attrs) | |
1974 |
|
1974 | |||
1975 | select2 = """ |
|
1975 | select2 = """ | |
1976 | <script> |
|
1976 | <script> | |
1977 | $(document).ready(function() { |
|
1977 | $(document).ready(function() { | |
1978 | $('#%s').select2({ |
|
1978 | $('#%s').select2({ | |
1979 | containerCssClass: 'drop-menu %s', |
|
1979 | containerCssClass: 'drop-menu %s', | |
1980 | dropdownCssClass: 'drop-menu-dropdown', |
|
1980 | dropdownCssClass: 'drop-menu-dropdown', | |
1981 | dropdownAutoWidth: true%s |
|
1981 | dropdownAutoWidth: true%s | |
1982 | }); |
|
1982 | }); | |
1983 | }); |
|
1983 | }); | |
1984 | </script> |
|
1984 | </script> | |
1985 | """ |
|
1985 | """ | |
1986 |
|
1986 | |||
1987 | filter_option = """, |
|
1987 | filter_option = """, | |
1988 | minimumResultsForSearch: -1 |
|
1988 | minimumResultsForSearch: -1 | |
1989 | """ |
|
1989 | """ | |
1990 | input_id = attrs.get('id') or name |
|
1990 | input_id = attrs.get('id') or name | |
1991 | extra_classes = ' '.join(attrs.pop('extra_classes', [])) |
|
1991 | extra_classes = ' '.join(attrs.pop('extra_classes', [])) | |
1992 | filter_enabled = "" if enable_filter else filter_option |
|
1992 | filter_enabled = "" if enable_filter else filter_option | |
1993 | select_script = literal(select2 % (input_id, extra_classes, filter_enabled)) |
|
1993 | select_script = literal(select2 % (input_id, extra_classes, filter_enabled)) | |
1994 |
|
1994 | |||
1995 | return literal(select_html+select_script) |
|
1995 | return literal(select_html+select_script) | |
1996 |
|
1996 | |||
1997 |
|
1997 | |||
1998 | def get_visual_attr(tmpl_context_var, attr_name): |
|
1998 | def get_visual_attr(tmpl_context_var, attr_name): | |
1999 | """ |
|
1999 | """ | |
2000 | A safe way to get a variable from visual variable of template context |
|
2000 | A safe way to get a variable from visual variable of template context | |
2001 |
|
2001 | |||
2002 | :param tmpl_context_var: instance of tmpl_context, usually present as `c` |
|
2002 | :param tmpl_context_var: instance of tmpl_context, usually present as `c` | |
2003 | :param attr_name: name of the attribute we fetch from the c.visual |
|
2003 | :param attr_name: name of the attribute we fetch from the c.visual | |
2004 | """ |
|
2004 | """ | |
2005 | visual = getattr(tmpl_context_var, 'visual', None) |
|
2005 | visual = getattr(tmpl_context_var, 'visual', None) | |
2006 | if not visual: |
|
2006 | if not visual: | |
2007 | return |
|
2007 | return | |
2008 | else: |
|
2008 | else: | |
2009 | return getattr(visual, attr_name, None) |
|
2009 | return getattr(visual, attr_name, None) | |
2010 |
|
2010 | |||
2011 |
|
2011 | |||
2012 | def get_last_path_part(file_node): |
|
2012 | def get_last_path_part(file_node): | |
2013 | if not file_node.path: |
|
2013 | if not file_node.path: | |
2014 | return u'/' |
|
2014 | return u'/' | |
2015 |
|
2015 | |||
2016 | path = safe_unicode(file_node.path.split('/')[-1]) |
|
2016 | path = safe_unicode(file_node.path.split('/')[-1]) | |
2017 | return u'../' + path |
|
2017 | return u'../' + path | |
2018 |
|
2018 | |||
2019 |
|
2019 | |||
2020 | def route_url(*args, **kwargs): |
|
2020 | def route_url(*args, **kwargs): | |
2021 | """ |
|
2021 | """ | |
2022 | Wrapper around pyramids `route_url` (fully qualified url) function. |
|
2022 | Wrapper around pyramids `route_url` (fully qualified url) function. | |
2023 | """ |
|
2023 | """ | |
2024 | req = get_current_request() |
|
2024 | req = get_current_request() | |
2025 | return req.route_url(*args, **kwargs) |
|
2025 | return req.route_url(*args, **kwargs) | |
2026 |
|
2026 | |||
2027 |
|
2027 | |||
2028 | def route_path(*args, **kwargs): |
|
2028 | def route_path(*args, **kwargs): | |
2029 | """ |
|
2029 | """ | |
2030 | Wrapper around pyramids `route_path` function. |
|
2030 | Wrapper around pyramids `route_path` function. | |
2031 | """ |
|
2031 | """ | |
2032 | req = get_current_request() |
|
2032 | req = get_current_request() | |
2033 | return req.route_path(*args, **kwargs) |
|
2033 | return req.route_path(*args, **kwargs) | |
2034 |
|
2034 | |||
2035 |
|
2035 | |||
2036 | def route_path_or_none(*args, **kwargs): |
|
2036 | def route_path_or_none(*args, **kwargs): | |
2037 | try: |
|
2037 | try: | |
2038 | return route_path(*args, **kwargs) |
|
2038 | return route_path(*args, **kwargs) | |
2039 | except KeyError: |
|
2039 | except KeyError: | |
2040 | return None |
|
2040 | return None | |
2041 |
|
2041 | |||
2042 |
|
2042 | |||
2043 | def current_route_path(request, **kw): |
|
2043 | def current_route_path(request, **kw): | |
2044 | new_args = request.GET.mixed() |
|
2044 | new_args = request.GET.mixed() | |
2045 | new_args.update(kw) |
|
2045 | new_args.update(kw) | |
2046 | return request.current_route_path(_query=new_args) |
|
2046 | return request.current_route_path(_query=new_args) | |
2047 |
|
2047 | |||
2048 |
|
2048 | |||
2049 | def curl_api_example(method, args): |
|
2049 | def curl_api_example(method, args): | |
2050 | args_json = json.dumps(OrderedDict([ |
|
2050 | args_json = json.dumps(OrderedDict([ | |
2051 | ('id', 1), |
|
2051 | ('id', 1), | |
2052 | ('auth_token', 'SECRET'), |
|
2052 | ('auth_token', 'SECRET'), | |
2053 | ('method', method), |
|
2053 | ('method', method), | |
2054 | ('args', args) |
|
2054 | ('args', args) | |
2055 | ])) |
|
2055 | ])) | |
2056 |
|
2056 | |||
2057 | return "curl {api_url} -X POST -H 'content-type:text/plain' --data-binary '{args_json}'".format( |
|
2057 | return "curl {api_url} -X POST -H 'content-type:text/plain' --data-binary '{args_json}'".format( | |
2058 | api_url=route_url('apiv2'), |
|
2058 | api_url=route_url('apiv2'), | |
2059 | args_json=args_json |
|
2059 | args_json=args_json | |
2060 | ) |
|
2060 | ) | |
2061 |
|
2061 | |||
2062 |
|
2062 | |||
2063 | def api_call_example(method, args): |
|
2063 | def api_call_example(method, args): | |
2064 | """ |
|
2064 | """ | |
2065 | Generates an API call example via CURL |
|
2065 | Generates an API call example via CURL | |
2066 | """ |
|
2066 | """ | |
2067 | curl_call = curl_api_example(method, args) |
|
2067 | curl_call = curl_api_example(method, args) | |
2068 |
|
2068 | |||
2069 | return literal( |
|
2069 | return literal( | |
2070 | curl_call + |
|
2070 | curl_call + | |
2071 | "<br/><br/>SECRET can be found in <a href=\"{token_url}\">auth-tokens</a> page, " |
|
2071 | "<br/><br/>SECRET can be found in <a href=\"{token_url}\">auth-tokens</a> page, " | |
2072 | "and needs to be of `api calls` role." |
|
2072 | "and needs to be of `api calls` role." | |
2073 | .format(token_url=route_url('my_account_auth_tokens'))) |
|
2073 | .format(token_url=route_url('my_account_auth_tokens'))) | |
2074 |
|
2074 | |||
2075 |
|
2075 | |||
2076 | def notification_description(notification, request): |
|
2076 | def notification_description(notification, request): | |
2077 | """ |
|
2077 | """ | |
2078 | Generate notification human readable description based on notification type |
|
2078 | Generate notification human readable description based on notification type | |
2079 | """ |
|
2079 | """ | |
2080 | from rhodecode.model.notification import NotificationModel |
|
2080 | from rhodecode.model.notification import NotificationModel | |
2081 | return NotificationModel().make_description( |
|
2081 | return NotificationModel().make_description( | |
2082 | notification, translate=request.translate) |
|
2082 | notification, translate=request.translate) | |
2083 |
|
2083 | |||
2084 |
|
2084 | |||
2085 | def go_import_header(request, db_repo=None): |
|
2085 | def go_import_header(request, db_repo=None): | |
2086 | """ |
|
2086 | """ | |
2087 | Creates a header for go-import functionality in Go Lang |
|
2087 | Creates a header for go-import functionality in Go Lang | |
2088 | """ |
|
2088 | """ | |
2089 |
|
2089 | |||
2090 | if not db_repo: |
|
2090 | if not db_repo: | |
2091 | return |
|
2091 | return | |
2092 | if 'go-get' not in request.GET: |
|
2092 | if 'go-get' not in request.GET: | |
2093 | return |
|
2093 | return | |
2094 |
|
2094 | |||
2095 | clone_url = db_repo.clone_url() |
|
2095 | clone_url = db_repo.clone_url() | |
2096 | prefix = re.split(r'^https?:\/\/', clone_url)[-1] |
|
2096 | prefix = re.split(r'^https?:\/\/', clone_url)[-1] | |
2097 | # we have a repo and go-get flag, |
|
2097 | # we have a repo and go-get flag, | |
2098 | return literal('<meta name="go-import" content="{} {} {}">'.format( |
|
2098 | return literal('<meta name="go-import" content="{} {} {}">'.format( | |
2099 | prefix, db_repo.repo_type, clone_url)) |
|
2099 | prefix, db_repo.repo_type, clone_url)) | |
2100 |
|
2100 | |||
2101 |
|
2101 | |||
2102 | def reviewer_as_json(*args, **kwargs): |
|
2102 | def reviewer_as_json(*args, **kwargs): | |
2103 | from rhodecode.apps.repository.utils import reviewer_as_json as _reviewer_as_json |
|
2103 | from rhodecode.apps.repository.utils import reviewer_as_json as _reviewer_as_json | |
2104 | return _reviewer_as_json(*args, **kwargs) |
|
2104 | return _reviewer_as_json(*args, **kwargs) | |
2105 |
|
2105 | |||
2106 |
|
2106 | |||
2107 | def get_repo_view_type(request): |
|
2107 | def get_repo_view_type(request): | |
2108 | route_name = request.matched_route.name |
|
2108 | route_name = request.matched_route.name | |
2109 | route_to_view_type = { |
|
2109 | route_to_view_type = { | |
2110 | 'repo_changelog': 'commits', |
|
2110 | 'repo_changelog': 'commits', | |
2111 | 'repo_commits': 'commits', |
|
2111 | 'repo_commits': 'commits', | |
2112 | 'repo_files': 'files', |
|
2112 | 'repo_files': 'files', | |
2113 | 'repo_summary': 'summary', |
|
2113 | 'repo_summary': 'summary', | |
2114 | 'repo_commit': 'commit' |
|
2114 | 'repo_commit': 'commit' | |
2115 | } |
|
2115 | } | |
2116 |
|
2116 | |||
2117 | return route_to_view_type.get(route_name) |
|
2117 | return route_to_view_type.get(route_name) | |
2118 |
|
2118 | |||
2119 |
|
2119 | |||
2120 | def is_active(menu_entry, selected): |
|
2120 | def is_active(menu_entry, selected): | |
2121 | """ |
|
2121 | """ | |
2122 | Returns active class for selecting menus in templates |
|
2122 | Returns active class for selecting menus in templates | |
2123 | <li class=${h.is_active('settings', current_active)}></li> |
|
2123 | <li class=${h.is_active('settings', current_active)}></li> | |
2124 | """ |
|
2124 | """ | |
2125 | if not isinstance(menu_entry, list): |
|
2125 | if not isinstance(menu_entry, list): | |
2126 | menu_entry = [menu_entry] |
|
2126 | menu_entry = [menu_entry] | |
2127 |
|
2127 | |||
2128 | if selected in menu_entry: |
|
2128 | if selected in menu_entry: | |
2129 | return "active" |
|
2129 | return "active" | |
2130 |
|
2130 | |||
2131 |
|
2131 | |||
2132 | class IssuesRegistry(object): |
|
2132 | class IssuesRegistry(object): | |
2133 | """ |
|
2133 | """ | |
2134 | issue_registry = IssuesRegistry() |
|
2134 | issue_registry = IssuesRegistry() | |
2135 | some_func(issues_callback=issues_registry(...)) |
|
2135 | some_func(issues_callback=issues_registry(...)) | |
2136 | """ |
|
2136 | """ | |
2137 |
|
2137 | |||
2138 | def __init__(self): |
|
2138 | def __init__(self): | |
2139 | self.issues = [] |
|
2139 | self.issues = [] | |
2140 | self.unique_issues = collections.defaultdict(lambda: []) |
|
2140 | self.unique_issues = collections.defaultdict(lambda: []) | |
2141 |
|
2141 | |||
2142 | def __call__(self, commit_dict=None): |
|
2142 | def __call__(self, commit_dict=None): | |
2143 | def callback(issue): |
|
2143 | def callback(issue): | |
2144 | if commit_dict and issue: |
|
2144 | if commit_dict and issue: | |
2145 | issue['commit'] = commit_dict |
|
2145 | issue['commit'] = commit_dict | |
2146 | self.issues.append(issue) |
|
2146 | self.issues.append(issue) | |
2147 | self.unique_issues[issue['id']].append(issue) |
|
2147 | self.unique_issues[issue['id']].append(issue) | |
2148 | return callback |
|
2148 | return callback | |
2149 |
|
2149 | |||
2150 | def get_issues(self): |
|
2150 | def get_issues(self): | |
2151 | return self.issues |
|
2151 | return self.issues | |
2152 |
|
2152 | |||
2153 | @property |
|
2153 | @property | |
2154 | def issues_unique_count(self): |
|
2154 | def issues_unique_count(self): | |
2155 | return len(set(i['id'] for i in self.issues)) |
|
2155 | return len(set(i['id'] for i in self.issues)) |
@@ -1,679 +1,679 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
|
2 | |||
3 | # Copyright (C) 2014-2020 RhodeCode GmbH |
|
3 | # Copyright (C) 2014-2020 RhodeCode GmbH | |
4 | # |
|
4 | # | |
5 | # This program is free software: you can redistribute it and/or modify |
|
5 | # This program is free software: you can redistribute it and/or modify | |
6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
6 | # it under the terms of the GNU Affero General Public License, version 3 | |
7 | # (only), as published by the Free Software Foundation. |
|
7 | # (only), as published by the Free Software Foundation. | |
8 | # |
|
8 | # | |
9 | # This program is distributed in the hope that it will be useful, |
|
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. |
|
12 | # GNU General Public License for more details. | |
13 | # |
|
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License |
|
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | # |
|
16 | # | |
17 | # This program is dual-licensed. If you wish to learn more about the |
|
17 | # This program is dual-licensed. If you wish to learn more about the | |
18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |
20 |
|
20 | |||
21 | """ |
|
21 | """ | |
22 | SimpleVCS middleware for handling protocol request (push/clone etc.) |
|
22 | SimpleVCS middleware for handling protocol request (push/clone etc.) | |
23 | It's implemented with basic auth function |
|
23 | It's implemented with basic auth function | |
24 | """ |
|
24 | """ | |
25 |
|
25 | |||
26 | import os |
|
26 | import os | |
27 | import re |
|
27 | import re | |
28 | import logging |
|
28 | import logging | |
29 | import importlib |
|
29 | import importlib | |
30 | from functools import wraps |
|
30 | from functools import wraps | |
31 |
from |
|
31 | from io import StringIO | |
32 | from lxml import etree |
|
32 | from lxml import etree | |
33 |
|
33 | |||
34 | import time |
|
34 | import time | |
35 | from paste.httpheaders import REMOTE_USER, AUTH_TYPE |
|
35 | from paste.httpheaders import REMOTE_USER, AUTH_TYPE | |
36 |
|
36 | |||
37 | from pyramid.httpexceptions import ( |
|
37 | from pyramid.httpexceptions import ( | |
38 | HTTPNotFound, HTTPForbidden, HTTPNotAcceptable, HTTPInternalServerError) |
|
38 | HTTPNotFound, HTTPForbidden, HTTPNotAcceptable, HTTPInternalServerError) | |
39 | from zope.cachedescriptors.property import Lazy as LazyProperty |
|
39 | from zope.cachedescriptors.property import Lazy as LazyProperty | |
40 |
|
40 | |||
41 | import rhodecode |
|
41 | import rhodecode | |
42 | from rhodecode.authentication.base import authenticate, VCS_TYPE, loadplugin |
|
42 | from rhodecode.authentication.base import authenticate, VCS_TYPE, loadplugin | |
43 | from rhodecode.lib import rc_cache |
|
43 | from rhodecode.lib import rc_cache | |
44 | from rhodecode.lib.auth import AuthUser, HasPermissionAnyMiddleware |
|
44 | from rhodecode.lib.auth import AuthUser, HasPermissionAnyMiddleware | |
45 | from rhodecode.lib.base import ( |
|
45 | from rhodecode.lib.base import ( | |
46 | BasicAuth, get_ip_addr, get_user_agent, vcs_operation_context) |
|
46 | BasicAuth, get_ip_addr, get_user_agent, vcs_operation_context) | |
47 | from rhodecode.lib.exceptions import (UserCreationError, NotAllowedToCreateUserError) |
|
47 | from rhodecode.lib.exceptions import (UserCreationError, NotAllowedToCreateUserError) | |
48 | from rhodecode.lib.hooks_daemon import prepare_callback_daemon |
|
48 | from rhodecode.lib.hooks_daemon import prepare_callback_daemon | |
49 | from rhodecode.lib.middleware import appenlight |
|
49 | from rhodecode.lib.middleware import appenlight | |
50 | from rhodecode.lib.middleware.utils import scm_app_http |
|
50 | from rhodecode.lib.middleware.utils import scm_app_http | |
51 | from rhodecode.lib.utils import is_valid_repo, SLUG_RE |
|
51 | from rhodecode.lib.utils import is_valid_repo, SLUG_RE | |
52 | from rhodecode.lib.utils2 import safe_str, fix_PATH, str2bool, safe_unicode |
|
52 | from rhodecode.lib.utils2 import safe_str, fix_PATH, str2bool, safe_unicode | |
53 | from rhodecode.lib.vcs.conf import settings as vcs_settings |
|
53 | from rhodecode.lib.vcs.conf import settings as vcs_settings | |
54 | from rhodecode.lib.vcs.backends import base |
|
54 | from rhodecode.lib.vcs.backends import base | |
55 |
|
55 | |||
56 | from rhodecode.model import meta |
|
56 | from rhodecode.model import meta | |
57 | from rhodecode.model.db import User, Repository, PullRequest |
|
57 | from rhodecode.model.db import User, Repository, PullRequest | |
58 | from rhodecode.model.scm import ScmModel |
|
58 | from rhodecode.model.scm import ScmModel | |
59 | from rhodecode.model.pull_request import PullRequestModel |
|
59 | from rhodecode.model.pull_request import PullRequestModel | |
60 | from rhodecode.model.settings import SettingsModel, VcsSettingsModel |
|
60 | from rhodecode.model.settings import SettingsModel, VcsSettingsModel | |
61 |
|
61 | |||
62 | log = logging.getLogger(__name__) |
|
62 | log = logging.getLogger(__name__) | |
63 |
|
63 | |||
64 |
|
64 | |||
65 | def extract_svn_txn_id(acl_repo_name, data): |
|
65 | def extract_svn_txn_id(acl_repo_name, data): | |
66 | """ |
|
66 | """ | |
67 | Helper method for extraction of svn txn_id from submitted XML data during |
|
67 | Helper method for extraction of svn txn_id from submitted XML data during | |
68 | POST operations |
|
68 | POST operations | |
69 | """ |
|
69 | """ | |
70 | try: |
|
70 | try: | |
71 | root = etree.fromstring(data) |
|
71 | root = etree.fromstring(data) | |
72 | pat = re.compile(r'/txn/(?P<txn_id>.*)') |
|
72 | pat = re.compile(r'/txn/(?P<txn_id>.*)') | |
73 | for el in root: |
|
73 | for el in root: | |
74 | if el.tag == '{DAV:}source': |
|
74 | if el.tag == '{DAV:}source': | |
75 | for sub_el in el: |
|
75 | for sub_el in el: | |
76 | if sub_el.tag == '{DAV:}href': |
|
76 | if sub_el.tag == '{DAV:}href': | |
77 | match = pat.search(sub_el.text) |
|
77 | match = pat.search(sub_el.text) | |
78 | if match: |
|
78 | if match: | |
79 | svn_tx_id = match.groupdict()['txn_id'] |
|
79 | svn_tx_id = match.groupdict()['txn_id'] | |
80 | txn_id = rc_cache.utils.compute_key_from_params( |
|
80 | txn_id = rc_cache.utils.compute_key_from_params( | |
81 | acl_repo_name, svn_tx_id) |
|
81 | acl_repo_name, svn_tx_id) | |
82 | return txn_id |
|
82 | return txn_id | |
83 | except Exception: |
|
83 | except Exception: | |
84 | log.exception('Failed to extract txn_id') |
|
84 | log.exception('Failed to extract txn_id') | |
85 |
|
85 | |||
86 |
|
86 | |||
87 | def initialize_generator(factory): |
|
87 | def initialize_generator(factory): | |
88 | """ |
|
88 | """ | |
89 | Initializes the returned generator by draining its first element. |
|
89 | Initializes the returned generator by draining its first element. | |
90 |
|
90 | |||
91 | This can be used to give a generator an initializer, which is the code |
|
91 | This can be used to give a generator an initializer, which is the code | |
92 | up to the first yield statement. This decorator enforces that the first |
|
92 | up to the first yield statement. This decorator enforces that the first | |
93 | produced element has the value ``"__init__"`` to make its special |
|
93 | produced element has the value ``"__init__"`` to make its special | |
94 | purpose very explicit in the using code. |
|
94 | purpose very explicit in the using code. | |
95 | """ |
|
95 | """ | |
96 |
|
96 | |||
97 | @wraps(factory) |
|
97 | @wraps(factory) | |
98 | def wrapper(*args, **kwargs): |
|
98 | def wrapper(*args, **kwargs): | |
99 | gen = factory(*args, **kwargs) |
|
99 | gen = factory(*args, **kwargs) | |
100 | try: |
|
100 | try: | |
101 | init = gen.next() |
|
101 | init = gen.next() | |
102 | except StopIteration: |
|
102 | except StopIteration: | |
103 | raise ValueError('Generator must yield at least one element.') |
|
103 | raise ValueError('Generator must yield at least one element.') | |
104 | if init != "__init__": |
|
104 | if init != "__init__": | |
105 | raise ValueError('First yielded element must be "__init__".') |
|
105 | raise ValueError('First yielded element must be "__init__".') | |
106 | return gen |
|
106 | return gen | |
107 | return wrapper |
|
107 | return wrapper | |
108 |
|
108 | |||
109 |
|
109 | |||
110 | class SimpleVCS(object): |
|
110 | class SimpleVCS(object): | |
111 | """Common functionality for SCM HTTP handlers.""" |
|
111 | """Common functionality for SCM HTTP handlers.""" | |
112 |
|
112 | |||
113 | SCM = 'unknown' |
|
113 | SCM = 'unknown' | |
114 |
|
114 | |||
115 | acl_repo_name = None |
|
115 | acl_repo_name = None | |
116 | url_repo_name = None |
|
116 | url_repo_name = None | |
117 | vcs_repo_name = None |
|
117 | vcs_repo_name = None | |
118 | rc_extras = {} |
|
118 | rc_extras = {} | |
119 |
|
119 | |||
120 | # We have to handle requests to shadow repositories different than requests |
|
120 | # We have to handle requests to shadow repositories different than requests | |
121 | # to normal repositories. Therefore we have to distinguish them. To do this |
|
121 | # to normal repositories. Therefore we have to distinguish them. To do this | |
122 | # we use this regex which will match only on URLs pointing to shadow |
|
122 | # we use this regex which will match only on URLs pointing to shadow | |
123 | # repositories. |
|
123 | # repositories. | |
124 | shadow_repo_re = re.compile( |
|
124 | shadow_repo_re = re.compile( | |
125 | '(?P<groups>(?:{slug_pat}/)*)' # repo groups |
|
125 | '(?P<groups>(?:{slug_pat}/)*)' # repo groups | |
126 | '(?P<target>{slug_pat})/' # target repo |
|
126 | '(?P<target>{slug_pat})/' # target repo | |
127 | 'pull-request/(?P<pr_id>\d+)/' # pull request |
|
127 | 'pull-request/(?P<pr_id>\d+)/' # pull request | |
128 | 'repository$' # shadow repo |
|
128 | 'repository$' # shadow repo | |
129 | .format(slug_pat=SLUG_RE.pattern)) |
|
129 | .format(slug_pat=SLUG_RE.pattern)) | |
130 |
|
130 | |||
131 | def __init__(self, config, registry): |
|
131 | def __init__(self, config, registry): | |
132 | self.registry = registry |
|
132 | self.registry = registry | |
133 | self.config = config |
|
133 | self.config = config | |
134 | # re-populated by specialized middleware |
|
134 | # re-populated by specialized middleware | |
135 | self.repo_vcs_config = base.Config() |
|
135 | self.repo_vcs_config = base.Config() | |
136 |
|
136 | |||
137 | rc_settings = SettingsModel().get_all_settings(cache=True, from_request=False) |
|
137 | rc_settings = SettingsModel().get_all_settings(cache=True, from_request=False) | |
138 | realm = rc_settings.get('rhodecode_realm') or 'RhodeCode AUTH' |
|
138 | realm = rc_settings.get('rhodecode_realm') or 'RhodeCode AUTH' | |
139 |
|
139 | |||
140 | # authenticate this VCS request using authfunc |
|
140 | # authenticate this VCS request using authfunc | |
141 | auth_ret_code_detection = \ |
|
141 | auth_ret_code_detection = \ | |
142 | str2bool(self.config.get('auth_ret_code_detection', False)) |
|
142 | str2bool(self.config.get('auth_ret_code_detection', False)) | |
143 | self.authenticate = BasicAuth( |
|
143 | self.authenticate = BasicAuth( | |
144 | '', authenticate, registry, config.get('auth_ret_code'), |
|
144 | '', authenticate, registry, config.get('auth_ret_code'), | |
145 | auth_ret_code_detection, rc_realm=realm) |
|
145 | auth_ret_code_detection, rc_realm=realm) | |
146 | self.ip_addr = '0.0.0.0' |
|
146 | self.ip_addr = '0.0.0.0' | |
147 |
|
147 | |||
148 | @LazyProperty |
|
148 | @LazyProperty | |
149 | def global_vcs_config(self): |
|
149 | def global_vcs_config(self): | |
150 | try: |
|
150 | try: | |
151 | return VcsSettingsModel().get_ui_settings_as_config_obj() |
|
151 | return VcsSettingsModel().get_ui_settings_as_config_obj() | |
152 | except Exception: |
|
152 | except Exception: | |
153 | return base.Config() |
|
153 | return base.Config() | |
154 |
|
154 | |||
155 | @property |
|
155 | @property | |
156 | def base_path(self): |
|
156 | def base_path(self): | |
157 | settings_path = self.repo_vcs_config.get(*VcsSettingsModel.PATH_SETTING) |
|
157 | settings_path = self.repo_vcs_config.get(*VcsSettingsModel.PATH_SETTING) | |
158 |
|
158 | |||
159 | if not settings_path: |
|
159 | if not settings_path: | |
160 | settings_path = self.global_vcs_config.get(*VcsSettingsModel.PATH_SETTING) |
|
160 | settings_path = self.global_vcs_config.get(*VcsSettingsModel.PATH_SETTING) | |
161 |
|
161 | |||
162 | if not settings_path: |
|
162 | if not settings_path: | |
163 | # try, maybe we passed in explicitly as config option |
|
163 | # try, maybe we passed in explicitly as config option | |
164 | settings_path = self.config.get('base_path') |
|
164 | settings_path = self.config.get('base_path') | |
165 |
|
165 | |||
166 | if not settings_path: |
|
166 | if not settings_path: | |
167 | raise ValueError('FATAL: base_path is empty') |
|
167 | raise ValueError('FATAL: base_path is empty') | |
168 | return settings_path |
|
168 | return settings_path | |
169 |
|
169 | |||
170 | def set_repo_names(self, environ): |
|
170 | def set_repo_names(self, environ): | |
171 | """ |
|
171 | """ | |
172 | This will populate the attributes acl_repo_name, url_repo_name, |
|
172 | This will populate the attributes acl_repo_name, url_repo_name, | |
173 | vcs_repo_name and is_shadow_repo. In case of requests to normal (non |
|
173 | vcs_repo_name and is_shadow_repo. In case of requests to normal (non | |
174 | shadow) repositories all names are equal. In case of requests to a |
|
174 | shadow) repositories all names are equal. In case of requests to a | |
175 | shadow repository the acl-name points to the target repo of the pull |
|
175 | shadow repository the acl-name points to the target repo of the pull | |
176 | request and the vcs-name points to the shadow repo file system path. |
|
176 | request and the vcs-name points to the shadow repo file system path. | |
177 | The url-name is always the URL used by the vcs client program. |
|
177 | The url-name is always the URL used by the vcs client program. | |
178 |
|
178 | |||
179 | Example in case of a shadow repo: |
|
179 | Example in case of a shadow repo: | |
180 | acl_repo_name = RepoGroup/MyRepo |
|
180 | acl_repo_name = RepoGroup/MyRepo | |
181 | url_repo_name = RepoGroup/MyRepo/pull-request/3/repository |
|
181 | url_repo_name = RepoGroup/MyRepo/pull-request/3/repository | |
182 | vcs_repo_name = /repo/base/path/RepoGroup/.__shadow_MyRepo_pr-3' |
|
182 | vcs_repo_name = /repo/base/path/RepoGroup/.__shadow_MyRepo_pr-3' | |
183 | """ |
|
183 | """ | |
184 | # First we set the repo name from URL for all attributes. This is the |
|
184 | # First we set the repo name from URL for all attributes. This is the | |
185 | # default if handling normal (non shadow) repo requests. |
|
185 | # default if handling normal (non shadow) repo requests. | |
186 | self.url_repo_name = self._get_repository_name(environ) |
|
186 | self.url_repo_name = self._get_repository_name(environ) | |
187 | self.acl_repo_name = self.vcs_repo_name = self.url_repo_name |
|
187 | self.acl_repo_name = self.vcs_repo_name = self.url_repo_name | |
188 | self.is_shadow_repo = False |
|
188 | self.is_shadow_repo = False | |
189 |
|
189 | |||
190 | # Check if this is a request to a shadow repository. |
|
190 | # Check if this is a request to a shadow repository. | |
191 | match = self.shadow_repo_re.match(self.url_repo_name) |
|
191 | match = self.shadow_repo_re.match(self.url_repo_name) | |
192 | if match: |
|
192 | if match: | |
193 | match_dict = match.groupdict() |
|
193 | match_dict = match.groupdict() | |
194 |
|
194 | |||
195 | # Build acl repo name from regex match. |
|
195 | # Build acl repo name from regex match. | |
196 | acl_repo_name = safe_unicode('{groups}{target}'.format( |
|
196 | acl_repo_name = safe_unicode('{groups}{target}'.format( | |
197 | groups=match_dict['groups'] or '', |
|
197 | groups=match_dict['groups'] or '', | |
198 | target=match_dict['target'])) |
|
198 | target=match_dict['target'])) | |
199 |
|
199 | |||
200 | # Retrieve pull request instance by ID from regex match. |
|
200 | # Retrieve pull request instance by ID from regex match. | |
201 | pull_request = PullRequest.get(match_dict['pr_id']) |
|
201 | pull_request = PullRequest.get(match_dict['pr_id']) | |
202 |
|
202 | |||
203 | # Only proceed if we got a pull request and if acl repo name from |
|
203 | # Only proceed if we got a pull request and if acl repo name from | |
204 | # URL equals the target repo name of the pull request. |
|
204 | # URL equals the target repo name of the pull request. | |
205 | if pull_request and (acl_repo_name == pull_request.target_repo.repo_name): |
|
205 | if pull_request and (acl_repo_name == pull_request.target_repo.repo_name): | |
206 |
|
206 | |||
207 | # Get file system path to shadow repository. |
|
207 | # Get file system path to shadow repository. | |
208 | workspace_id = PullRequestModel()._workspace_id(pull_request) |
|
208 | workspace_id = PullRequestModel()._workspace_id(pull_request) | |
209 | vcs_repo_name = pull_request.target_repo.get_shadow_repository_path(workspace_id) |
|
209 | vcs_repo_name = pull_request.target_repo.get_shadow_repository_path(workspace_id) | |
210 |
|
210 | |||
211 | # Store names for later usage. |
|
211 | # Store names for later usage. | |
212 | self.vcs_repo_name = vcs_repo_name |
|
212 | self.vcs_repo_name = vcs_repo_name | |
213 | self.acl_repo_name = acl_repo_name |
|
213 | self.acl_repo_name = acl_repo_name | |
214 | self.is_shadow_repo = True |
|
214 | self.is_shadow_repo = True | |
215 |
|
215 | |||
216 | log.debug('Setting all VCS repository names: %s', { |
|
216 | log.debug('Setting all VCS repository names: %s', { | |
217 | 'acl_repo_name': self.acl_repo_name, |
|
217 | 'acl_repo_name': self.acl_repo_name, | |
218 | 'url_repo_name': self.url_repo_name, |
|
218 | 'url_repo_name': self.url_repo_name, | |
219 | 'vcs_repo_name': self.vcs_repo_name, |
|
219 | 'vcs_repo_name': self.vcs_repo_name, | |
220 | }) |
|
220 | }) | |
221 |
|
221 | |||
222 | @property |
|
222 | @property | |
223 | def scm_app(self): |
|
223 | def scm_app(self): | |
224 | custom_implementation = self.config['vcs.scm_app_implementation'] |
|
224 | custom_implementation = self.config['vcs.scm_app_implementation'] | |
225 | if custom_implementation == 'http': |
|
225 | if custom_implementation == 'http': | |
226 | log.debug('Using HTTP implementation of scm app.') |
|
226 | log.debug('Using HTTP implementation of scm app.') | |
227 | scm_app_impl = scm_app_http |
|
227 | scm_app_impl = scm_app_http | |
228 | else: |
|
228 | else: | |
229 | log.debug('Using custom implementation of scm_app: "{}"'.format( |
|
229 | log.debug('Using custom implementation of scm_app: "{}"'.format( | |
230 | custom_implementation)) |
|
230 | custom_implementation)) | |
231 | scm_app_impl = importlib.import_module(custom_implementation) |
|
231 | scm_app_impl = importlib.import_module(custom_implementation) | |
232 | return scm_app_impl |
|
232 | return scm_app_impl | |
233 |
|
233 | |||
234 | def _get_by_id(self, repo_name): |
|
234 | def _get_by_id(self, repo_name): | |
235 | """ |
|
235 | """ | |
236 | Gets a special pattern _<ID> from clone url and tries to replace it |
|
236 | Gets a special pattern _<ID> from clone url and tries to replace it | |
237 | with a repository_name for support of _<ID> non changeable urls |
|
237 | with a repository_name for support of _<ID> non changeable urls | |
238 | """ |
|
238 | """ | |
239 |
|
239 | |||
240 | data = repo_name.split('/') |
|
240 | data = repo_name.split('/') | |
241 | if len(data) >= 2: |
|
241 | if len(data) >= 2: | |
242 | from rhodecode.model.repo import RepoModel |
|
242 | from rhodecode.model.repo import RepoModel | |
243 | by_id_match = RepoModel().get_repo_by_id(repo_name) |
|
243 | by_id_match = RepoModel().get_repo_by_id(repo_name) | |
244 | if by_id_match: |
|
244 | if by_id_match: | |
245 | data[1] = by_id_match.repo_name |
|
245 | data[1] = by_id_match.repo_name | |
246 |
|
246 | |||
247 | return safe_str('/'.join(data)) |
|
247 | return safe_str('/'.join(data)) | |
248 |
|
248 | |||
249 | def _invalidate_cache(self, repo_name): |
|
249 | def _invalidate_cache(self, repo_name): | |
250 | """ |
|
250 | """ | |
251 | Set's cache for this repository for invalidation on next access |
|
251 | Set's cache for this repository for invalidation on next access | |
252 |
|
252 | |||
253 | :param repo_name: full repo name, also a cache key |
|
253 | :param repo_name: full repo name, also a cache key | |
254 | """ |
|
254 | """ | |
255 | ScmModel().mark_for_invalidation(repo_name) |
|
255 | ScmModel().mark_for_invalidation(repo_name) | |
256 |
|
256 | |||
257 | def is_valid_and_existing_repo(self, repo_name, base_path, scm_type): |
|
257 | def is_valid_and_existing_repo(self, repo_name, base_path, scm_type): | |
258 | db_repo = Repository.get_by_repo_name(repo_name) |
|
258 | db_repo = Repository.get_by_repo_name(repo_name) | |
259 | if not db_repo: |
|
259 | if not db_repo: | |
260 | log.debug('Repository `%s` not found inside the database.', |
|
260 | log.debug('Repository `%s` not found inside the database.', | |
261 | repo_name) |
|
261 | repo_name) | |
262 | return False |
|
262 | return False | |
263 |
|
263 | |||
264 | if db_repo.repo_type != scm_type: |
|
264 | if db_repo.repo_type != scm_type: | |
265 | log.warning( |
|
265 | log.warning( | |
266 | 'Repository `%s` have incorrect scm_type, expected %s got %s', |
|
266 | 'Repository `%s` have incorrect scm_type, expected %s got %s', | |
267 | repo_name, db_repo.repo_type, scm_type) |
|
267 | repo_name, db_repo.repo_type, scm_type) | |
268 | return False |
|
268 | return False | |
269 |
|
269 | |||
270 | config = db_repo._config |
|
270 | config = db_repo._config | |
271 | config.set('extensions', 'largefiles', '') |
|
271 | config.set('extensions', 'largefiles', '') | |
272 | return is_valid_repo( |
|
272 | return is_valid_repo( | |
273 | repo_name, base_path, |
|
273 | repo_name, base_path, | |
274 | explicit_scm=scm_type, expect_scm=scm_type, config=config) |
|
274 | explicit_scm=scm_type, expect_scm=scm_type, config=config) | |
275 |
|
275 | |||
276 | def valid_and_active_user(self, user): |
|
276 | def valid_and_active_user(self, user): | |
277 | """ |
|
277 | """ | |
278 | Checks if that user is not empty, and if it's actually object it checks |
|
278 | Checks if that user is not empty, and if it's actually object it checks | |
279 | if he's active. |
|
279 | if he's active. | |
280 |
|
280 | |||
281 | :param user: user object or None |
|
281 | :param user: user object or None | |
282 | :return: boolean |
|
282 | :return: boolean | |
283 | """ |
|
283 | """ | |
284 | if user is None: |
|
284 | if user is None: | |
285 | return False |
|
285 | return False | |
286 |
|
286 | |||
287 | elif user.active: |
|
287 | elif user.active: | |
288 | return True |
|
288 | return True | |
289 |
|
289 | |||
290 | return False |
|
290 | return False | |
291 |
|
291 | |||
292 | @property |
|
292 | @property | |
293 | def is_shadow_repo_dir(self): |
|
293 | def is_shadow_repo_dir(self): | |
294 | return os.path.isdir(self.vcs_repo_name) |
|
294 | return os.path.isdir(self.vcs_repo_name) | |
295 |
|
295 | |||
296 | def _check_permission(self, action, user, auth_user, repo_name, ip_addr=None, |
|
296 | def _check_permission(self, action, user, auth_user, repo_name, ip_addr=None, | |
297 | plugin_id='', plugin_cache_active=False, cache_ttl=0): |
|
297 | plugin_id='', plugin_cache_active=False, cache_ttl=0): | |
298 | """ |
|
298 | """ | |
299 | Checks permissions using action (push/pull) user and repository |
|
299 | Checks permissions using action (push/pull) user and repository | |
300 | name. If plugin_cache and ttl is set it will use the plugin which |
|
300 | name. If plugin_cache and ttl is set it will use the plugin which | |
301 | authenticated the user to store the cached permissions result for N |
|
301 | authenticated the user to store the cached permissions result for N | |
302 | amount of seconds as in cache_ttl |
|
302 | amount of seconds as in cache_ttl | |
303 |
|
303 | |||
304 | :param action: push or pull action |
|
304 | :param action: push or pull action | |
305 | :param user: user instance |
|
305 | :param user: user instance | |
306 | :param repo_name: repository name |
|
306 | :param repo_name: repository name | |
307 | """ |
|
307 | """ | |
308 |
|
308 | |||
309 | log.debug('AUTH_CACHE_TTL for permissions `%s` active: %s (TTL: %s)', |
|
309 | log.debug('AUTH_CACHE_TTL for permissions `%s` active: %s (TTL: %s)', | |
310 | plugin_id, plugin_cache_active, cache_ttl) |
|
310 | plugin_id, plugin_cache_active, cache_ttl) | |
311 |
|
311 | |||
312 | user_id = user.user_id |
|
312 | user_id = user.user_id | |
313 | cache_namespace_uid = 'cache_user_auth.{}'.format(user_id) |
|
313 | cache_namespace_uid = 'cache_user_auth.{}'.format(user_id) | |
314 | region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid) |
|
314 | region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid) | |
315 |
|
315 | |||
316 | @region.conditional_cache_on_arguments(namespace=cache_namespace_uid, |
|
316 | @region.conditional_cache_on_arguments(namespace=cache_namespace_uid, | |
317 | expiration_time=cache_ttl, |
|
317 | expiration_time=cache_ttl, | |
318 | condition=plugin_cache_active) |
|
318 | condition=plugin_cache_active) | |
319 | def compute_perm_vcs( |
|
319 | def compute_perm_vcs( | |
320 | cache_name, plugin_id, action, user_id, repo_name, ip_addr): |
|
320 | cache_name, plugin_id, action, user_id, repo_name, ip_addr): | |
321 |
|
321 | |||
322 | log.debug('auth: calculating permission access now...') |
|
322 | log.debug('auth: calculating permission access now...') | |
323 | # check IP |
|
323 | # check IP | |
324 | inherit = user.inherit_default_permissions |
|
324 | inherit = user.inherit_default_permissions | |
325 | ip_allowed = AuthUser.check_ip_allowed( |
|
325 | ip_allowed = AuthUser.check_ip_allowed( | |
326 | user_id, ip_addr, inherit_from_default=inherit) |
|
326 | user_id, ip_addr, inherit_from_default=inherit) | |
327 | if ip_allowed: |
|
327 | if ip_allowed: | |
328 | log.info('Access for IP:%s allowed', ip_addr) |
|
328 | log.info('Access for IP:%s allowed', ip_addr) | |
329 | else: |
|
329 | else: | |
330 | return False |
|
330 | return False | |
331 |
|
331 | |||
332 | if action == 'push': |
|
332 | if action == 'push': | |
333 | perms = ('repository.write', 'repository.admin') |
|
333 | perms = ('repository.write', 'repository.admin') | |
334 | if not HasPermissionAnyMiddleware(*perms)(auth_user, repo_name): |
|
334 | if not HasPermissionAnyMiddleware(*perms)(auth_user, repo_name): | |
335 | return False |
|
335 | return False | |
336 |
|
336 | |||
337 | else: |
|
337 | else: | |
338 | # any other action need at least read permission |
|
338 | # any other action need at least read permission | |
339 | perms = ( |
|
339 | perms = ( | |
340 | 'repository.read', 'repository.write', 'repository.admin') |
|
340 | 'repository.read', 'repository.write', 'repository.admin') | |
341 | if not HasPermissionAnyMiddleware(*perms)(auth_user, repo_name): |
|
341 | if not HasPermissionAnyMiddleware(*perms)(auth_user, repo_name): | |
342 | return False |
|
342 | return False | |
343 |
|
343 | |||
344 | return True |
|
344 | return True | |
345 |
|
345 | |||
346 | start = time.time() |
|
346 | start = time.time() | |
347 | log.debug('Running plugin `%s` permissions check', plugin_id) |
|
347 | log.debug('Running plugin `%s` permissions check', plugin_id) | |
348 |
|
348 | |||
349 | # for environ based auth, password can be empty, but then the validation is |
|
349 | # for environ based auth, password can be empty, but then the validation is | |
350 | # on the server that fills in the env data needed for authentication |
|
350 | # on the server that fills in the env data needed for authentication | |
351 | perm_result = compute_perm_vcs( |
|
351 | perm_result = compute_perm_vcs( | |
352 | 'vcs_permissions', plugin_id, action, user.user_id, repo_name, ip_addr) |
|
352 | 'vcs_permissions', plugin_id, action, user.user_id, repo_name, ip_addr) | |
353 |
|
353 | |||
354 | auth_time = time.time() - start |
|
354 | auth_time = time.time() - start | |
355 | log.debug('Permissions for plugin `%s` completed in %.4fs, ' |
|
355 | log.debug('Permissions for plugin `%s` completed in %.4fs, ' | |
356 | 'expiration time of fetched cache %.1fs.', |
|
356 | 'expiration time of fetched cache %.1fs.', | |
357 | plugin_id, auth_time, cache_ttl) |
|
357 | plugin_id, auth_time, cache_ttl) | |
358 |
|
358 | |||
359 | return perm_result |
|
359 | return perm_result | |
360 |
|
360 | |||
361 | def _get_http_scheme(self, environ): |
|
361 | def _get_http_scheme(self, environ): | |
362 | try: |
|
362 | try: | |
363 | return environ['wsgi.url_scheme'] |
|
363 | return environ['wsgi.url_scheme'] | |
364 | except Exception: |
|
364 | except Exception: | |
365 | log.exception('Failed to read http scheme') |
|
365 | log.exception('Failed to read http scheme') | |
366 | return 'http' |
|
366 | return 'http' | |
367 |
|
367 | |||
368 | def _check_ssl(self, environ, start_response): |
|
368 | def _check_ssl(self, environ, start_response): | |
369 | """ |
|
369 | """ | |
370 | Checks the SSL check flag and returns False if SSL is not present |
|
370 | Checks the SSL check flag and returns False if SSL is not present | |
371 | and required True otherwise |
|
371 | and required True otherwise | |
372 | """ |
|
372 | """ | |
373 | org_proto = environ['wsgi._org_proto'] |
|
373 | org_proto = environ['wsgi._org_proto'] | |
374 | # check if we have SSL required ! if not it's a bad request ! |
|
374 | # check if we have SSL required ! if not it's a bad request ! | |
375 | require_ssl = str2bool(self.repo_vcs_config.get('web', 'push_ssl')) |
|
375 | require_ssl = str2bool(self.repo_vcs_config.get('web', 'push_ssl')) | |
376 | if require_ssl and org_proto == 'http': |
|
376 | if require_ssl and org_proto == 'http': | |
377 | log.debug( |
|
377 | log.debug( | |
378 | 'Bad request: detected protocol is `%s` and ' |
|
378 | 'Bad request: detected protocol is `%s` and ' | |
379 | 'SSL/HTTPS is required.', org_proto) |
|
379 | 'SSL/HTTPS is required.', org_proto) | |
380 | return False |
|
380 | return False | |
381 | return True |
|
381 | return True | |
382 |
|
382 | |||
383 | def _get_default_cache_ttl(self): |
|
383 | def _get_default_cache_ttl(self): | |
384 | # take AUTH_CACHE_TTL from the `rhodecode` auth plugin |
|
384 | # take AUTH_CACHE_TTL from the `rhodecode` auth plugin | |
385 | plugin = loadplugin('egg:rhodecode-enterprise-ce#rhodecode') |
|
385 | plugin = loadplugin('egg:rhodecode-enterprise-ce#rhodecode') | |
386 | plugin_settings = plugin.get_settings() |
|
386 | plugin_settings = plugin.get_settings() | |
387 | plugin_cache_active, cache_ttl = plugin.get_ttl_cache( |
|
387 | plugin_cache_active, cache_ttl = plugin.get_ttl_cache( | |
388 | plugin_settings) or (False, 0) |
|
388 | plugin_settings) or (False, 0) | |
389 | return plugin_cache_active, cache_ttl |
|
389 | return plugin_cache_active, cache_ttl | |
390 |
|
390 | |||
391 | def __call__(self, environ, start_response): |
|
391 | def __call__(self, environ, start_response): | |
392 | try: |
|
392 | try: | |
393 | return self._handle_request(environ, start_response) |
|
393 | return self._handle_request(environ, start_response) | |
394 | except Exception: |
|
394 | except Exception: | |
395 | log.exception("Exception while handling request") |
|
395 | log.exception("Exception while handling request") | |
396 | appenlight.track_exception(environ) |
|
396 | appenlight.track_exception(environ) | |
397 | return HTTPInternalServerError()(environ, start_response) |
|
397 | return HTTPInternalServerError()(environ, start_response) | |
398 | finally: |
|
398 | finally: | |
399 | meta.Session.remove() |
|
399 | meta.Session.remove() | |
400 |
|
400 | |||
401 | def _handle_request(self, environ, start_response): |
|
401 | def _handle_request(self, environ, start_response): | |
402 | if not self._check_ssl(environ, start_response): |
|
402 | if not self._check_ssl(environ, start_response): | |
403 | reason = ('SSL required, while RhodeCode was unable ' |
|
403 | reason = ('SSL required, while RhodeCode was unable ' | |
404 | 'to detect this as SSL request') |
|
404 | 'to detect this as SSL request') | |
405 | log.debug('User not allowed to proceed, %s', reason) |
|
405 | log.debug('User not allowed to proceed, %s', reason) | |
406 | return HTTPNotAcceptable(reason)(environ, start_response) |
|
406 | return HTTPNotAcceptable(reason)(environ, start_response) | |
407 |
|
407 | |||
408 | if not self.url_repo_name: |
|
408 | if not self.url_repo_name: | |
409 | log.warning('Repository name is empty: %s', self.url_repo_name) |
|
409 | log.warning('Repository name is empty: %s', self.url_repo_name) | |
410 | # failed to get repo name, we fail now |
|
410 | # failed to get repo name, we fail now | |
411 | return HTTPNotFound()(environ, start_response) |
|
411 | return HTTPNotFound()(environ, start_response) | |
412 | log.debug('Extracted repo name is %s', self.url_repo_name) |
|
412 | log.debug('Extracted repo name is %s', self.url_repo_name) | |
413 |
|
413 | |||
414 | ip_addr = get_ip_addr(environ) |
|
414 | ip_addr = get_ip_addr(environ) | |
415 | user_agent = get_user_agent(environ) |
|
415 | user_agent = get_user_agent(environ) | |
416 | username = None |
|
416 | username = None | |
417 |
|
417 | |||
418 | # skip passing error to error controller |
|
418 | # skip passing error to error controller | |
419 | environ['pylons.status_code_redirect'] = True |
|
419 | environ['pylons.status_code_redirect'] = True | |
420 |
|
420 | |||
421 | # ====================================================================== |
|
421 | # ====================================================================== | |
422 | # GET ACTION PULL or PUSH |
|
422 | # GET ACTION PULL or PUSH | |
423 | # ====================================================================== |
|
423 | # ====================================================================== | |
424 | action = self._get_action(environ) |
|
424 | action = self._get_action(environ) | |
425 |
|
425 | |||
426 | # ====================================================================== |
|
426 | # ====================================================================== | |
427 | # Check if this is a request to a shadow repository of a pull request. |
|
427 | # Check if this is a request to a shadow repository of a pull request. | |
428 | # In this case only pull action is allowed. |
|
428 | # In this case only pull action is allowed. | |
429 | # ====================================================================== |
|
429 | # ====================================================================== | |
430 | if self.is_shadow_repo and action != 'pull': |
|
430 | if self.is_shadow_repo and action != 'pull': | |
431 | reason = 'Only pull action is allowed for shadow repositories.' |
|
431 | reason = 'Only pull action is allowed for shadow repositories.' | |
432 | log.debug('User not allowed to proceed, %s', reason) |
|
432 | log.debug('User not allowed to proceed, %s', reason) | |
433 | return HTTPNotAcceptable(reason)(environ, start_response) |
|
433 | return HTTPNotAcceptable(reason)(environ, start_response) | |
434 |
|
434 | |||
435 | # Check if the shadow repo actually exists, in case someone refers |
|
435 | # Check if the shadow repo actually exists, in case someone refers | |
436 | # to it, and it has been deleted because of successful merge. |
|
436 | # to it, and it has been deleted because of successful merge. | |
437 | if self.is_shadow_repo and not self.is_shadow_repo_dir: |
|
437 | if self.is_shadow_repo and not self.is_shadow_repo_dir: | |
438 | log.debug( |
|
438 | log.debug( | |
439 | 'Shadow repo detected, and shadow repo dir `%s` is missing', |
|
439 | 'Shadow repo detected, and shadow repo dir `%s` is missing', | |
440 | self.is_shadow_repo_dir) |
|
440 | self.is_shadow_repo_dir) | |
441 | return HTTPNotFound()(environ, start_response) |
|
441 | return HTTPNotFound()(environ, start_response) | |
442 |
|
442 | |||
443 | # ====================================================================== |
|
443 | # ====================================================================== | |
444 | # CHECK ANONYMOUS PERMISSION |
|
444 | # CHECK ANONYMOUS PERMISSION | |
445 | # ====================================================================== |
|
445 | # ====================================================================== | |
446 | detect_force_push = False |
|
446 | detect_force_push = False | |
447 | check_branch_perms = False |
|
447 | check_branch_perms = False | |
448 | if action in ['pull', 'push']: |
|
448 | if action in ['pull', 'push']: | |
449 | user_obj = anonymous_user = User.get_default_user() |
|
449 | user_obj = anonymous_user = User.get_default_user() | |
450 | auth_user = user_obj.AuthUser() |
|
450 | auth_user = user_obj.AuthUser() | |
451 | username = anonymous_user.username |
|
451 | username = anonymous_user.username | |
452 | if anonymous_user.active: |
|
452 | if anonymous_user.active: | |
453 | plugin_cache_active, cache_ttl = self._get_default_cache_ttl() |
|
453 | plugin_cache_active, cache_ttl = self._get_default_cache_ttl() | |
454 | # ONLY check permissions if the user is activated |
|
454 | # ONLY check permissions if the user is activated | |
455 | anonymous_perm = self._check_permission( |
|
455 | anonymous_perm = self._check_permission( | |
456 | action, anonymous_user, auth_user, self.acl_repo_name, ip_addr, |
|
456 | action, anonymous_user, auth_user, self.acl_repo_name, ip_addr, | |
457 | plugin_id='anonymous_access', |
|
457 | plugin_id='anonymous_access', | |
458 | plugin_cache_active=plugin_cache_active, |
|
458 | plugin_cache_active=plugin_cache_active, | |
459 | cache_ttl=cache_ttl, |
|
459 | cache_ttl=cache_ttl, | |
460 | ) |
|
460 | ) | |
461 | else: |
|
461 | else: | |
462 | anonymous_perm = False |
|
462 | anonymous_perm = False | |
463 |
|
463 | |||
464 | if not anonymous_user.active or not anonymous_perm: |
|
464 | if not anonymous_user.active or not anonymous_perm: | |
465 | if not anonymous_user.active: |
|
465 | if not anonymous_user.active: | |
466 | log.debug('Anonymous access is disabled, running ' |
|
466 | log.debug('Anonymous access is disabled, running ' | |
467 | 'authentication') |
|
467 | 'authentication') | |
468 |
|
468 | |||
469 | if not anonymous_perm: |
|
469 | if not anonymous_perm: | |
470 | log.debug('Not enough credentials to access this ' |
|
470 | log.debug('Not enough credentials to access this ' | |
471 | 'repository as anonymous user') |
|
471 | 'repository as anonymous user') | |
472 |
|
472 | |||
473 | username = None |
|
473 | username = None | |
474 | # ============================================================== |
|
474 | # ============================================================== | |
475 | # DEFAULT PERM FAILED OR ANONYMOUS ACCESS IS DISABLED SO WE |
|
475 | # DEFAULT PERM FAILED OR ANONYMOUS ACCESS IS DISABLED SO WE | |
476 | # NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS |
|
476 | # NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS | |
477 | # ============================================================== |
|
477 | # ============================================================== | |
478 |
|
478 | |||
479 | # try to auth based on environ, container auth methods |
|
479 | # try to auth based on environ, container auth methods | |
480 | log.debug('Running PRE-AUTH for container based authentication') |
|
480 | log.debug('Running PRE-AUTH for container based authentication') | |
481 | pre_auth = authenticate( |
|
481 | pre_auth = authenticate( | |
482 | '', '', environ, VCS_TYPE, registry=self.registry, |
|
482 | '', '', environ, VCS_TYPE, registry=self.registry, | |
483 | acl_repo_name=self.acl_repo_name) |
|
483 | acl_repo_name=self.acl_repo_name) | |
484 | if pre_auth and pre_auth.get('username'): |
|
484 | if pre_auth and pre_auth.get('username'): | |
485 | username = pre_auth['username'] |
|
485 | username = pre_auth['username'] | |
486 | log.debug('PRE-AUTH got %s as username', username) |
|
486 | log.debug('PRE-AUTH got %s as username', username) | |
487 | if pre_auth: |
|
487 | if pre_auth: | |
488 | log.debug('PRE-AUTH successful from %s', |
|
488 | log.debug('PRE-AUTH successful from %s', | |
489 | pre_auth.get('auth_data', {}).get('_plugin')) |
|
489 | pre_auth.get('auth_data', {}).get('_plugin')) | |
490 |
|
490 | |||
491 | # If not authenticated by the container, running basic auth |
|
491 | # If not authenticated by the container, running basic auth | |
492 | # before inject the calling repo_name for special scope checks |
|
492 | # before inject the calling repo_name for special scope checks | |
493 | self.authenticate.acl_repo_name = self.acl_repo_name |
|
493 | self.authenticate.acl_repo_name = self.acl_repo_name | |
494 |
|
494 | |||
495 | plugin_cache_active, cache_ttl = False, 0 |
|
495 | plugin_cache_active, cache_ttl = False, 0 | |
496 | plugin = None |
|
496 | plugin = None | |
497 | if not username: |
|
497 | if not username: | |
498 | self.authenticate.realm = self.authenticate.get_rc_realm() |
|
498 | self.authenticate.realm = self.authenticate.get_rc_realm() | |
499 |
|
499 | |||
500 | try: |
|
500 | try: | |
501 | auth_result = self.authenticate(environ) |
|
501 | auth_result = self.authenticate(environ) | |
502 | except (UserCreationError, NotAllowedToCreateUserError) as e: |
|
502 | except (UserCreationError, NotAllowedToCreateUserError) as e: | |
503 | log.error(e) |
|
503 | log.error(e) | |
504 | reason = safe_str(e) |
|
504 | reason = safe_str(e) | |
505 | return HTTPNotAcceptable(reason)(environ, start_response) |
|
505 | return HTTPNotAcceptable(reason)(environ, start_response) | |
506 |
|
506 | |||
507 | if isinstance(auth_result, dict): |
|
507 | if isinstance(auth_result, dict): | |
508 | AUTH_TYPE.update(environ, 'basic') |
|
508 | AUTH_TYPE.update(environ, 'basic') | |
509 | REMOTE_USER.update(environ, auth_result['username']) |
|
509 | REMOTE_USER.update(environ, auth_result['username']) | |
510 | username = auth_result['username'] |
|
510 | username = auth_result['username'] | |
511 | plugin = auth_result.get('auth_data', {}).get('_plugin') |
|
511 | plugin = auth_result.get('auth_data', {}).get('_plugin') | |
512 | log.info( |
|
512 | log.info( | |
513 | 'MAIN-AUTH successful for user `%s` from %s plugin', |
|
513 | 'MAIN-AUTH successful for user `%s` from %s plugin', | |
514 | username, plugin) |
|
514 | username, plugin) | |
515 |
|
515 | |||
516 | plugin_cache_active, cache_ttl = auth_result.get( |
|
516 | plugin_cache_active, cache_ttl = auth_result.get( | |
517 | 'auth_data', {}).get('_ttl_cache') or (False, 0) |
|
517 | 'auth_data', {}).get('_ttl_cache') or (False, 0) | |
518 | else: |
|
518 | else: | |
519 | return auth_result.wsgi_application(environ, start_response) |
|
519 | return auth_result.wsgi_application(environ, start_response) | |
520 |
|
520 | |||
521 | # ============================================================== |
|
521 | # ============================================================== | |
522 | # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME |
|
522 | # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME | |
523 | # ============================================================== |
|
523 | # ============================================================== | |
524 | user = User.get_by_username(username) |
|
524 | user = User.get_by_username(username) | |
525 | if not self.valid_and_active_user(user): |
|
525 | if not self.valid_and_active_user(user): | |
526 | return HTTPForbidden()(environ, start_response) |
|
526 | return HTTPForbidden()(environ, start_response) | |
527 | username = user.username |
|
527 | username = user.username | |
528 | user_id = user.user_id |
|
528 | user_id = user.user_id | |
529 |
|
529 | |||
530 | # check user attributes for password change flag |
|
530 | # check user attributes for password change flag | |
531 | user_obj = user |
|
531 | user_obj = user | |
532 | auth_user = user_obj.AuthUser() |
|
532 | auth_user = user_obj.AuthUser() | |
533 | if user_obj and user_obj.username != User.DEFAULT_USER and \ |
|
533 | if user_obj and user_obj.username != User.DEFAULT_USER and \ | |
534 | user_obj.user_data.get('force_password_change'): |
|
534 | user_obj.user_data.get('force_password_change'): | |
535 | reason = 'password change required' |
|
535 | reason = 'password change required' | |
536 | log.debug('User not allowed to authenticate, %s', reason) |
|
536 | log.debug('User not allowed to authenticate, %s', reason) | |
537 | return HTTPNotAcceptable(reason)(environ, start_response) |
|
537 | return HTTPNotAcceptable(reason)(environ, start_response) | |
538 |
|
538 | |||
539 | # check permissions for this repository |
|
539 | # check permissions for this repository | |
540 | perm = self._check_permission( |
|
540 | perm = self._check_permission( | |
541 | action, user, auth_user, self.acl_repo_name, ip_addr, |
|
541 | action, user, auth_user, self.acl_repo_name, ip_addr, | |
542 | plugin, plugin_cache_active, cache_ttl) |
|
542 | plugin, plugin_cache_active, cache_ttl) | |
543 | if not perm: |
|
543 | if not perm: | |
544 | return HTTPForbidden()(environ, start_response) |
|
544 | return HTTPForbidden()(environ, start_response) | |
545 | environ['rc_auth_user_id'] = user_id |
|
545 | environ['rc_auth_user_id'] = user_id | |
546 |
|
546 | |||
547 | if action == 'push': |
|
547 | if action == 'push': | |
548 | perms = auth_user.get_branch_permissions(self.acl_repo_name) |
|
548 | perms = auth_user.get_branch_permissions(self.acl_repo_name) | |
549 | if perms: |
|
549 | if perms: | |
550 | check_branch_perms = True |
|
550 | check_branch_perms = True | |
551 | detect_force_push = True |
|
551 | detect_force_push = True | |
552 |
|
552 | |||
553 | # extras are injected into UI object and later available |
|
553 | # extras are injected into UI object and later available | |
554 | # in hooks executed by RhodeCode |
|
554 | # in hooks executed by RhodeCode | |
555 | check_locking = _should_check_locking(environ.get('QUERY_STRING')) |
|
555 | check_locking = _should_check_locking(environ.get('QUERY_STRING')) | |
556 |
|
556 | |||
557 | extras = vcs_operation_context( |
|
557 | extras = vcs_operation_context( | |
558 | environ, repo_name=self.acl_repo_name, username=username, |
|
558 | environ, repo_name=self.acl_repo_name, username=username, | |
559 | action=action, scm=self.SCM, check_locking=check_locking, |
|
559 | action=action, scm=self.SCM, check_locking=check_locking, | |
560 | is_shadow_repo=self.is_shadow_repo, check_branch_perms=check_branch_perms, |
|
560 | is_shadow_repo=self.is_shadow_repo, check_branch_perms=check_branch_perms, | |
561 | detect_force_push=detect_force_push |
|
561 | detect_force_push=detect_force_push | |
562 | ) |
|
562 | ) | |
563 |
|
563 | |||
564 | # ====================================================================== |
|
564 | # ====================================================================== | |
565 | # REQUEST HANDLING |
|
565 | # REQUEST HANDLING | |
566 | # ====================================================================== |
|
566 | # ====================================================================== | |
567 | repo_path = os.path.join( |
|
567 | repo_path = os.path.join( | |
568 | safe_str(self.base_path), safe_str(self.vcs_repo_name)) |
|
568 | safe_str(self.base_path), safe_str(self.vcs_repo_name)) | |
569 | log.debug('Repository path is %s', repo_path) |
|
569 | log.debug('Repository path is %s', repo_path) | |
570 |
|
570 | |||
571 | fix_PATH() |
|
571 | fix_PATH() | |
572 |
|
572 | |||
573 | log.info( |
|
573 | log.info( | |
574 | '%s action on %s repo "%s" by "%s" from %s %s', |
|
574 | '%s action on %s repo "%s" by "%s" from %s %s', | |
575 | action, self.SCM, safe_str(self.url_repo_name), |
|
575 | action, self.SCM, safe_str(self.url_repo_name), | |
576 | safe_str(username), ip_addr, user_agent) |
|
576 | safe_str(username), ip_addr, user_agent) | |
577 |
|
577 | |||
578 | return self._generate_vcs_response( |
|
578 | return self._generate_vcs_response( | |
579 | environ, start_response, repo_path, extras, action) |
|
579 | environ, start_response, repo_path, extras, action) | |
580 |
|
580 | |||
581 | @initialize_generator |
|
581 | @initialize_generator | |
582 | def _generate_vcs_response( |
|
582 | def _generate_vcs_response( | |
583 | self, environ, start_response, repo_path, extras, action): |
|
583 | self, environ, start_response, repo_path, extras, action): | |
584 | """ |
|
584 | """ | |
585 | Returns a generator for the response content. |
|
585 | Returns a generator for the response content. | |
586 |
|
586 | |||
587 | This method is implemented as a generator, so that it can trigger |
|
587 | This method is implemented as a generator, so that it can trigger | |
588 | the cache validation after all content sent back to the client. It |
|
588 | the cache validation after all content sent back to the client. It | |
589 | also handles the locking exceptions which will be triggered when |
|
589 | also handles the locking exceptions which will be triggered when | |
590 | the first chunk is produced by the underlying WSGI application. |
|
590 | the first chunk is produced by the underlying WSGI application. | |
591 | """ |
|
591 | """ | |
592 | txn_id = '' |
|
592 | txn_id = '' | |
593 | if 'CONTENT_LENGTH' in environ and environ['REQUEST_METHOD'] == 'MERGE': |
|
593 | if 'CONTENT_LENGTH' in environ and environ['REQUEST_METHOD'] == 'MERGE': | |
594 | # case for SVN, we want to re-use the callback daemon port |
|
594 | # case for SVN, we want to re-use the callback daemon port | |
595 | # so we use the txn_id, for this we peek the body, and still save |
|
595 | # so we use the txn_id, for this we peek the body, and still save | |
596 | # it as wsgi.input |
|
596 | # it as wsgi.input | |
597 | data = environ['wsgi.input'].read() |
|
597 | data = environ['wsgi.input'].read() | |
598 | environ['wsgi.input'] = StringIO(data) |
|
598 | environ['wsgi.input'] = StringIO(data) | |
599 | txn_id = extract_svn_txn_id(self.acl_repo_name, data) |
|
599 | txn_id = extract_svn_txn_id(self.acl_repo_name, data) | |
600 |
|
600 | |||
601 | callback_daemon, extras = self._prepare_callback_daemon( |
|
601 | callback_daemon, extras = self._prepare_callback_daemon( | |
602 | extras, environ, action, txn_id=txn_id) |
|
602 | extras, environ, action, txn_id=txn_id) | |
603 | log.debug('HOOKS extras is %s', extras) |
|
603 | log.debug('HOOKS extras is %s', extras) | |
604 |
|
604 | |||
605 | http_scheme = self._get_http_scheme(environ) |
|
605 | http_scheme = self._get_http_scheme(environ) | |
606 |
|
606 | |||
607 | config = self._create_config(extras, self.acl_repo_name, scheme=http_scheme) |
|
607 | config = self._create_config(extras, self.acl_repo_name, scheme=http_scheme) | |
608 | app = self._create_wsgi_app(repo_path, self.url_repo_name, config) |
|
608 | app = self._create_wsgi_app(repo_path, self.url_repo_name, config) | |
609 | with callback_daemon: |
|
609 | with callback_daemon: | |
610 | app.rc_extras = extras |
|
610 | app.rc_extras = extras | |
611 |
|
611 | |||
612 | try: |
|
612 | try: | |
613 | response = app(environ, start_response) |
|
613 | response = app(environ, start_response) | |
614 | finally: |
|
614 | finally: | |
615 | # This statement works together with the decorator |
|
615 | # This statement works together with the decorator | |
616 | # "initialize_generator" above. The decorator ensures that |
|
616 | # "initialize_generator" above. The decorator ensures that | |
617 | # we hit the first yield statement before the generator is |
|
617 | # we hit the first yield statement before the generator is | |
618 | # returned back to the WSGI server. This is needed to |
|
618 | # returned back to the WSGI server. This is needed to | |
619 | # ensure that the call to "app" above triggers the |
|
619 | # ensure that the call to "app" above triggers the | |
620 | # needed callback to "start_response" before the |
|
620 | # needed callback to "start_response" before the | |
621 | # generator is actually used. |
|
621 | # generator is actually used. | |
622 | yield "__init__" |
|
622 | yield "__init__" | |
623 |
|
623 | |||
624 | # iter content |
|
624 | # iter content | |
625 | for chunk in response: |
|
625 | for chunk in response: | |
626 | yield chunk |
|
626 | yield chunk | |
627 |
|
627 | |||
628 | try: |
|
628 | try: | |
629 | # invalidate cache on push |
|
629 | # invalidate cache on push | |
630 | if action == 'push': |
|
630 | if action == 'push': | |
631 | self._invalidate_cache(self.url_repo_name) |
|
631 | self._invalidate_cache(self.url_repo_name) | |
632 | finally: |
|
632 | finally: | |
633 | meta.Session.remove() |
|
633 | meta.Session.remove() | |
634 |
|
634 | |||
635 | def _get_repository_name(self, environ): |
|
635 | def _get_repository_name(self, environ): | |
636 | """Get repository name out of the environmnent |
|
636 | """Get repository name out of the environmnent | |
637 |
|
637 | |||
638 | :param environ: WSGI environment |
|
638 | :param environ: WSGI environment | |
639 | """ |
|
639 | """ | |
640 | raise NotImplementedError() |
|
640 | raise NotImplementedError() | |
641 |
|
641 | |||
642 | def _get_action(self, environ): |
|
642 | def _get_action(self, environ): | |
643 | """Map request commands into a pull or push command. |
|
643 | """Map request commands into a pull or push command. | |
644 |
|
644 | |||
645 | :param environ: WSGI environment |
|
645 | :param environ: WSGI environment | |
646 | """ |
|
646 | """ | |
647 | raise NotImplementedError() |
|
647 | raise NotImplementedError() | |
648 |
|
648 | |||
649 | def _create_wsgi_app(self, repo_path, repo_name, config): |
|
649 | def _create_wsgi_app(self, repo_path, repo_name, config): | |
650 | """Return the WSGI app that will finally handle the request.""" |
|
650 | """Return the WSGI app that will finally handle the request.""" | |
651 | raise NotImplementedError() |
|
651 | raise NotImplementedError() | |
652 |
|
652 | |||
653 | def _create_config(self, extras, repo_name, scheme='http'): |
|
653 | def _create_config(self, extras, repo_name, scheme='http'): | |
654 | """Create a safe config representation.""" |
|
654 | """Create a safe config representation.""" | |
655 | raise NotImplementedError() |
|
655 | raise NotImplementedError() | |
656 |
|
656 | |||
657 | def _should_use_callback_daemon(self, extras, environ, action): |
|
657 | def _should_use_callback_daemon(self, extras, environ, action): | |
658 | if extras.get('is_shadow_repo'): |
|
658 | if extras.get('is_shadow_repo'): | |
659 | # we don't want to execute hooks, and callback daemon for shadow repos |
|
659 | # we don't want to execute hooks, and callback daemon for shadow repos | |
660 | return False |
|
660 | return False | |
661 | return True |
|
661 | return True | |
662 |
|
662 | |||
663 | def _prepare_callback_daemon(self, extras, environ, action, txn_id=None): |
|
663 | def _prepare_callback_daemon(self, extras, environ, action, txn_id=None): | |
664 | direct_calls = vcs_settings.HOOKS_DIRECT_CALLS |
|
664 | direct_calls = vcs_settings.HOOKS_DIRECT_CALLS | |
665 | if not self._should_use_callback_daemon(extras, environ, action): |
|
665 | if not self._should_use_callback_daemon(extras, environ, action): | |
666 | # disable callback daemon for actions that don't require it |
|
666 | # disable callback daemon for actions that don't require it | |
667 | direct_calls = True |
|
667 | direct_calls = True | |
668 |
|
668 | |||
669 | return prepare_callback_daemon( |
|
669 | return prepare_callback_daemon( | |
670 | extras, protocol=vcs_settings.HOOKS_PROTOCOL, |
|
670 | extras, protocol=vcs_settings.HOOKS_PROTOCOL, | |
671 | host=vcs_settings.HOOKS_HOST, use_direct_calls=direct_calls, txn_id=txn_id) |
|
671 | host=vcs_settings.HOOKS_HOST, use_direct_calls=direct_calls, txn_id=txn_id) | |
672 |
|
672 | |||
673 |
|
673 | |||
674 | def _should_check_locking(query_string): |
|
674 | def _should_check_locking(query_string): | |
675 | # this is kind of hacky, but due to how mercurial handles client-server |
|
675 | # this is kind of hacky, but due to how mercurial handles client-server | |
676 | # server see all operation on commit; bookmarks, phases and |
|
676 | # server see all operation on commit; bookmarks, phases and | |
677 | # obsolescence marker in different transaction, we don't want to check |
|
677 | # obsolescence marker in different transaction, we don't want to check | |
678 | # locking on those |
|
678 | # locking on those | |
679 | return query_string not in ['cmd=listkeys'] |
|
679 | return query_string not in ['cmd=listkeys'] |
@@ -1,496 +1,496 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
|
2 | |||
3 | # Copyright (C) 2014-2020 RhodeCode GmbH |
|
3 | # Copyright (C) 2014-2020 RhodeCode GmbH | |
4 | # |
|
4 | # | |
5 | # This program is free software: you can redistribute it and/or modify |
|
5 | # This program is free software: you can redistribute it and/or modify | |
6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
6 | # it under the terms of the GNU Affero General Public License, version 3 | |
7 | # (only), as published by the Free Software Foundation. |
|
7 | # (only), as published by the Free Software Foundation. | |
8 | # |
|
8 | # | |
9 | # This program is distributed in the hope that it will be useful, |
|
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. |
|
12 | # GNU General Public License for more details. | |
13 | # |
|
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License |
|
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | # |
|
16 | # | |
17 | # This program is dual-licensed. If you wish to learn more about the |
|
17 | # This program is dual-licensed. If you wish to learn more about the | |
18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |
20 |
|
20 | |||
21 | """ |
|
21 | """ | |
22 | GIT commit module |
|
22 | GIT commit module | |
23 | """ |
|
23 | """ | |
24 |
|
24 | |||
25 | import re |
|
25 | import re | |
26 | import stat |
|
26 | import stat | |
27 | from itertools import chain |
|
27 | from itertools import chain | |
28 |
from |
|
28 | from io import StringIO | |
29 |
|
29 | |||
30 | from zope.cachedescriptors.property import Lazy as LazyProperty |
|
30 | from zope.cachedescriptors.property import Lazy as LazyProperty | |
31 |
|
31 | |||
32 | from rhodecode.lib.datelib import utcdate_fromtimestamp |
|
32 | from rhodecode.lib.datelib import utcdate_fromtimestamp | |
33 | from rhodecode.lib.utils import safe_unicode, safe_str |
|
33 | from rhodecode.lib.utils import safe_unicode, safe_str | |
34 | from rhodecode.lib.utils2 import safe_int |
|
34 | from rhodecode.lib.utils2 import safe_int | |
35 | from rhodecode.lib.vcs.conf import settings |
|
35 | from rhodecode.lib.vcs.conf import settings | |
36 | from rhodecode.lib.vcs.backends import base |
|
36 | from rhodecode.lib.vcs.backends import base | |
37 | from rhodecode.lib.vcs.exceptions import CommitError, NodeDoesNotExistError |
|
37 | from rhodecode.lib.vcs.exceptions import CommitError, NodeDoesNotExistError | |
38 | from rhodecode.lib.vcs.nodes import ( |
|
38 | from rhodecode.lib.vcs.nodes import ( | |
39 | FileNode, DirNode, NodeKind, RootNode, SubModuleNode, |
|
39 | FileNode, DirNode, NodeKind, RootNode, SubModuleNode, | |
40 | ChangedFileNodesGenerator, AddedFileNodesGenerator, |
|
40 | ChangedFileNodesGenerator, AddedFileNodesGenerator, | |
41 | RemovedFileNodesGenerator, LargeFileNode) |
|
41 | RemovedFileNodesGenerator, LargeFileNode) | |
42 | from rhodecode.lib.vcs.compat import configparser |
|
42 | from rhodecode.lib.vcs.compat import configparser | |
43 |
|
43 | |||
44 |
|
44 | |||
45 | class GitCommit(base.BaseCommit): |
|
45 | class GitCommit(base.BaseCommit): | |
46 | """ |
|
46 | """ | |
47 | Represents state of the repository at single commit id. |
|
47 | Represents state of the repository at single commit id. | |
48 | """ |
|
48 | """ | |
49 |
|
49 | |||
50 | _filter_pre_load = [ |
|
50 | _filter_pre_load = [ | |
51 | # done through a more complex tree walk on parents |
|
51 | # done through a more complex tree walk on parents | |
52 | "affected_files", |
|
52 | "affected_files", | |
53 | # done through subprocess not remote call |
|
53 | # done through subprocess not remote call | |
54 | "children", |
|
54 | "children", | |
55 | # done through a more complex tree walk on parents |
|
55 | # done through a more complex tree walk on parents | |
56 | "status", |
|
56 | "status", | |
57 | # mercurial specific property not supported here |
|
57 | # mercurial specific property not supported here | |
58 | "_file_paths", |
|
58 | "_file_paths", | |
59 | # mercurial specific property not supported here |
|
59 | # mercurial specific property not supported here | |
60 | 'obsolete', |
|
60 | 'obsolete', | |
61 | # mercurial specific property not supported here |
|
61 | # mercurial specific property not supported here | |
62 | 'phase', |
|
62 | 'phase', | |
63 | # mercurial specific property not supported here |
|
63 | # mercurial specific property not supported here | |
64 | 'hidden' |
|
64 | 'hidden' | |
65 | ] |
|
65 | ] | |
66 |
|
66 | |||
67 | def __init__(self, repository, raw_id, idx, pre_load=None): |
|
67 | def __init__(self, repository, raw_id, idx, pre_load=None): | |
68 | self.repository = repository |
|
68 | self.repository = repository | |
69 | self._remote = repository._remote |
|
69 | self._remote = repository._remote | |
70 | # TODO: johbo: Tweak of raw_id should not be necessary |
|
70 | # TODO: johbo: Tweak of raw_id should not be necessary | |
71 | self.raw_id = safe_str(raw_id) |
|
71 | self.raw_id = safe_str(raw_id) | |
72 | self.idx = idx |
|
72 | self.idx = idx | |
73 |
|
73 | |||
74 | self._set_bulk_properties(pre_load) |
|
74 | self._set_bulk_properties(pre_load) | |
75 |
|
75 | |||
76 | # caches |
|
76 | # caches | |
77 | self._stat_modes = {} # stat info for paths |
|
77 | self._stat_modes = {} # stat info for paths | |
78 | self._paths = {} # path processed with parse_tree |
|
78 | self._paths = {} # path processed with parse_tree | |
79 | self.nodes = {} |
|
79 | self.nodes = {} | |
80 | self._submodules = None |
|
80 | self._submodules = None | |
81 |
|
81 | |||
82 | def _set_bulk_properties(self, pre_load): |
|
82 | def _set_bulk_properties(self, pre_load): | |
83 |
|
83 | |||
84 | if not pre_load: |
|
84 | if not pre_load: | |
85 | return |
|
85 | return | |
86 | pre_load = [entry for entry in pre_load |
|
86 | pre_load = [entry for entry in pre_load | |
87 | if entry not in self._filter_pre_load] |
|
87 | if entry not in self._filter_pre_load] | |
88 | if not pre_load: |
|
88 | if not pre_load: | |
89 | return |
|
89 | return | |
90 |
|
90 | |||
91 | result = self._remote.bulk_request(self.raw_id, pre_load) |
|
91 | result = self._remote.bulk_request(self.raw_id, pre_load) | |
92 | for attr, value in result.items(): |
|
92 | for attr, value in result.items(): | |
93 | if attr in ["author", "message"]: |
|
93 | if attr in ["author", "message"]: | |
94 | if value: |
|
94 | if value: | |
95 | value = safe_unicode(value) |
|
95 | value = safe_unicode(value) | |
96 | elif attr == "date": |
|
96 | elif attr == "date": | |
97 | value = utcdate_fromtimestamp(*value) |
|
97 | value = utcdate_fromtimestamp(*value) | |
98 | elif attr == "parents": |
|
98 | elif attr == "parents": | |
99 | value = self._make_commits(value) |
|
99 | value = self._make_commits(value) | |
100 | elif attr == "branch": |
|
100 | elif attr == "branch": | |
101 | value = self._set_branch(value) |
|
101 | value = self._set_branch(value) | |
102 | self.__dict__[attr] = value |
|
102 | self.__dict__[attr] = value | |
103 |
|
103 | |||
104 | @LazyProperty |
|
104 | @LazyProperty | |
105 | def _commit(self): |
|
105 | def _commit(self): | |
106 | return self._remote[self.raw_id] |
|
106 | return self._remote[self.raw_id] | |
107 |
|
107 | |||
108 | @LazyProperty |
|
108 | @LazyProperty | |
109 | def _tree_id(self): |
|
109 | def _tree_id(self): | |
110 | return self._remote[self._commit['tree']]['id'] |
|
110 | return self._remote[self._commit['tree']]['id'] | |
111 |
|
111 | |||
112 | @LazyProperty |
|
112 | @LazyProperty | |
113 | def id(self): |
|
113 | def id(self): | |
114 | return self.raw_id |
|
114 | return self.raw_id | |
115 |
|
115 | |||
116 | @LazyProperty |
|
116 | @LazyProperty | |
117 | def short_id(self): |
|
117 | def short_id(self): | |
118 | return self.raw_id[:12] |
|
118 | return self.raw_id[:12] | |
119 |
|
119 | |||
120 | @LazyProperty |
|
120 | @LazyProperty | |
121 | def message(self): |
|
121 | def message(self): | |
122 | return safe_unicode(self._remote.message(self.id)) |
|
122 | return safe_unicode(self._remote.message(self.id)) | |
123 |
|
123 | |||
124 | @LazyProperty |
|
124 | @LazyProperty | |
125 | def committer(self): |
|
125 | def committer(self): | |
126 | return safe_unicode(self._remote.author(self.id)) |
|
126 | return safe_unicode(self._remote.author(self.id)) | |
127 |
|
127 | |||
128 | @LazyProperty |
|
128 | @LazyProperty | |
129 | def author(self): |
|
129 | def author(self): | |
130 | return safe_unicode(self._remote.author(self.id)) |
|
130 | return safe_unicode(self._remote.author(self.id)) | |
131 |
|
131 | |||
132 | @LazyProperty |
|
132 | @LazyProperty | |
133 | def date(self): |
|
133 | def date(self): | |
134 | unix_ts, tz = self._remote.date(self.raw_id) |
|
134 | unix_ts, tz = self._remote.date(self.raw_id) | |
135 | return utcdate_fromtimestamp(unix_ts, tz) |
|
135 | return utcdate_fromtimestamp(unix_ts, tz) | |
136 |
|
136 | |||
137 | @LazyProperty |
|
137 | @LazyProperty | |
138 | def status(self): |
|
138 | def status(self): | |
139 | """ |
|
139 | """ | |
140 | Returns modified, added, removed, deleted files for current commit |
|
140 | Returns modified, added, removed, deleted files for current commit | |
141 | """ |
|
141 | """ | |
142 | return self.changed, self.added, self.removed |
|
142 | return self.changed, self.added, self.removed | |
143 |
|
143 | |||
144 | @LazyProperty |
|
144 | @LazyProperty | |
145 | def tags(self): |
|
145 | def tags(self): | |
146 | tags = [safe_unicode(name) for name, |
|
146 | tags = [safe_unicode(name) for name, | |
147 | commit_id in self.repository.tags.iteritems() |
|
147 | commit_id in self.repository.tags.iteritems() | |
148 | if commit_id == self.raw_id] |
|
148 | if commit_id == self.raw_id] | |
149 | return tags |
|
149 | return tags | |
150 |
|
150 | |||
151 | @LazyProperty |
|
151 | @LazyProperty | |
152 | def commit_branches(self): |
|
152 | def commit_branches(self): | |
153 | branches = [] |
|
153 | branches = [] | |
154 | for name, commit_id in self.repository.branches.iteritems(): |
|
154 | for name, commit_id in self.repository.branches.iteritems(): | |
155 | if commit_id == self.raw_id: |
|
155 | if commit_id == self.raw_id: | |
156 | branches.append(name) |
|
156 | branches.append(name) | |
157 | return branches |
|
157 | return branches | |
158 |
|
158 | |||
159 | def _set_branch(self, branches): |
|
159 | def _set_branch(self, branches): | |
160 | if branches: |
|
160 | if branches: | |
161 | # actually commit can have multiple branches in git |
|
161 | # actually commit can have multiple branches in git | |
162 | return safe_unicode(branches[0]) |
|
162 | return safe_unicode(branches[0]) | |
163 |
|
163 | |||
164 | @LazyProperty |
|
164 | @LazyProperty | |
165 | def branch(self): |
|
165 | def branch(self): | |
166 | branches = self._remote.branch(self.raw_id) |
|
166 | branches = self._remote.branch(self.raw_id) | |
167 | return self._set_branch(branches) |
|
167 | return self._set_branch(branches) | |
168 |
|
168 | |||
169 | def _get_tree_id_for_path(self, path): |
|
169 | def _get_tree_id_for_path(self, path): | |
170 | path = safe_str(path) |
|
170 | path = safe_str(path) | |
171 | if path in self._paths: |
|
171 | if path in self._paths: | |
172 | return self._paths[path] |
|
172 | return self._paths[path] | |
173 |
|
173 | |||
174 | tree_id = self._tree_id |
|
174 | tree_id = self._tree_id | |
175 |
|
175 | |||
176 | path = path.strip('/') |
|
176 | path = path.strip('/') | |
177 | if path == '': |
|
177 | if path == '': | |
178 | data = [tree_id, "tree"] |
|
178 | data = [tree_id, "tree"] | |
179 | self._paths[''] = data |
|
179 | self._paths[''] = data | |
180 | return data |
|
180 | return data | |
181 |
|
181 | |||
182 | tree_id, tree_type, tree_mode = \ |
|
182 | tree_id, tree_type, tree_mode = \ | |
183 | self._remote.tree_and_type_for_path(self.raw_id, path) |
|
183 | self._remote.tree_and_type_for_path(self.raw_id, path) | |
184 | if tree_id is None: |
|
184 | if tree_id is None: | |
185 | raise self.no_node_at_path(path) |
|
185 | raise self.no_node_at_path(path) | |
186 |
|
186 | |||
187 | self._paths[path] = [tree_id, tree_type] |
|
187 | self._paths[path] = [tree_id, tree_type] | |
188 | self._stat_modes[path] = tree_mode |
|
188 | self._stat_modes[path] = tree_mode | |
189 |
|
189 | |||
190 | if path not in self._paths: |
|
190 | if path not in self._paths: | |
191 | raise self.no_node_at_path(path) |
|
191 | raise self.no_node_at_path(path) | |
192 |
|
192 | |||
193 | return self._paths[path] |
|
193 | return self._paths[path] | |
194 |
|
194 | |||
195 | def _get_kind(self, path): |
|
195 | def _get_kind(self, path): | |
196 | tree_id, type_ = self._get_tree_id_for_path(path) |
|
196 | tree_id, type_ = self._get_tree_id_for_path(path) | |
197 | if type_ == 'blob': |
|
197 | if type_ == 'blob': | |
198 | return NodeKind.FILE |
|
198 | return NodeKind.FILE | |
199 | elif type_ == 'tree': |
|
199 | elif type_ == 'tree': | |
200 | return NodeKind.DIR |
|
200 | return NodeKind.DIR | |
201 | elif type_ == 'link': |
|
201 | elif type_ == 'link': | |
202 | return NodeKind.SUBMODULE |
|
202 | return NodeKind.SUBMODULE | |
203 | return None |
|
203 | return None | |
204 |
|
204 | |||
205 | def _get_filectx(self, path): |
|
205 | def _get_filectx(self, path): | |
206 | path = self._fix_path(path) |
|
206 | path = self._fix_path(path) | |
207 | if self._get_kind(path) != NodeKind.FILE: |
|
207 | if self._get_kind(path) != NodeKind.FILE: | |
208 | raise CommitError( |
|
208 | raise CommitError( | |
209 | "File does not exist for commit %s at '%s'" % (self.raw_id, path)) |
|
209 | "File does not exist for commit %s at '%s'" % (self.raw_id, path)) | |
210 | return path |
|
210 | return path | |
211 |
|
211 | |||
212 | def _get_file_nodes(self): |
|
212 | def _get_file_nodes(self): | |
213 | return chain(*(t[2] for t in self.walk())) |
|
213 | return chain(*(t[2] for t in self.walk())) | |
214 |
|
214 | |||
215 | @LazyProperty |
|
215 | @LazyProperty | |
216 | def parents(self): |
|
216 | def parents(self): | |
217 | """ |
|
217 | """ | |
218 | Returns list of parent commits. |
|
218 | Returns list of parent commits. | |
219 | """ |
|
219 | """ | |
220 | parent_ids = self._remote.parents(self.id) |
|
220 | parent_ids = self._remote.parents(self.id) | |
221 | return self._make_commits(parent_ids) |
|
221 | return self._make_commits(parent_ids) | |
222 |
|
222 | |||
223 | @LazyProperty |
|
223 | @LazyProperty | |
224 | def children(self): |
|
224 | def children(self): | |
225 | """ |
|
225 | """ | |
226 | Returns list of child commits. |
|
226 | Returns list of child commits. | |
227 | """ |
|
227 | """ | |
228 |
|
228 | |||
229 | children = self._remote.children(self.raw_id) |
|
229 | children = self._remote.children(self.raw_id) | |
230 | return self._make_commits(children) |
|
230 | return self._make_commits(children) | |
231 |
|
231 | |||
232 | def _make_commits(self, commit_ids): |
|
232 | def _make_commits(self, commit_ids): | |
233 | def commit_maker(_commit_id): |
|
233 | def commit_maker(_commit_id): | |
234 | return self.repository.get_commit(commit_id=commit_id) |
|
234 | return self.repository.get_commit(commit_id=commit_id) | |
235 |
|
235 | |||
236 | return [commit_maker(commit_id) for commit_id in commit_ids] |
|
236 | return [commit_maker(commit_id) for commit_id in commit_ids] | |
237 |
|
237 | |||
238 | def get_file_mode(self, path): |
|
238 | def get_file_mode(self, path): | |
239 | """ |
|
239 | """ | |
240 | Returns stat mode of the file at the given `path`. |
|
240 | Returns stat mode of the file at the given `path`. | |
241 | """ |
|
241 | """ | |
242 | path = safe_str(path) |
|
242 | path = safe_str(path) | |
243 | # ensure path is traversed |
|
243 | # ensure path is traversed | |
244 | self._get_tree_id_for_path(path) |
|
244 | self._get_tree_id_for_path(path) | |
245 | return self._stat_modes[path] |
|
245 | return self._stat_modes[path] | |
246 |
|
246 | |||
247 | def is_link(self, path): |
|
247 | def is_link(self, path): | |
248 | return stat.S_ISLNK(self.get_file_mode(path)) |
|
248 | return stat.S_ISLNK(self.get_file_mode(path)) | |
249 |
|
249 | |||
250 | def is_node_binary(self, path): |
|
250 | def is_node_binary(self, path): | |
251 | tree_id, _ = self._get_tree_id_for_path(path) |
|
251 | tree_id, _ = self._get_tree_id_for_path(path) | |
252 | return self._remote.is_binary(tree_id) |
|
252 | return self._remote.is_binary(tree_id) | |
253 |
|
253 | |||
254 | def get_file_content(self, path): |
|
254 | def get_file_content(self, path): | |
255 | """ |
|
255 | """ | |
256 | Returns content of the file at given `path`. |
|
256 | Returns content of the file at given `path`. | |
257 | """ |
|
257 | """ | |
258 | tree_id, _ = self._get_tree_id_for_path(path) |
|
258 | tree_id, _ = self._get_tree_id_for_path(path) | |
259 | return self._remote.blob_as_pretty_string(tree_id) |
|
259 | return self._remote.blob_as_pretty_string(tree_id) | |
260 |
|
260 | |||
261 | def get_file_content_streamed(self, path): |
|
261 | def get_file_content_streamed(self, path): | |
262 | tree_id, _ = self._get_tree_id_for_path(path) |
|
262 | tree_id, _ = self._get_tree_id_for_path(path) | |
263 | stream_method = getattr(self._remote, 'stream:blob_as_pretty_string') |
|
263 | stream_method = getattr(self._remote, 'stream:blob_as_pretty_string') | |
264 | return stream_method(tree_id) |
|
264 | return stream_method(tree_id) | |
265 |
|
265 | |||
266 | def get_file_size(self, path): |
|
266 | def get_file_size(self, path): | |
267 | """ |
|
267 | """ | |
268 | Returns size of the file at given `path`. |
|
268 | Returns size of the file at given `path`. | |
269 | """ |
|
269 | """ | |
270 | tree_id, _ = self._get_tree_id_for_path(path) |
|
270 | tree_id, _ = self._get_tree_id_for_path(path) | |
271 | return self._remote.blob_raw_length(tree_id) |
|
271 | return self._remote.blob_raw_length(tree_id) | |
272 |
|
272 | |||
273 | def get_path_history(self, path, limit=None, pre_load=None): |
|
273 | def get_path_history(self, path, limit=None, pre_load=None): | |
274 | """ |
|
274 | """ | |
275 | Returns history of file as reversed list of `GitCommit` objects for |
|
275 | Returns history of file as reversed list of `GitCommit` objects for | |
276 | which file at given `path` has been modified. |
|
276 | which file at given `path` has been modified. | |
277 | """ |
|
277 | """ | |
278 |
|
278 | |||
279 | path = self._get_filectx(path) |
|
279 | path = self._get_filectx(path) | |
280 | hist = self._remote.node_history(self.raw_id, path, limit) |
|
280 | hist = self._remote.node_history(self.raw_id, path, limit) | |
281 | return [ |
|
281 | return [ | |
282 | self.repository.get_commit(commit_id=commit_id, pre_load=pre_load) |
|
282 | self.repository.get_commit(commit_id=commit_id, pre_load=pre_load) | |
283 | for commit_id in hist] |
|
283 | for commit_id in hist] | |
284 |
|
284 | |||
285 | def get_file_annotate(self, path, pre_load=None): |
|
285 | def get_file_annotate(self, path, pre_load=None): | |
286 | """ |
|
286 | """ | |
287 | Returns a generator of four element tuples with |
|
287 | Returns a generator of four element tuples with | |
288 | lineno, commit_id, commit lazy loader and line |
|
288 | lineno, commit_id, commit lazy loader and line | |
289 | """ |
|
289 | """ | |
290 |
|
290 | |||
291 | result = self._remote.node_annotate(self.raw_id, path) |
|
291 | result = self._remote.node_annotate(self.raw_id, path) | |
292 |
|
292 | |||
293 | for ln_no, commit_id, content in result: |
|
293 | for ln_no, commit_id, content in result: | |
294 | yield ( |
|
294 | yield ( | |
295 | ln_no, commit_id, |
|
295 | ln_no, commit_id, | |
296 | lambda: self.repository.get_commit(commit_id=commit_id, pre_load=pre_load), |
|
296 | lambda: self.repository.get_commit(commit_id=commit_id, pre_load=pre_load), | |
297 | content) |
|
297 | content) | |
298 |
|
298 | |||
299 | def get_nodes(self, path): |
|
299 | def get_nodes(self, path): | |
300 |
|
300 | |||
301 | if self._get_kind(path) != NodeKind.DIR: |
|
301 | if self._get_kind(path) != NodeKind.DIR: | |
302 | raise CommitError( |
|
302 | raise CommitError( | |
303 | "Directory does not exist for commit %s at '%s'" % (self.raw_id, path)) |
|
303 | "Directory does not exist for commit %s at '%s'" % (self.raw_id, path)) | |
304 | path = self._fix_path(path) |
|
304 | path = self._fix_path(path) | |
305 |
|
305 | |||
306 | tree_id, _ = self._get_tree_id_for_path(path) |
|
306 | tree_id, _ = self._get_tree_id_for_path(path) | |
307 |
|
307 | |||
308 | dirnodes = [] |
|
308 | dirnodes = [] | |
309 | filenodes = [] |
|
309 | filenodes = [] | |
310 |
|
310 | |||
311 | # extracted tree ID gives us our files... |
|
311 | # extracted tree ID gives us our files... | |
312 | bytes_path = safe_str(path) # libgit operates on bytes |
|
312 | bytes_path = safe_str(path) # libgit operates on bytes | |
313 | for name, stat_, id_, type_ in self._remote.tree_items(tree_id): |
|
313 | for name, stat_, id_, type_ in self._remote.tree_items(tree_id): | |
314 | if type_ == 'link': |
|
314 | if type_ == 'link': | |
315 | url = self._get_submodule_url('/'.join((bytes_path, name))) |
|
315 | url = self._get_submodule_url('/'.join((bytes_path, name))) | |
316 | dirnodes.append(SubModuleNode( |
|
316 | dirnodes.append(SubModuleNode( | |
317 | name, url=url, commit=id_, alias=self.repository.alias)) |
|
317 | name, url=url, commit=id_, alias=self.repository.alias)) | |
318 | continue |
|
318 | continue | |
319 |
|
319 | |||
320 | if bytes_path != '': |
|
320 | if bytes_path != '': | |
321 | obj_path = '/'.join((bytes_path, name)) |
|
321 | obj_path = '/'.join((bytes_path, name)) | |
322 | else: |
|
322 | else: | |
323 | obj_path = name |
|
323 | obj_path = name | |
324 | if obj_path not in self._stat_modes: |
|
324 | if obj_path not in self._stat_modes: | |
325 | self._stat_modes[obj_path] = stat_ |
|
325 | self._stat_modes[obj_path] = stat_ | |
326 |
|
326 | |||
327 | if type_ == 'tree': |
|
327 | if type_ == 'tree': | |
328 | dirnodes.append(DirNode(obj_path, commit=self)) |
|
328 | dirnodes.append(DirNode(obj_path, commit=self)) | |
329 | elif type_ == 'blob': |
|
329 | elif type_ == 'blob': | |
330 | filenodes.append(FileNode(obj_path, commit=self, mode=stat_)) |
|
330 | filenodes.append(FileNode(obj_path, commit=self, mode=stat_)) | |
331 | else: |
|
331 | else: | |
332 | raise CommitError( |
|
332 | raise CommitError( | |
333 | "Requested object should be Tree or Blob, is %s", type_) |
|
333 | "Requested object should be Tree or Blob, is %s", type_) | |
334 |
|
334 | |||
335 | nodes = dirnodes + filenodes |
|
335 | nodes = dirnodes + filenodes | |
336 | for node in nodes: |
|
336 | for node in nodes: | |
337 | if node.path not in self.nodes: |
|
337 | if node.path not in self.nodes: | |
338 | self.nodes[node.path] = node |
|
338 | self.nodes[node.path] = node | |
339 | nodes.sort() |
|
339 | nodes.sort() | |
340 | return nodes |
|
340 | return nodes | |
341 |
|
341 | |||
342 | def get_node(self, path, pre_load=None): |
|
342 | def get_node(self, path, pre_load=None): | |
343 | if isinstance(path, unicode): |
|
343 | if isinstance(path, unicode): | |
344 | path = path.encode('utf-8') |
|
344 | path = path.encode('utf-8') | |
345 | path = self._fix_path(path) |
|
345 | path = self._fix_path(path) | |
346 | if path not in self.nodes: |
|
346 | if path not in self.nodes: | |
347 | try: |
|
347 | try: | |
348 | tree_id, type_ = self._get_tree_id_for_path(path) |
|
348 | tree_id, type_ = self._get_tree_id_for_path(path) | |
349 | except CommitError: |
|
349 | except CommitError: | |
350 | raise NodeDoesNotExistError( |
|
350 | raise NodeDoesNotExistError( | |
351 | "Cannot find one of parents' directories for a given " |
|
351 | "Cannot find one of parents' directories for a given " | |
352 | "path: %s" % path) |
|
352 | "path: %s" % path) | |
353 |
|
353 | |||
354 | if type_ in ['link', 'commit']: |
|
354 | if type_ in ['link', 'commit']: | |
355 | url = self._get_submodule_url(path) |
|
355 | url = self._get_submodule_url(path) | |
356 | node = SubModuleNode(path, url=url, commit=tree_id, |
|
356 | node = SubModuleNode(path, url=url, commit=tree_id, | |
357 | alias=self.repository.alias) |
|
357 | alias=self.repository.alias) | |
358 | elif type_ == 'tree': |
|
358 | elif type_ == 'tree': | |
359 | if path == '': |
|
359 | if path == '': | |
360 | node = RootNode(commit=self) |
|
360 | node = RootNode(commit=self) | |
361 | else: |
|
361 | else: | |
362 | node = DirNode(path, commit=self) |
|
362 | node = DirNode(path, commit=self) | |
363 | elif type_ == 'blob': |
|
363 | elif type_ == 'blob': | |
364 | node = FileNode(path, commit=self, pre_load=pre_load) |
|
364 | node = FileNode(path, commit=self, pre_load=pre_load) | |
365 | self._stat_modes[path] = node.mode |
|
365 | self._stat_modes[path] = node.mode | |
366 | else: |
|
366 | else: | |
367 | raise self.no_node_at_path(path) |
|
367 | raise self.no_node_at_path(path) | |
368 |
|
368 | |||
369 | # cache node |
|
369 | # cache node | |
370 | self.nodes[path] = node |
|
370 | self.nodes[path] = node | |
371 |
|
371 | |||
372 | return self.nodes[path] |
|
372 | return self.nodes[path] | |
373 |
|
373 | |||
374 | def get_largefile_node(self, path): |
|
374 | def get_largefile_node(self, path): | |
375 | tree_id, _ = self._get_tree_id_for_path(path) |
|
375 | tree_id, _ = self._get_tree_id_for_path(path) | |
376 | pointer_spec = self._remote.is_large_file(tree_id) |
|
376 | pointer_spec = self._remote.is_large_file(tree_id) | |
377 |
|
377 | |||
378 | if pointer_spec: |
|
378 | if pointer_spec: | |
379 | # content of that file regular FileNode is the hash of largefile |
|
379 | # content of that file regular FileNode is the hash of largefile | |
380 | file_id = pointer_spec.get('oid_hash') |
|
380 | file_id = pointer_spec.get('oid_hash') | |
381 | if self._remote.in_largefiles_store(file_id): |
|
381 | if self._remote.in_largefiles_store(file_id): | |
382 | lf_path = self._remote.store_path(file_id) |
|
382 | lf_path = self._remote.store_path(file_id) | |
383 | return LargeFileNode(lf_path, commit=self, org_path=path) |
|
383 | return LargeFileNode(lf_path, commit=self, org_path=path) | |
384 |
|
384 | |||
385 | @LazyProperty |
|
385 | @LazyProperty | |
386 | def affected_files(self): |
|
386 | def affected_files(self): | |
387 | """ |
|
387 | """ | |
388 | Gets a fast accessible file changes for given commit |
|
388 | Gets a fast accessible file changes for given commit | |
389 | """ |
|
389 | """ | |
390 | added, modified, deleted = self._changes_cache |
|
390 | added, modified, deleted = self._changes_cache | |
391 | return list(added.union(modified).union(deleted)) |
|
391 | return list(added.union(modified).union(deleted)) | |
392 |
|
392 | |||
393 | @LazyProperty |
|
393 | @LazyProperty | |
394 | def _changes_cache(self): |
|
394 | def _changes_cache(self): | |
395 | added = set() |
|
395 | added = set() | |
396 | modified = set() |
|
396 | modified = set() | |
397 | deleted = set() |
|
397 | deleted = set() | |
398 | _r = self._remote |
|
398 | _r = self._remote | |
399 |
|
399 | |||
400 | parents = self.parents |
|
400 | parents = self.parents | |
401 | if not self.parents: |
|
401 | if not self.parents: | |
402 | parents = [base.EmptyCommit()] |
|
402 | parents = [base.EmptyCommit()] | |
403 | for parent in parents: |
|
403 | for parent in parents: | |
404 | if isinstance(parent, base.EmptyCommit): |
|
404 | if isinstance(parent, base.EmptyCommit): | |
405 | oid = None |
|
405 | oid = None | |
406 | else: |
|
406 | else: | |
407 | oid = parent.raw_id |
|
407 | oid = parent.raw_id | |
408 | changes = _r.tree_changes(oid, self.raw_id) |
|
408 | changes = _r.tree_changes(oid, self.raw_id) | |
409 | for (oldpath, newpath), (_, _), (_, _) in changes: |
|
409 | for (oldpath, newpath), (_, _), (_, _) in changes: | |
410 | if newpath and oldpath: |
|
410 | if newpath and oldpath: | |
411 | modified.add(newpath) |
|
411 | modified.add(newpath) | |
412 | elif newpath and not oldpath: |
|
412 | elif newpath and not oldpath: | |
413 | added.add(newpath) |
|
413 | added.add(newpath) | |
414 | elif not newpath and oldpath: |
|
414 | elif not newpath and oldpath: | |
415 | deleted.add(oldpath) |
|
415 | deleted.add(oldpath) | |
416 | return added, modified, deleted |
|
416 | return added, modified, deleted | |
417 |
|
417 | |||
418 | def _get_paths_for_status(self, status): |
|
418 | def _get_paths_for_status(self, status): | |
419 | """ |
|
419 | """ | |
420 | Returns sorted list of paths for given ``status``. |
|
420 | Returns sorted list of paths for given ``status``. | |
421 |
|
421 | |||
422 | :param status: one of: *added*, *modified* or *deleted* |
|
422 | :param status: one of: *added*, *modified* or *deleted* | |
423 | """ |
|
423 | """ | |
424 | added, modified, deleted = self._changes_cache |
|
424 | added, modified, deleted = self._changes_cache | |
425 | return sorted({ |
|
425 | return sorted({ | |
426 | 'added': list(added), |
|
426 | 'added': list(added), | |
427 | 'modified': list(modified), |
|
427 | 'modified': list(modified), | |
428 | 'deleted': list(deleted)}[status] |
|
428 | 'deleted': list(deleted)}[status] | |
429 | ) |
|
429 | ) | |
430 |
|
430 | |||
431 | @LazyProperty |
|
431 | @LazyProperty | |
432 | def added(self): |
|
432 | def added(self): | |
433 | """ |
|
433 | """ | |
434 | Returns list of added ``FileNode`` objects. |
|
434 | Returns list of added ``FileNode`` objects. | |
435 | """ |
|
435 | """ | |
436 | if not self.parents: |
|
436 | if not self.parents: | |
437 | return list(self._get_file_nodes()) |
|
437 | return list(self._get_file_nodes()) | |
438 | return AddedFileNodesGenerator(self.added_paths, self) |
|
438 | return AddedFileNodesGenerator(self.added_paths, self) | |
439 |
|
439 | |||
440 | @LazyProperty |
|
440 | @LazyProperty | |
441 | def added_paths(self): |
|
441 | def added_paths(self): | |
442 | return [n for n in self._get_paths_for_status('added')] |
|
442 | return [n for n in self._get_paths_for_status('added')] | |
443 |
|
443 | |||
444 | @LazyProperty |
|
444 | @LazyProperty | |
445 | def changed(self): |
|
445 | def changed(self): | |
446 | """ |
|
446 | """ | |
447 | Returns list of modified ``FileNode`` objects. |
|
447 | Returns list of modified ``FileNode`` objects. | |
448 | """ |
|
448 | """ | |
449 | if not self.parents: |
|
449 | if not self.parents: | |
450 | return [] |
|
450 | return [] | |
451 | return ChangedFileNodesGenerator(self.changed_paths, self) |
|
451 | return ChangedFileNodesGenerator(self.changed_paths, self) | |
452 |
|
452 | |||
453 | @LazyProperty |
|
453 | @LazyProperty | |
454 | def changed_paths(self): |
|
454 | def changed_paths(self): | |
455 | return [n for n in self._get_paths_for_status('modified')] |
|
455 | return [n for n in self._get_paths_for_status('modified')] | |
456 |
|
456 | |||
457 | @LazyProperty |
|
457 | @LazyProperty | |
458 | def removed(self): |
|
458 | def removed(self): | |
459 | """ |
|
459 | """ | |
460 | Returns list of removed ``FileNode`` objects. |
|
460 | Returns list of removed ``FileNode`` objects. | |
461 | """ |
|
461 | """ | |
462 | if not self.parents: |
|
462 | if not self.parents: | |
463 | return [] |
|
463 | return [] | |
464 | return RemovedFileNodesGenerator(self.removed_paths, self) |
|
464 | return RemovedFileNodesGenerator(self.removed_paths, self) | |
465 |
|
465 | |||
466 | @LazyProperty |
|
466 | @LazyProperty | |
467 | def removed_paths(self): |
|
467 | def removed_paths(self): | |
468 | return [n for n in self._get_paths_for_status('deleted')] |
|
468 | return [n for n in self._get_paths_for_status('deleted')] | |
469 |
|
469 | |||
470 | def _get_submodule_url(self, submodule_path): |
|
470 | def _get_submodule_url(self, submodule_path): | |
471 | git_modules_path = '.gitmodules' |
|
471 | git_modules_path = '.gitmodules' | |
472 |
|
472 | |||
473 | if self._submodules is None: |
|
473 | if self._submodules is None: | |
474 | self._submodules = {} |
|
474 | self._submodules = {} | |
475 |
|
475 | |||
476 | try: |
|
476 | try: | |
477 | submodules_node = self.get_node(git_modules_path) |
|
477 | submodules_node = self.get_node(git_modules_path) | |
478 | except NodeDoesNotExistError: |
|
478 | except NodeDoesNotExistError: | |
479 | return None |
|
479 | return None | |
480 |
|
480 | |||
481 | # ConfigParser fails if there are whitespaces, also it needs an iterable |
|
481 | # ConfigParser fails if there are whitespaces, also it needs an iterable | |
482 | # file like content |
|
482 | # file like content | |
483 | def iter_content(_content): |
|
483 | def iter_content(_content): | |
484 | for line in _content.splitlines(): |
|
484 | for line in _content.splitlines(): | |
485 | yield line |
|
485 | yield line | |
486 |
|
486 | |||
487 | parser = configparser.RawConfigParser() |
|
487 | parser = configparser.RawConfigParser() | |
488 | parser.read_file(iter_content(submodules_node.content)) |
|
488 | parser.read_file(iter_content(submodules_node.content)) | |
489 |
|
489 | |||
490 | for section in parser.sections(): |
|
490 | for section in parser.sections(): | |
491 | path = parser.get(section, 'path') |
|
491 | path = parser.get(section, 'path') | |
492 | url = parser.get(section, 'url') |
|
492 | url = parser.get(section, 'url') | |
493 | if path and url: |
|
493 | if path and url: | |
494 | self._submodules[path.strip('/')] = url |
|
494 | self._submodules[path.strip('/')] = url | |
495 |
|
495 | |||
496 | return self._submodules.get(submodule_path.strip('/')) |
|
496 | return self._submodules.get(submodule_path.strip('/')) |
@@ -1,209 +1,209 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
|
2 | |||
3 | # Copyright (C) 2010-2020 RhodeCode GmbH |
|
3 | # Copyright (C) 2010-2020 RhodeCode GmbH | |
4 | # |
|
4 | # | |
5 | # This program is free software: you can redistribute it and/or modify |
|
5 | # This program is free software: you can redistribute it and/or modify | |
6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
6 | # it under the terms of the GNU Affero General Public License, version 3 | |
7 | # (only), as published by the Free Software Foundation. |
|
7 | # (only), as published by the Free Software Foundation. | |
8 | # |
|
8 | # | |
9 | # This program is distributed in the hope that it will be useful, |
|
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. |
|
12 | # GNU General Public License for more details. | |
13 | # |
|
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License |
|
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | # |
|
16 | # | |
17 | # This program is dual-licensed. If you wish to learn more about the |
|
17 | # This program is dual-licensed. If you wish to learn more about the | |
18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |
20 |
|
20 | |||
21 |
from |
|
21 | from io import StringIO | |
22 |
|
22 | |||
23 | import pytest |
|
23 | import pytest | |
24 | from mock import patch, Mock |
|
24 | from mock import patch, Mock | |
25 |
|
25 | |||
26 | from rhodecode.lib.middleware.simplesvn import SimpleSvn, SimpleSvnApp |
|
26 | from rhodecode.lib.middleware.simplesvn import SimpleSvn, SimpleSvnApp | |
27 | from rhodecode.lib.utils import get_rhodecode_base_path |
|
27 | from rhodecode.lib.utils import get_rhodecode_base_path | |
28 |
|
28 | |||
29 |
|
29 | |||
30 | class TestSimpleSvn(object): |
|
30 | class TestSimpleSvn(object): | |
31 | @pytest.fixture(autouse=True) |
|
31 | @pytest.fixture(autouse=True) | |
32 | def simple_svn(self, baseapp, request_stub): |
|
32 | def simple_svn(self, baseapp, request_stub): | |
33 | base_path = get_rhodecode_base_path() |
|
33 | base_path = get_rhodecode_base_path() | |
34 | self.app = SimpleSvn( |
|
34 | self.app = SimpleSvn( | |
35 | config={'auth_ret_code': '', 'base_path': base_path}, |
|
35 | config={'auth_ret_code': '', 'base_path': base_path}, | |
36 | registry=request_stub.registry) |
|
36 | registry=request_stub.registry) | |
37 |
|
37 | |||
38 | def test_get_config(self): |
|
38 | def test_get_config(self): | |
39 | extras = {'foo': 'FOO', 'bar': 'BAR'} |
|
39 | extras = {'foo': 'FOO', 'bar': 'BAR'} | |
40 | config = self.app._create_config(extras, repo_name='test-repo') |
|
40 | config = self.app._create_config(extras, repo_name='test-repo') | |
41 | assert config == extras |
|
41 | assert config == extras | |
42 |
|
42 | |||
43 | @pytest.mark.parametrize( |
|
43 | @pytest.mark.parametrize( | |
44 | 'method', ['OPTIONS', 'PROPFIND', 'GET', 'REPORT']) |
|
44 | 'method', ['OPTIONS', 'PROPFIND', 'GET', 'REPORT']) | |
45 | def test_get_action_returns_pull(self, method): |
|
45 | def test_get_action_returns_pull(self, method): | |
46 | environment = {'REQUEST_METHOD': method} |
|
46 | environment = {'REQUEST_METHOD': method} | |
47 | action = self.app._get_action(environment) |
|
47 | action = self.app._get_action(environment) | |
48 | assert action == 'pull' |
|
48 | assert action == 'pull' | |
49 |
|
49 | |||
50 | @pytest.mark.parametrize( |
|
50 | @pytest.mark.parametrize( | |
51 | 'method', [ |
|
51 | 'method', [ | |
52 | 'MKACTIVITY', 'PROPPATCH', 'PUT', 'CHECKOUT', 'MKCOL', 'MOVE', |
|
52 | 'MKACTIVITY', 'PROPPATCH', 'PUT', 'CHECKOUT', 'MKCOL', 'MOVE', | |
53 | 'COPY', 'DELETE', 'LOCK', 'UNLOCK', 'MERGE' |
|
53 | 'COPY', 'DELETE', 'LOCK', 'UNLOCK', 'MERGE' | |
54 | ]) |
|
54 | ]) | |
55 | def test_get_action_returns_push(self, method): |
|
55 | def test_get_action_returns_push(self, method): | |
56 | environment = {'REQUEST_METHOD': method} |
|
56 | environment = {'REQUEST_METHOD': method} | |
57 | action = self.app._get_action(environment) |
|
57 | action = self.app._get_action(environment) | |
58 | assert action == 'push' |
|
58 | assert action == 'push' | |
59 |
|
59 | |||
60 | @pytest.mark.parametrize( |
|
60 | @pytest.mark.parametrize( | |
61 | 'path, expected_name', [ |
|
61 | 'path, expected_name', [ | |
62 | ('/hello-svn', 'hello-svn'), |
|
62 | ('/hello-svn', 'hello-svn'), | |
63 | ('/hello-svn/', 'hello-svn'), |
|
63 | ('/hello-svn/', 'hello-svn'), | |
64 | ('/group/hello-svn/', 'group/hello-svn'), |
|
64 | ('/group/hello-svn/', 'group/hello-svn'), | |
65 | ('/group/hello-svn/!svn/vcc/default', 'group/hello-svn'), |
|
65 | ('/group/hello-svn/!svn/vcc/default', 'group/hello-svn'), | |
66 | ]) |
|
66 | ]) | |
67 | def test_get_repository_name(self, path, expected_name): |
|
67 | def test_get_repository_name(self, path, expected_name): | |
68 | environment = {'PATH_INFO': path} |
|
68 | environment = {'PATH_INFO': path} | |
69 | name = self.app._get_repository_name(environment) |
|
69 | name = self.app._get_repository_name(environment) | |
70 | assert name == expected_name |
|
70 | assert name == expected_name | |
71 |
|
71 | |||
72 | def test_get_repository_name_subfolder(self, backend_svn): |
|
72 | def test_get_repository_name_subfolder(self, backend_svn): | |
73 | repo = backend_svn.repo |
|
73 | repo = backend_svn.repo | |
74 | environment = { |
|
74 | environment = { | |
75 | 'PATH_INFO': '/{}/path/with/subfolders'.format(repo.repo_name)} |
|
75 | 'PATH_INFO': '/{}/path/with/subfolders'.format(repo.repo_name)} | |
76 | name = self.app._get_repository_name(environment) |
|
76 | name = self.app._get_repository_name(environment) | |
77 | assert name == repo.repo_name |
|
77 | assert name == repo.repo_name | |
78 |
|
78 | |||
79 | def test_create_wsgi_app(self): |
|
79 | def test_create_wsgi_app(self): | |
80 | with patch.object(SimpleSvn, '_is_svn_enabled') as mock_method: |
|
80 | with patch.object(SimpleSvn, '_is_svn_enabled') as mock_method: | |
81 | mock_method.return_value = False |
|
81 | mock_method.return_value = False | |
82 | with patch('rhodecode.lib.middleware.simplesvn.DisabledSimpleSvnApp') as ( |
|
82 | with patch('rhodecode.lib.middleware.simplesvn.DisabledSimpleSvnApp') as ( | |
83 | wsgi_app_mock): |
|
83 | wsgi_app_mock): | |
84 | config = Mock() |
|
84 | config = Mock() | |
85 | wsgi_app = self.app._create_wsgi_app( |
|
85 | wsgi_app = self.app._create_wsgi_app( | |
86 | repo_path='', repo_name='', config=config) |
|
86 | repo_path='', repo_name='', config=config) | |
87 |
|
87 | |||
88 | wsgi_app_mock.assert_called_once_with(config) |
|
88 | wsgi_app_mock.assert_called_once_with(config) | |
89 | assert wsgi_app == wsgi_app_mock() |
|
89 | assert wsgi_app == wsgi_app_mock() | |
90 |
|
90 | |||
91 | def test_create_wsgi_app_when_enabled(self): |
|
91 | def test_create_wsgi_app_when_enabled(self): | |
92 | with patch.object(SimpleSvn, '_is_svn_enabled') as mock_method: |
|
92 | with patch.object(SimpleSvn, '_is_svn_enabled') as mock_method: | |
93 | mock_method.return_value = True |
|
93 | mock_method.return_value = True | |
94 | with patch('rhodecode.lib.middleware.simplesvn.SimpleSvnApp') as ( |
|
94 | with patch('rhodecode.lib.middleware.simplesvn.SimpleSvnApp') as ( | |
95 | wsgi_app_mock): |
|
95 | wsgi_app_mock): | |
96 | config = Mock() |
|
96 | config = Mock() | |
97 | wsgi_app = self.app._create_wsgi_app( |
|
97 | wsgi_app = self.app._create_wsgi_app( | |
98 | repo_path='', repo_name='', config=config) |
|
98 | repo_path='', repo_name='', config=config) | |
99 |
|
99 | |||
100 | wsgi_app_mock.assert_called_once_with(config) |
|
100 | wsgi_app_mock.assert_called_once_with(config) | |
101 | assert wsgi_app == wsgi_app_mock() |
|
101 | assert wsgi_app == wsgi_app_mock() | |
102 |
|
102 | |||
103 |
|
103 | |||
104 | class TestSimpleSvnApp(object): |
|
104 | class TestSimpleSvnApp(object): | |
105 | data = '<xml></xml>' |
|
105 | data = '<xml></xml>' | |
106 | path = '/group/my-repo' |
|
106 | path = '/group/my-repo' | |
107 | wsgi_input = StringIO(data) |
|
107 | wsgi_input = StringIO(data) | |
108 | environment = { |
|
108 | environment = { | |
109 | 'HTTP_DAV': ( |
|
109 | 'HTTP_DAV': ( | |
110 | 'http://subversion.tigris.org/xmlns/dav/svn/depth,' |
|
110 | 'http://subversion.tigris.org/xmlns/dav/svn/depth,' | |
111 | ' http://subversion.tigris.org/xmlns/dav/svn/mergeinfo'), |
|
111 | ' http://subversion.tigris.org/xmlns/dav/svn/mergeinfo'), | |
112 | 'HTTP_USER_AGENT': 'SVN/1.8.11 (x86_64-linux) serf/1.3.8', |
|
112 | 'HTTP_USER_AGENT': 'SVN/1.8.11 (x86_64-linux) serf/1.3.8', | |
113 | 'REQUEST_METHOD': 'OPTIONS', |
|
113 | 'REQUEST_METHOD': 'OPTIONS', | |
114 | 'PATH_INFO': path, |
|
114 | 'PATH_INFO': path, | |
115 | 'wsgi.input': wsgi_input, |
|
115 | 'wsgi.input': wsgi_input, | |
116 | 'CONTENT_TYPE': 'text/xml', |
|
116 | 'CONTENT_TYPE': 'text/xml', | |
117 | 'CONTENT_LENGTH': '130' |
|
117 | 'CONTENT_LENGTH': '130' | |
118 | } |
|
118 | } | |
119 |
|
119 | |||
120 | def setup_method(self, method): |
|
120 | def setup_method(self, method): | |
121 | self.host = 'http://localhost/' |
|
121 | self.host = 'http://localhost/' | |
122 | base_path = get_rhodecode_base_path() |
|
122 | base_path = get_rhodecode_base_path() | |
123 | self.app = SimpleSvnApp( |
|
123 | self.app = SimpleSvnApp( | |
124 | config={'subversion_http_server_url': self.host, |
|
124 | config={'subversion_http_server_url': self.host, | |
125 | 'base_path': base_path}) |
|
125 | 'base_path': base_path}) | |
126 |
|
126 | |||
127 | def test_get_request_headers_with_content_type(self): |
|
127 | def test_get_request_headers_with_content_type(self): | |
128 | expected_headers = { |
|
128 | expected_headers = { | |
129 | 'Dav': self.environment['HTTP_DAV'], |
|
129 | 'Dav': self.environment['HTTP_DAV'], | |
130 | 'User-Agent': self.environment['HTTP_USER_AGENT'], |
|
130 | 'User-Agent': self.environment['HTTP_USER_AGENT'], | |
131 | 'Content-Type': self.environment['CONTENT_TYPE'], |
|
131 | 'Content-Type': self.environment['CONTENT_TYPE'], | |
132 | 'Content-Length': self.environment['CONTENT_LENGTH'] |
|
132 | 'Content-Length': self.environment['CONTENT_LENGTH'] | |
133 | } |
|
133 | } | |
134 | headers = self.app._get_request_headers(self.environment) |
|
134 | headers = self.app._get_request_headers(self.environment) | |
135 | assert headers == expected_headers |
|
135 | assert headers == expected_headers | |
136 |
|
136 | |||
137 | def test_get_request_headers_without_content_type(self): |
|
137 | def test_get_request_headers_without_content_type(self): | |
138 | environment = self.environment.copy() |
|
138 | environment = self.environment.copy() | |
139 | environment.pop('CONTENT_TYPE') |
|
139 | environment.pop('CONTENT_TYPE') | |
140 | expected_headers = { |
|
140 | expected_headers = { | |
141 | 'Dav': environment['HTTP_DAV'], |
|
141 | 'Dav': environment['HTTP_DAV'], | |
142 | 'Content-Length': self.environment['CONTENT_LENGTH'], |
|
142 | 'Content-Length': self.environment['CONTENT_LENGTH'], | |
143 | 'User-Agent': environment['HTTP_USER_AGENT'], |
|
143 | 'User-Agent': environment['HTTP_USER_AGENT'], | |
144 | } |
|
144 | } | |
145 | request_headers = self.app._get_request_headers(environment) |
|
145 | request_headers = self.app._get_request_headers(environment) | |
146 | assert request_headers == expected_headers |
|
146 | assert request_headers == expected_headers | |
147 |
|
147 | |||
148 | def test_get_response_headers(self): |
|
148 | def test_get_response_headers(self): | |
149 | headers = { |
|
149 | headers = { | |
150 | 'Connection': 'keep-alive', |
|
150 | 'Connection': 'keep-alive', | |
151 | 'Keep-Alive': 'timeout=5, max=100', |
|
151 | 'Keep-Alive': 'timeout=5, max=100', | |
152 | 'Transfer-Encoding': 'chunked', |
|
152 | 'Transfer-Encoding': 'chunked', | |
153 | 'Content-Encoding': 'gzip', |
|
153 | 'Content-Encoding': 'gzip', | |
154 | 'MS-Author-Via': 'DAV', |
|
154 | 'MS-Author-Via': 'DAV', | |
155 | 'SVN-Supported-Posts': 'create-txn-with-props' |
|
155 | 'SVN-Supported-Posts': 'create-txn-with-props' | |
156 | } |
|
156 | } | |
157 | expected_headers = [ |
|
157 | expected_headers = [ | |
158 | ('MS-Author-Via', 'DAV'), |
|
158 | ('MS-Author-Via', 'DAV'), | |
159 | ('SVN-Supported-Posts', 'create-txn-with-props'), |
|
159 | ('SVN-Supported-Posts', 'create-txn-with-props'), | |
160 | ] |
|
160 | ] | |
161 | response_headers = self.app._get_response_headers(headers) |
|
161 | response_headers = self.app._get_response_headers(headers) | |
162 | assert sorted(response_headers) == sorted(expected_headers) |
|
162 | assert sorted(response_headers) == sorted(expected_headers) | |
163 |
|
163 | |||
164 | @pytest.mark.parametrize('svn_http_url, path_info, expected_url', [ |
|
164 | @pytest.mark.parametrize('svn_http_url, path_info, expected_url', [ | |
165 | ('http://localhost:8200', '/repo_name', 'http://localhost:8200/repo_name'), |
|
165 | ('http://localhost:8200', '/repo_name', 'http://localhost:8200/repo_name'), | |
166 | ('http://localhost:8200///', '/repo_name', 'http://localhost:8200/repo_name'), |
|
166 | ('http://localhost:8200///', '/repo_name', 'http://localhost:8200/repo_name'), | |
167 | ('http://localhost:8200', '/group/repo_name', 'http://localhost:8200/group/repo_name'), |
|
167 | ('http://localhost:8200', '/group/repo_name', 'http://localhost:8200/group/repo_name'), | |
168 | ('http://localhost:8200/', '/group/repo_name', 'http://localhost:8200/group/repo_name'), |
|
168 | ('http://localhost:8200/', '/group/repo_name', 'http://localhost:8200/group/repo_name'), | |
169 | ('http://localhost:8200/prefix', '/repo_name', 'http://localhost:8200/prefix/repo_name'), |
|
169 | ('http://localhost:8200/prefix', '/repo_name', 'http://localhost:8200/prefix/repo_name'), | |
170 | ('http://localhost:8200/prefix', 'repo_name', 'http://localhost:8200/prefix/repo_name'), |
|
170 | ('http://localhost:8200/prefix', 'repo_name', 'http://localhost:8200/prefix/repo_name'), | |
171 | ('http://localhost:8200/prefix', '/group/repo_name', 'http://localhost:8200/prefix/group/repo_name') |
|
171 | ('http://localhost:8200/prefix', '/group/repo_name', 'http://localhost:8200/prefix/group/repo_name') | |
172 | ]) |
|
172 | ]) | |
173 | def test_get_url(self, svn_http_url, path_info, expected_url): |
|
173 | def test_get_url(self, svn_http_url, path_info, expected_url): | |
174 | url = self.app._get_url(svn_http_url, path_info) |
|
174 | url = self.app._get_url(svn_http_url, path_info) | |
175 | assert url == expected_url |
|
175 | assert url == expected_url | |
176 |
|
176 | |||
177 | def test_call(self): |
|
177 | def test_call(self): | |
178 | start_response = Mock() |
|
178 | start_response = Mock() | |
179 | response_mock = Mock() |
|
179 | response_mock = Mock() | |
180 | response_mock.headers = { |
|
180 | response_mock.headers = { | |
181 | 'Content-Encoding': 'gzip', |
|
181 | 'Content-Encoding': 'gzip', | |
182 | 'MS-Author-Via': 'DAV', |
|
182 | 'MS-Author-Via': 'DAV', | |
183 | 'SVN-Supported-Posts': 'create-txn-with-props' |
|
183 | 'SVN-Supported-Posts': 'create-txn-with-props' | |
184 | } |
|
184 | } | |
185 | response_mock.status_code = 200 |
|
185 | response_mock.status_code = 200 | |
186 | response_mock.reason = 'OK' |
|
186 | response_mock.reason = 'OK' | |
187 | with patch('rhodecode.lib.middleware.simplesvn.requests.request') as ( |
|
187 | with patch('rhodecode.lib.middleware.simplesvn.requests.request') as ( | |
188 | request_mock): |
|
188 | request_mock): | |
189 | request_mock.return_value = response_mock |
|
189 | request_mock.return_value = response_mock | |
190 | self.app(self.environment, start_response) |
|
190 | self.app(self.environment, start_response) | |
191 |
|
191 | |||
192 | expected_url = '{}{}'.format(self.host.strip('/'), self.path) |
|
192 | expected_url = '{}{}'.format(self.host.strip('/'), self.path) | |
193 | expected_request_headers = { |
|
193 | expected_request_headers = { | |
194 | 'Dav': self.environment['HTTP_DAV'], |
|
194 | 'Dav': self.environment['HTTP_DAV'], | |
195 | 'User-Agent': self.environment['HTTP_USER_AGENT'], |
|
195 | 'User-Agent': self.environment['HTTP_USER_AGENT'], | |
196 | 'Content-Type': self.environment['CONTENT_TYPE'], |
|
196 | 'Content-Type': self.environment['CONTENT_TYPE'], | |
197 | 'Content-Length': self.environment['CONTENT_LENGTH'] |
|
197 | 'Content-Length': self.environment['CONTENT_LENGTH'] | |
198 | } |
|
198 | } | |
199 | expected_response_headers = [ |
|
199 | expected_response_headers = [ | |
200 | ('SVN-Supported-Posts', 'create-txn-with-props'), |
|
200 | ('SVN-Supported-Posts', 'create-txn-with-props'), | |
201 | ('MS-Author-Via', 'DAV'), |
|
201 | ('MS-Author-Via', 'DAV'), | |
202 | ] |
|
202 | ] | |
203 | request_mock.assert_called_once_with( |
|
203 | request_mock.assert_called_once_with( | |
204 | self.environment['REQUEST_METHOD'], expected_url, |
|
204 | self.environment['REQUEST_METHOD'], expected_url, | |
205 | data=self.data, headers=expected_request_headers, stream=False) |
|
205 | data=self.data, headers=expected_request_headers, stream=False) | |
206 | response_mock.iter_content.assert_called_once_with(chunk_size=1024) |
|
206 | response_mock.iter_content.assert_called_once_with(chunk_size=1024) | |
207 | args, _ = start_response.call_args |
|
207 | args, _ = start_response.call_args | |
208 | assert args[0] == '200 OK' |
|
208 | assert args[0] == '200 OK' | |
209 | assert sorted(args[1]) == sorted(expected_response_headers) |
|
209 | assert sorted(args[1]) == sorted(expected_response_headers) |
@@ -1,342 +1,342 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
|
2 | |||
3 | # Copyright (C) 2010-2020 RhodeCode GmbH |
|
3 | # Copyright (C) 2010-2020 RhodeCode GmbH | |
4 | # |
|
4 | # | |
5 | # This program is free software: you can redistribute it and/or modify |
|
5 | # This program is free software: you can redistribute it and/or modify | |
6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
6 | # it under the terms of the GNU Affero General Public License, version 3 | |
7 | # (only), as published by the Free Software Foundation. |
|
7 | # (only), as published by the Free Software Foundation. | |
8 | # |
|
8 | # | |
9 | # This program is distributed in the hope that it will be useful, |
|
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. |
|
12 | # GNU General Public License for more details. | |
13 | # |
|
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License |
|
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | # |
|
16 | # | |
17 | # This program is dual-licensed. If you wish to learn more about the |
|
17 | # This program is dual-licensed. If you wish to learn more about the | |
18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |
20 |
|
20 | |||
21 | import json |
|
21 | import json | |
22 | import logging |
|
22 | import logging | |
23 |
from |
|
23 | from io import StringIO | |
24 |
|
24 | |||
25 | import mock |
|
25 | import mock | |
26 | import pytest |
|
26 | import pytest | |
27 |
|
27 | |||
28 | from rhodecode.lib import hooks_daemon |
|
28 | from rhodecode.lib import hooks_daemon | |
29 | from rhodecode.tests.utils import assert_message_in_log |
|
29 | from rhodecode.tests.utils import assert_message_in_log | |
30 |
|
30 | |||
31 |
|
31 | |||
32 | class TestDummyHooksCallbackDaemon(object): |
|
32 | class TestDummyHooksCallbackDaemon(object): | |
33 | def test_hooks_module_path_set_properly(self): |
|
33 | def test_hooks_module_path_set_properly(self): | |
34 | daemon = hooks_daemon.DummyHooksCallbackDaemon() |
|
34 | daemon = hooks_daemon.DummyHooksCallbackDaemon() | |
35 | assert daemon.hooks_module == 'rhodecode.lib.hooks_daemon' |
|
35 | assert daemon.hooks_module == 'rhodecode.lib.hooks_daemon' | |
36 |
|
36 | |||
37 | def test_logs_entering_the_hook(self): |
|
37 | def test_logs_entering_the_hook(self): | |
38 | daemon = hooks_daemon.DummyHooksCallbackDaemon() |
|
38 | daemon = hooks_daemon.DummyHooksCallbackDaemon() | |
39 | with mock.patch.object(hooks_daemon.log, 'debug') as log_mock: |
|
39 | with mock.patch.object(hooks_daemon.log, 'debug') as log_mock: | |
40 | with daemon as return_value: |
|
40 | with daemon as return_value: | |
41 | log_mock.assert_called_once_with( |
|
41 | log_mock.assert_called_once_with( | |
42 | 'Running `%s` callback daemon', 'DummyHooksCallbackDaemon') |
|
42 | 'Running `%s` callback daemon', 'DummyHooksCallbackDaemon') | |
43 | assert return_value == daemon |
|
43 | assert return_value == daemon | |
44 |
|
44 | |||
45 | def test_logs_exiting_the_hook(self): |
|
45 | def test_logs_exiting_the_hook(self): | |
46 | daemon = hooks_daemon.DummyHooksCallbackDaemon() |
|
46 | daemon = hooks_daemon.DummyHooksCallbackDaemon() | |
47 | with mock.patch.object(hooks_daemon.log, 'debug') as log_mock: |
|
47 | with mock.patch.object(hooks_daemon.log, 'debug') as log_mock: | |
48 | with daemon: |
|
48 | with daemon: | |
49 | pass |
|
49 | pass | |
50 | log_mock.assert_called_with( |
|
50 | log_mock.assert_called_with( | |
51 | 'Exiting `%s` callback daemon', 'DummyHooksCallbackDaemon') |
|
51 | 'Exiting `%s` callback daemon', 'DummyHooksCallbackDaemon') | |
52 |
|
52 | |||
53 |
|
53 | |||
54 | class TestHooks(object): |
|
54 | class TestHooks(object): | |
55 | def test_hooks_can_be_used_as_a_context_processor(self): |
|
55 | def test_hooks_can_be_used_as_a_context_processor(self): | |
56 | hooks = hooks_daemon.Hooks() |
|
56 | hooks = hooks_daemon.Hooks() | |
57 | with hooks as return_value: |
|
57 | with hooks as return_value: | |
58 | pass |
|
58 | pass | |
59 | assert hooks == return_value |
|
59 | assert hooks == return_value | |
60 |
|
60 | |||
61 |
|
61 | |||
62 | class TestHooksHttpHandler(object): |
|
62 | class TestHooksHttpHandler(object): | |
63 | def test_read_request_parses_method_name_and_arguments(self): |
|
63 | def test_read_request_parses_method_name_and_arguments(self): | |
64 | data = { |
|
64 | data = { | |
65 | 'method': 'test', |
|
65 | 'method': 'test', | |
66 | 'extras': { |
|
66 | 'extras': { | |
67 | 'param1': 1, |
|
67 | 'param1': 1, | |
68 | 'param2': 'a' |
|
68 | 'param2': 'a' | |
69 | } |
|
69 | } | |
70 | } |
|
70 | } | |
71 | request = self._generate_post_request(data) |
|
71 | request = self._generate_post_request(data) | |
72 | hooks_patcher = mock.patch.object( |
|
72 | hooks_patcher = mock.patch.object( | |
73 | hooks_daemon.Hooks, data['method'], create=True, return_value=1) |
|
73 | hooks_daemon.Hooks, data['method'], create=True, return_value=1) | |
74 |
|
74 | |||
75 | with hooks_patcher as hooks_mock: |
|
75 | with hooks_patcher as hooks_mock: | |
76 | MockServer(hooks_daemon.HooksHttpHandler, request) |
|
76 | MockServer(hooks_daemon.HooksHttpHandler, request) | |
77 |
|
77 | |||
78 | hooks_mock.assert_called_once_with(data['extras']) |
|
78 | hooks_mock.assert_called_once_with(data['extras']) | |
79 |
|
79 | |||
80 | def test_hooks_serialized_result_is_returned(self): |
|
80 | def test_hooks_serialized_result_is_returned(self): | |
81 | request = self._generate_post_request({}) |
|
81 | request = self._generate_post_request({}) | |
82 | rpc_method = 'test' |
|
82 | rpc_method = 'test' | |
83 | hook_result = { |
|
83 | hook_result = { | |
84 | 'first': 'one', |
|
84 | 'first': 'one', | |
85 | 'second': 2 |
|
85 | 'second': 2 | |
86 | } |
|
86 | } | |
87 | read_patcher = mock.patch.object( |
|
87 | read_patcher = mock.patch.object( | |
88 | hooks_daemon.HooksHttpHandler, '_read_request', |
|
88 | hooks_daemon.HooksHttpHandler, '_read_request', | |
89 | return_value=(rpc_method, {})) |
|
89 | return_value=(rpc_method, {})) | |
90 | hooks_patcher = mock.patch.object( |
|
90 | hooks_patcher = mock.patch.object( | |
91 | hooks_daemon.Hooks, rpc_method, create=True, |
|
91 | hooks_daemon.Hooks, rpc_method, create=True, | |
92 | return_value=hook_result) |
|
92 | return_value=hook_result) | |
93 |
|
93 | |||
94 | with read_patcher, hooks_patcher: |
|
94 | with read_patcher, hooks_patcher: | |
95 | server = MockServer(hooks_daemon.HooksHttpHandler, request) |
|
95 | server = MockServer(hooks_daemon.HooksHttpHandler, request) | |
96 |
|
96 | |||
97 | expected_result = json.dumps(hook_result) |
|
97 | expected_result = json.dumps(hook_result) | |
98 | assert server.request.output_stream.buflist[-1] == expected_result |
|
98 | assert server.request.output_stream.buflist[-1] == expected_result | |
99 |
|
99 | |||
100 | def test_exception_is_returned_in_response(self): |
|
100 | def test_exception_is_returned_in_response(self): | |
101 | request = self._generate_post_request({}) |
|
101 | request = self._generate_post_request({}) | |
102 | rpc_method = 'test' |
|
102 | rpc_method = 'test' | |
103 | read_patcher = mock.patch.object( |
|
103 | read_patcher = mock.patch.object( | |
104 | hooks_daemon.HooksHttpHandler, '_read_request', |
|
104 | hooks_daemon.HooksHttpHandler, '_read_request', | |
105 | return_value=(rpc_method, {})) |
|
105 | return_value=(rpc_method, {})) | |
106 | hooks_patcher = mock.patch.object( |
|
106 | hooks_patcher = mock.patch.object( | |
107 | hooks_daemon.Hooks, rpc_method, create=True, |
|
107 | hooks_daemon.Hooks, rpc_method, create=True, | |
108 | side_effect=Exception('Test exception')) |
|
108 | side_effect=Exception('Test exception')) | |
109 |
|
109 | |||
110 | with read_patcher, hooks_patcher: |
|
110 | with read_patcher, hooks_patcher: | |
111 | server = MockServer(hooks_daemon.HooksHttpHandler, request) |
|
111 | server = MockServer(hooks_daemon.HooksHttpHandler, request) | |
112 |
|
112 | |||
113 | org_exc = json.loads(server.request.output_stream.buflist[-1]) |
|
113 | org_exc = json.loads(server.request.output_stream.buflist[-1]) | |
114 | expected_result = { |
|
114 | expected_result = { | |
115 | 'exception': 'Exception', |
|
115 | 'exception': 'Exception', | |
116 | 'exception_traceback': org_exc['exception_traceback'], |
|
116 | 'exception_traceback': org_exc['exception_traceback'], | |
117 | 'exception_args': ['Test exception'] |
|
117 | 'exception_args': ['Test exception'] | |
118 | } |
|
118 | } | |
119 | assert org_exc == expected_result |
|
119 | assert org_exc == expected_result | |
120 |
|
120 | |||
121 | def test_log_message_writes_to_debug_log(self, caplog): |
|
121 | def test_log_message_writes_to_debug_log(self, caplog): | |
122 | ip_port = ('0.0.0.0', 8888) |
|
122 | ip_port = ('0.0.0.0', 8888) | |
123 | handler = hooks_daemon.HooksHttpHandler( |
|
123 | handler = hooks_daemon.HooksHttpHandler( | |
124 | MockRequest('POST /'), ip_port, mock.Mock()) |
|
124 | MockRequest('POST /'), ip_port, mock.Mock()) | |
125 | fake_date = '1/Nov/2015 00:00:00' |
|
125 | fake_date = '1/Nov/2015 00:00:00' | |
126 | date_patcher = mock.patch.object( |
|
126 | date_patcher = mock.patch.object( | |
127 | handler, 'log_date_time_string', return_value=fake_date) |
|
127 | handler, 'log_date_time_string', return_value=fake_date) | |
128 | with date_patcher, caplog.at_level(logging.DEBUG): |
|
128 | with date_patcher, caplog.at_level(logging.DEBUG): | |
129 | handler.log_message('Some message %d, %s', 123, 'string') |
|
129 | handler.log_message('Some message %d, %s', 123, 'string') | |
130 |
|
130 | |||
131 | expected_message = "HOOKS: {} - - [{}] Some message 123, string".format(ip_port, fake_date) |
|
131 | expected_message = "HOOKS: {} - - [{}] Some message 123, string".format(ip_port, fake_date) | |
132 | assert_message_in_log( |
|
132 | assert_message_in_log( | |
133 | caplog.records, expected_message, |
|
133 | caplog.records, expected_message, | |
134 | levelno=logging.DEBUG, module='hooks_daemon') |
|
134 | levelno=logging.DEBUG, module='hooks_daemon') | |
135 |
|
135 | |||
136 | def _generate_post_request(self, data): |
|
136 | def _generate_post_request(self, data): | |
137 | payload = json.dumps(data) |
|
137 | payload = json.dumps(data) | |
138 | return 'POST / HTTP/1.0\nContent-Length: {}\n\n{}'.format( |
|
138 | return 'POST / HTTP/1.0\nContent-Length: {}\n\n{}'.format( | |
139 | len(payload), payload) |
|
139 | len(payload), payload) | |
140 |
|
140 | |||
141 |
|
141 | |||
142 | class ThreadedHookCallbackDaemon(object): |
|
142 | class ThreadedHookCallbackDaemon(object): | |
143 | def test_constructor_calls_prepare(self): |
|
143 | def test_constructor_calls_prepare(self): | |
144 | prepare_daemon_patcher = mock.patch.object( |
|
144 | prepare_daemon_patcher = mock.patch.object( | |
145 | hooks_daemon.ThreadedHookCallbackDaemon, '_prepare') |
|
145 | hooks_daemon.ThreadedHookCallbackDaemon, '_prepare') | |
146 | with prepare_daemon_patcher as prepare_daemon_mock: |
|
146 | with prepare_daemon_patcher as prepare_daemon_mock: | |
147 | hooks_daemon.ThreadedHookCallbackDaemon() |
|
147 | hooks_daemon.ThreadedHookCallbackDaemon() | |
148 | prepare_daemon_mock.assert_called_once_with() |
|
148 | prepare_daemon_mock.assert_called_once_with() | |
149 |
|
149 | |||
150 | def test_run_is_called_on_context_start(self): |
|
150 | def test_run_is_called_on_context_start(self): | |
151 | patchers = mock.patch.multiple( |
|
151 | patchers = mock.patch.multiple( | |
152 | hooks_daemon.ThreadedHookCallbackDaemon, |
|
152 | hooks_daemon.ThreadedHookCallbackDaemon, | |
153 | _run=mock.DEFAULT, _prepare=mock.DEFAULT, __exit__=mock.DEFAULT) |
|
153 | _run=mock.DEFAULT, _prepare=mock.DEFAULT, __exit__=mock.DEFAULT) | |
154 |
|
154 | |||
155 | with patchers as mocks: |
|
155 | with patchers as mocks: | |
156 | daemon = hooks_daemon.ThreadedHookCallbackDaemon() |
|
156 | daemon = hooks_daemon.ThreadedHookCallbackDaemon() | |
157 | with daemon as daemon_context: |
|
157 | with daemon as daemon_context: | |
158 | pass |
|
158 | pass | |
159 | mocks['_run'].assert_called_once_with() |
|
159 | mocks['_run'].assert_called_once_with() | |
160 | assert daemon_context == daemon |
|
160 | assert daemon_context == daemon | |
161 |
|
161 | |||
162 | def test_stop_is_called_on_context_exit(self): |
|
162 | def test_stop_is_called_on_context_exit(self): | |
163 | patchers = mock.patch.multiple( |
|
163 | patchers = mock.patch.multiple( | |
164 | hooks_daemon.ThreadedHookCallbackDaemon, |
|
164 | hooks_daemon.ThreadedHookCallbackDaemon, | |
165 | _run=mock.DEFAULT, _prepare=mock.DEFAULT, _stop=mock.DEFAULT) |
|
165 | _run=mock.DEFAULT, _prepare=mock.DEFAULT, _stop=mock.DEFAULT) | |
166 |
|
166 | |||
167 | with patchers as mocks: |
|
167 | with patchers as mocks: | |
168 | daemon = hooks_daemon.ThreadedHookCallbackDaemon() |
|
168 | daemon = hooks_daemon.ThreadedHookCallbackDaemon() | |
169 | with daemon as daemon_context: |
|
169 | with daemon as daemon_context: | |
170 | assert mocks['_stop'].call_count == 0 |
|
170 | assert mocks['_stop'].call_count == 0 | |
171 |
|
171 | |||
172 | mocks['_stop'].assert_called_once_with() |
|
172 | mocks['_stop'].assert_called_once_with() | |
173 | assert daemon_context == daemon |
|
173 | assert daemon_context == daemon | |
174 |
|
174 | |||
175 |
|
175 | |||
176 | class TestHttpHooksCallbackDaemon(object): |
|
176 | class TestHttpHooksCallbackDaemon(object): | |
177 | def test_hooks_callback_generates_new_port(self, caplog): |
|
177 | def test_hooks_callback_generates_new_port(self, caplog): | |
178 | with caplog.at_level(logging.DEBUG): |
|
178 | with caplog.at_level(logging.DEBUG): | |
179 | daemon = hooks_daemon.HttpHooksCallbackDaemon(host='127.0.0.1', port=8881) |
|
179 | daemon = hooks_daemon.HttpHooksCallbackDaemon(host='127.0.0.1', port=8881) | |
180 | assert daemon._daemon.server_address == ('127.0.0.1', 8881) |
|
180 | assert daemon._daemon.server_address == ('127.0.0.1', 8881) | |
181 |
|
181 | |||
182 | with caplog.at_level(logging.DEBUG): |
|
182 | with caplog.at_level(logging.DEBUG): | |
183 | daemon = hooks_daemon.HttpHooksCallbackDaemon(host=None, port=None) |
|
183 | daemon = hooks_daemon.HttpHooksCallbackDaemon(host=None, port=None) | |
184 | assert daemon._daemon.server_address[1] in range(0, 66000) |
|
184 | assert daemon._daemon.server_address[1] in range(0, 66000) | |
185 | assert daemon._daemon.server_address[0] != '127.0.0.1' |
|
185 | assert daemon._daemon.server_address[0] != '127.0.0.1' | |
186 |
|
186 | |||
187 | def test_prepare_inits_daemon_variable(self, tcp_server, caplog): |
|
187 | def test_prepare_inits_daemon_variable(self, tcp_server, caplog): | |
188 | with self._tcp_patcher(tcp_server), caplog.at_level(logging.DEBUG): |
|
188 | with self._tcp_patcher(tcp_server), caplog.at_level(logging.DEBUG): | |
189 | daemon = hooks_daemon.HttpHooksCallbackDaemon(host='127.0.0.1', port=8881) |
|
189 | daemon = hooks_daemon.HttpHooksCallbackDaemon(host='127.0.0.1', port=8881) | |
190 | assert daemon._daemon == tcp_server |
|
190 | assert daemon._daemon == tcp_server | |
191 |
|
191 | |||
192 | _, port = tcp_server.server_address |
|
192 | _, port = tcp_server.server_address | |
193 | expected_uri = '{}:{}'.format('127.0.0.1', port) |
|
193 | expected_uri = '{}:{}'.format('127.0.0.1', port) | |
194 | msg = 'HOOKS: {} Preparing HTTP callback daemon registering ' \ |
|
194 | msg = 'HOOKS: {} Preparing HTTP callback daemon registering ' \ | |
195 | 'hook object: rhodecode.lib.hooks_daemon.HooksHttpHandler'.format(expected_uri) |
|
195 | 'hook object: rhodecode.lib.hooks_daemon.HooksHttpHandler'.format(expected_uri) | |
196 | assert_message_in_log( |
|
196 | assert_message_in_log( | |
197 | caplog.records, msg, levelno=logging.DEBUG, module='hooks_daemon') |
|
197 | caplog.records, msg, levelno=logging.DEBUG, module='hooks_daemon') | |
198 |
|
198 | |||
199 | def test_prepare_inits_hooks_uri_and_logs_it( |
|
199 | def test_prepare_inits_hooks_uri_and_logs_it( | |
200 | self, tcp_server, caplog): |
|
200 | self, tcp_server, caplog): | |
201 | with self._tcp_patcher(tcp_server), caplog.at_level(logging.DEBUG): |
|
201 | with self._tcp_patcher(tcp_server), caplog.at_level(logging.DEBUG): | |
202 | daemon = hooks_daemon.HttpHooksCallbackDaemon(host='127.0.0.1', port=8881) |
|
202 | daemon = hooks_daemon.HttpHooksCallbackDaemon(host='127.0.0.1', port=8881) | |
203 |
|
203 | |||
204 | _, port = tcp_server.server_address |
|
204 | _, port = tcp_server.server_address | |
205 | expected_uri = '{}:{}'.format('127.0.0.1', port) |
|
205 | expected_uri = '{}:{}'.format('127.0.0.1', port) | |
206 | assert daemon.hooks_uri == expected_uri |
|
206 | assert daemon.hooks_uri == expected_uri | |
207 |
|
207 | |||
208 | msg = 'HOOKS: {} Preparing HTTP callback daemon registering ' \ |
|
208 | msg = 'HOOKS: {} Preparing HTTP callback daemon registering ' \ | |
209 | 'hook object: rhodecode.lib.hooks_daemon.HooksHttpHandler'.format(expected_uri) |
|
209 | 'hook object: rhodecode.lib.hooks_daemon.HooksHttpHandler'.format(expected_uri) | |
210 | assert_message_in_log( |
|
210 | assert_message_in_log( | |
211 | caplog.records, msg, |
|
211 | caplog.records, msg, | |
212 | levelno=logging.DEBUG, module='hooks_daemon') |
|
212 | levelno=logging.DEBUG, module='hooks_daemon') | |
213 |
|
213 | |||
214 | def test_run_creates_a_thread(self, tcp_server): |
|
214 | def test_run_creates_a_thread(self, tcp_server): | |
215 | thread = mock.Mock() |
|
215 | thread = mock.Mock() | |
216 |
|
216 | |||
217 | with self._tcp_patcher(tcp_server): |
|
217 | with self._tcp_patcher(tcp_server): | |
218 | daemon = hooks_daemon.HttpHooksCallbackDaemon() |
|
218 | daemon = hooks_daemon.HttpHooksCallbackDaemon() | |
219 |
|
219 | |||
220 | with self._thread_patcher(thread) as thread_mock: |
|
220 | with self._thread_patcher(thread) as thread_mock: | |
221 | daemon._run() |
|
221 | daemon._run() | |
222 |
|
222 | |||
223 | thread_mock.assert_called_once_with( |
|
223 | thread_mock.assert_called_once_with( | |
224 | target=tcp_server.serve_forever, |
|
224 | target=tcp_server.serve_forever, | |
225 | kwargs={'poll_interval': daemon.POLL_INTERVAL}) |
|
225 | kwargs={'poll_interval': daemon.POLL_INTERVAL}) | |
226 | assert thread.daemon is True |
|
226 | assert thread.daemon is True | |
227 | thread.start.assert_called_once_with() |
|
227 | thread.start.assert_called_once_with() | |
228 |
|
228 | |||
229 | def test_run_logs(self, tcp_server, caplog): |
|
229 | def test_run_logs(self, tcp_server, caplog): | |
230 |
|
230 | |||
231 | with self._tcp_patcher(tcp_server): |
|
231 | with self._tcp_patcher(tcp_server): | |
232 | daemon = hooks_daemon.HttpHooksCallbackDaemon() |
|
232 | daemon = hooks_daemon.HttpHooksCallbackDaemon() | |
233 |
|
233 | |||
234 | with self._thread_patcher(mock.Mock()), caplog.at_level(logging.DEBUG): |
|
234 | with self._thread_patcher(mock.Mock()), caplog.at_level(logging.DEBUG): | |
235 | daemon._run() |
|
235 | daemon._run() | |
236 |
|
236 | |||
237 | assert_message_in_log( |
|
237 | assert_message_in_log( | |
238 | caplog.records, |
|
238 | caplog.records, | |
239 | 'Running event loop of callback daemon in background thread', |
|
239 | 'Running event loop of callback daemon in background thread', | |
240 | levelno=logging.DEBUG, module='hooks_daemon') |
|
240 | levelno=logging.DEBUG, module='hooks_daemon') | |
241 |
|
241 | |||
242 | def test_stop_cleans_up_the_connection(self, tcp_server, caplog): |
|
242 | def test_stop_cleans_up_the_connection(self, tcp_server, caplog): | |
243 | thread = mock.Mock() |
|
243 | thread = mock.Mock() | |
244 |
|
244 | |||
245 | with self._tcp_patcher(tcp_server): |
|
245 | with self._tcp_patcher(tcp_server): | |
246 | daemon = hooks_daemon.HttpHooksCallbackDaemon() |
|
246 | daemon = hooks_daemon.HttpHooksCallbackDaemon() | |
247 |
|
247 | |||
248 | with self._thread_patcher(thread), caplog.at_level(logging.DEBUG): |
|
248 | with self._thread_patcher(thread), caplog.at_level(logging.DEBUG): | |
249 | with daemon: |
|
249 | with daemon: | |
250 | assert daemon._daemon == tcp_server |
|
250 | assert daemon._daemon == tcp_server | |
251 | assert daemon._callback_thread == thread |
|
251 | assert daemon._callback_thread == thread | |
252 |
|
252 | |||
253 | assert daemon._daemon is None |
|
253 | assert daemon._daemon is None | |
254 | assert daemon._callback_thread is None |
|
254 | assert daemon._callback_thread is None | |
255 | tcp_server.shutdown.assert_called_with() |
|
255 | tcp_server.shutdown.assert_called_with() | |
256 | thread.join.assert_called_once_with() |
|
256 | thread.join.assert_called_once_with() | |
257 |
|
257 | |||
258 | assert_message_in_log( |
|
258 | assert_message_in_log( | |
259 | caplog.records, 'Waiting for background thread to finish.', |
|
259 | caplog.records, 'Waiting for background thread to finish.', | |
260 | levelno=logging.DEBUG, module='hooks_daemon') |
|
260 | levelno=logging.DEBUG, module='hooks_daemon') | |
261 |
|
261 | |||
262 | def _tcp_patcher(self, tcp_server): |
|
262 | def _tcp_patcher(self, tcp_server): | |
263 | return mock.patch.object( |
|
263 | return mock.patch.object( | |
264 | hooks_daemon, 'TCPServer', return_value=tcp_server) |
|
264 | hooks_daemon, 'TCPServer', return_value=tcp_server) | |
265 |
|
265 | |||
266 | def _thread_patcher(self, thread): |
|
266 | def _thread_patcher(self, thread): | |
267 | return mock.patch.object( |
|
267 | return mock.patch.object( | |
268 | hooks_daemon.threading, 'Thread', return_value=thread) |
|
268 | hooks_daemon.threading, 'Thread', return_value=thread) | |
269 |
|
269 | |||
270 |
|
270 | |||
271 | class TestPrepareHooksDaemon(object): |
|
271 | class TestPrepareHooksDaemon(object): | |
272 | @pytest.mark.parametrize('protocol', ('http',)) |
|
272 | @pytest.mark.parametrize('protocol', ('http',)) | |
273 | def test_returns_dummy_hooks_callback_daemon_when_using_direct_calls( |
|
273 | def test_returns_dummy_hooks_callback_daemon_when_using_direct_calls( | |
274 | self, protocol): |
|
274 | self, protocol): | |
275 | expected_extras = {'extra1': 'value1'} |
|
275 | expected_extras = {'extra1': 'value1'} | |
276 | callback, extras = hooks_daemon.prepare_callback_daemon( |
|
276 | callback, extras = hooks_daemon.prepare_callback_daemon( | |
277 | expected_extras.copy(), protocol=protocol, |
|
277 | expected_extras.copy(), protocol=protocol, | |
278 | host='127.0.0.1', use_direct_calls=True) |
|
278 | host='127.0.0.1', use_direct_calls=True) | |
279 | assert isinstance(callback, hooks_daemon.DummyHooksCallbackDaemon) |
|
279 | assert isinstance(callback, hooks_daemon.DummyHooksCallbackDaemon) | |
280 | expected_extras['hooks_module'] = 'rhodecode.lib.hooks_daemon' |
|
280 | expected_extras['hooks_module'] = 'rhodecode.lib.hooks_daemon' | |
281 | expected_extras['time'] = extras['time'] |
|
281 | expected_extras['time'] = extras['time'] | |
282 | assert 'extra1' in extras |
|
282 | assert 'extra1' in extras | |
283 |
|
283 | |||
284 | @pytest.mark.parametrize('protocol, expected_class', ( |
|
284 | @pytest.mark.parametrize('protocol, expected_class', ( | |
285 | ('http', hooks_daemon.HttpHooksCallbackDaemon), |
|
285 | ('http', hooks_daemon.HttpHooksCallbackDaemon), | |
286 | )) |
|
286 | )) | |
287 | def test_returns_real_hooks_callback_daemon_when_protocol_is_specified( |
|
287 | def test_returns_real_hooks_callback_daemon_when_protocol_is_specified( | |
288 | self, protocol, expected_class): |
|
288 | self, protocol, expected_class): | |
289 | expected_extras = { |
|
289 | expected_extras = { | |
290 | 'extra1': 'value1', |
|
290 | 'extra1': 'value1', | |
291 | 'txn_id': 'txnid2', |
|
291 | 'txn_id': 'txnid2', | |
292 | 'hooks_protocol': protocol.lower() |
|
292 | 'hooks_protocol': protocol.lower() | |
293 | } |
|
293 | } | |
294 | callback, extras = hooks_daemon.prepare_callback_daemon( |
|
294 | callback, extras = hooks_daemon.prepare_callback_daemon( | |
295 | expected_extras.copy(), protocol=protocol, host='127.0.0.1', |
|
295 | expected_extras.copy(), protocol=protocol, host='127.0.0.1', | |
296 | use_direct_calls=False, |
|
296 | use_direct_calls=False, | |
297 | txn_id='txnid2') |
|
297 | txn_id='txnid2') | |
298 | assert isinstance(callback, expected_class) |
|
298 | assert isinstance(callback, expected_class) | |
299 | extras.pop('hooks_uri') |
|
299 | extras.pop('hooks_uri') | |
300 | expected_extras['time'] = extras['time'] |
|
300 | expected_extras['time'] = extras['time'] | |
301 | assert extras == expected_extras |
|
301 | assert extras == expected_extras | |
302 |
|
302 | |||
303 | @pytest.mark.parametrize('protocol', ( |
|
303 | @pytest.mark.parametrize('protocol', ( | |
304 | 'invalid', |
|
304 | 'invalid', | |
305 | 'Http', |
|
305 | 'Http', | |
306 | 'HTTP', |
|
306 | 'HTTP', | |
307 | )) |
|
307 | )) | |
308 | def test_raises_on_invalid_protocol(self, protocol): |
|
308 | def test_raises_on_invalid_protocol(self, protocol): | |
309 | expected_extras = { |
|
309 | expected_extras = { | |
310 | 'extra1': 'value1', |
|
310 | 'extra1': 'value1', | |
311 | 'hooks_protocol': protocol.lower() |
|
311 | 'hooks_protocol': protocol.lower() | |
312 | } |
|
312 | } | |
313 | with pytest.raises(Exception): |
|
313 | with pytest.raises(Exception): | |
314 | callback, extras = hooks_daemon.prepare_callback_daemon( |
|
314 | callback, extras = hooks_daemon.prepare_callback_daemon( | |
315 | expected_extras.copy(), |
|
315 | expected_extras.copy(), | |
316 | protocol=protocol, host='127.0.0.1', |
|
316 | protocol=protocol, host='127.0.0.1', | |
317 | use_direct_calls=False) |
|
317 | use_direct_calls=False) | |
318 |
|
318 | |||
319 |
|
319 | |||
320 | class MockRequest(object): |
|
320 | class MockRequest(object): | |
321 | def __init__(self, request): |
|
321 | def __init__(self, request): | |
322 | self.request = request |
|
322 | self.request = request | |
323 | self.input_stream = StringIO(b'{}'.format(self.request)) |
|
323 | self.input_stream = StringIO(b'{}'.format(self.request)) | |
324 | self.output_stream = StringIO() |
|
324 | self.output_stream = StringIO() | |
325 |
|
325 | |||
326 | def makefile(self, mode, *args, **kwargs): |
|
326 | def makefile(self, mode, *args, **kwargs): | |
327 | return self.output_stream if mode == 'wb' else self.input_stream |
|
327 | return self.output_stream if mode == 'wb' else self.input_stream | |
328 |
|
328 | |||
329 |
|
329 | |||
330 | class MockServer(object): |
|
330 | class MockServer(object): | |
331 | def __init__(self, handler_cls, request): |
|
331 | def __init__(self, handler_cls, request): | |
332 | ip_port = ('0.0.0.0', 8888) |
|
332 | ip_port = ('0.0.0.0', 8888) | |
333 | self.request = MockRequest(request) |
|
333 | self.request = MockRequest(request) | |
334 | self.server_address = ip_port |
|
334 | self.server_address = ip_port | |
335 | self.handler = handler_cls(self.request, ip_port, self) |
|
335 | self.handler = handler_cls(self.request, ip_port, self) | |
336 |
|
336 | |||
337 |
|
337 | |||
338 | @pytest.fixture() |
|
338 | @pytest.fixture() | |
339 | def tcp_server(): |
|
339 | def tcp_server(): | |
340 | server = mock.Mock() |
|
340 | server = mock.Mock() | |
341 | server.server_address = ('127.0.0.1', 8881) |
|
341 | server.server_address = ('127.0.0.1', 8881) | |
342 | return server |
|
342 | return server |
@@ -1,176 +1,176 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 |
|
2 | |||
3 | # Copyright (C) 2010-2020 RhodeCode GmbH |
|
3 | # Copyright (C) 2010-2020 RhodeCode GmbH | |
4 | # |
|
4 | # | |
5 | # This program is free software: you can redistribute it and/or modify |
|
5 | # This program is free software: you can redistribute it and/or modify | |
6 | # it under the terms of the GNU Affero General Public License, version 3 |
|
6 | # it under the terms of the GNU Affero General Public License, version 3 | |
7 | # (only), as published by the Free Software Foundation. |
|
7 | # (only), as published by the Free Software Foundation. | |
8 | # |
|
8 | # | |
9 | # This program is distributed in the hope that it will be useful, |
|
9 | # This program is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. |
|
12 | # GNU General Public License for more details. | |
13 | # |
|
13 | # | |
14 | # You should have received a copy of the GNU Affero General Public License |
|
14 | # You should have received a copy of the GNU Affero General Public License | |
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
15 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
16 | # |
|
16 | # | |
17 | # This program is dual-licensed. If you wish to learn more about the |
|
17 | # This program is dual-licensed. If you wish to learn more about the | |
18 | # RhodeCode Enterprise Edition, including its added features, Support services, |
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ |
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |
20 |
|
20 | |||
21 | import datetime |
|
21 | import datetime | |
22 | import os |
|
22 | import os | |
23 | import shutil |
|
23 | import shutil | |
24 | import tarfile |
|
24 | import tarfile | |
25 | import tempfile |
|
25 | import tempfile | |
26 | import zipfile |
|
26 | import zipfile | |
27 | import StringIO |
|
27 | from io import StringIO | |
28 |
|
28 | |||
29 | import mock |
|
29 | import mock | |
30 | import pytest |
|
30 | import pytest | |
31 |
|
31 | |||
32 | from rhodecode.lib.vcs.backends import base |
|
32 | from rhodecode.lib.vcs.backends import base | |
33 | from rhodecode.lib.vcs.exceptions import ImproperArchiveTypeError, VCSError |
|
33 | from rhodecode.lib.vcs.exceptions import ImproperArchiveTypeError, VCSError | |
34 | from rhodecode.lib.vcs.nodes import FileNode |
|
34 | from rhodecode.lib.vcs.nodes import FileNode | |
35 | from rhodecode.tests.vcs.conftest import BackendTestMixin |
|
35 | from rhodecode.tests.vcs.conftest import BackendTestMixin | |
36 |
|
36 | |||
37 |
|
37 | |||
38 | @pytest.mark.usefixtures("vcs_repository_support") |
|
38 | @pytest.mark.usefixtures("vcs_repository_support") | |
39 | class TestArchives(BackendTestMixin): |
|
39 | class TestArchives(BackendTestMixin): | |
40 |
|
40 | |||
41 | @pytest.fixture(autouse=True) |
|
41 | @pytest.fixture(autouse=True) | |
42 | def tempfile(self, request): |
|
42 | def tempfile(self, request): | |
43 | self.temp_file = tempfile.mkstemp()[1] |
|
43 | self.temp_file = tempfile.mkstemp()[1] | |
44 |
|
44 | |||
45 | @request.addfinalizer |
|
45 | @request.addfinalizer | |
46 | def cleanup(): |
|
46 | def cleanup(): | |
47 | os.remove(self.temp_file) |
|
47 | os.remove(self.temp_file) | |
48 |
|
48 | |||
49 | @classmethod |
|
49 | @classmethod | |
50 | def _get_commits(cls): |
|
50 | def _get_commits(cls): | |
51 | start_date = datetime.datetime(2010, 1, 1, 20) |
|
51 | start_date = datetime.datetime(2010, 1, 1, 20) | |
52 | yield { |
|
52 | yield { | |
53 | 'message': 'Initial Commit', |
|
53 | 'message': 'Initial Commit', | |
54 | 'author': 'Joe Doe <joe.doe@example.com>', |
|
54 | 'author': 'Joe Doe <joe.doe@example.com>', | |
55 | 'date': start_date + datetime.timedelta(hours=12), |
|
55 | 'date': start_date + datetime.timedelta(hours=12), | |
56 | 'added': [ |
|
56 | 'added': [ | |
57 | FileNode('executable_0o100755', '...', mode=0o100755), |
|
57 | FileNode('executable_0o100755', '...', mode=0o100755), | |
58 | FileNode('executable_0o100500', '...', mode=0o100500), |
|
58 | FileNode('executable_0o100500', '...', mode=0o100500), | |
59 | FileNode('not_executable', '...', mode=0o100644), |
|
59 | FileNode('not_executable', '...', mode=0o100644), | |
60 | ], |
|
60 | ], | |
61 | } |
|
61 | } | |
62 | for x in range(5): |
|
62 | for x in range(5): | |
63 | yield { |
|
63 | yield { | |
64 | 'message': 'Commit %d' % x, |
|
64 | 'message': 'Commit %d' % x, | |
65 | 'author': 'Joe Doe <joe.doe@example.com>', |
|
65 | 'author': 'Joe Doe <joe.doe@example.com>', | |
66 | 'date': start_date + datetime.timedelta(hours=12 * x), |
|
66 | 'date': start_date + datetime.timedelta(hours=12 * x), | |
67 | 'added': [ |
|
67 | 'added': [ | |
68 | FileNode('%d/file_%d.txt' % (x, x), content='Foobar %d' % x), |
|
68 | FileNode('%d/file_%d.txt' % (x, x), content='Foobar %d' % x), | |
69 | ], |
|
69 | ], | |
70 | } |
|
70 | } | |
71 |
|
71 | |||
72 | @pytest.mark.parametrize('compressor', ['gz', 'bz2']) |
|
72 | @pytest.mark.parametrize('compressor', ['gz', 'bz2']) | |
73 | def test_archive_tar(self, compressor): |
|
73 | def test_archive_tar(self, compressor): | |
74 | self.tip.archive_repo( |
|
74 | self.tip.archive_repo( | |
75 | self.temp_file, kind='t{}'.format(compressor), archive_dir_name='repo') |
|
75 | self.temp_file, kind='t{}'.format(compressor), archive_dir_name='repo') | |
76 | out_dir = tempfile.mkdtemp() |
|
76 | out_dir = tempfile.mkdtemp() | |
77 | out_file = tarfile.open(self.temp_file, 'r|{}'.format(compressor)) |
|
77 | out_file = tarfile.open(self.temp_file, 'r|{}'.format(compressor)) | |
78 | out_file.extractall(out_dir) |
|
78 | out_file.extractall(out_dir) | |
79 | out_file.close() |
|
79 | out_file.close() | |
80 |
|
80 | |||
81 | for x in range(5): |
|
81 | for x in range(5): | |
82 | node_path = '%d/file_%d.txt' % (x, x) |
|
82 | node_path = '%d/file_%d.txt' % (x, x) | |
83 | with open(os.path.join(out_dir, 'repo/' + node_path)) as f: |
|
83 | with open(os.path.join(out_dir, 'repo/' + node_path)) as f: | |
84 | file_content = f.read() |
|
84 | file_content = f.read() | |
85 | assert file_content == self.tip.get_node(node_path).content |
|
85 | assert file_content == self.tip.get_node(node_path).content | |
86 |
|
86 | |||
87 | shutil.rmtree(out_dir) |
|
87 | shutil.rmtree(out_dir) | |
88 |
|
88 | |||
89 | @pytest.mark.parametrize('compressor', ['gz', 'bz2']) |
|
89 | @pytest.mark.parametrize('compressor', ['gz', 'bz2']) | |
90 | def test_archive_tar_symlink(self, compressor): |
|
90 | def test_archive_tar_symlink(self, compressor): | |
91 | return False |
|
91 | return False | |
92 |
|
92 | |||
93 | @pytest.mark.parametrize('compressor', ['gz', 'bz2']) |
|
93 | @pytest.mark.parametrize('compressor', ['gz', 'bz2']) | |
94 | def test_archive_tar_file_modes(self, compressor): |
|
94 | def test_archive_tar_file_modes(self, compressor): | |
95 | self.tip.archive_repo( |
|
95 | self.tip.archive_repo( | |
96 | self.temp_file, kind='t{}'.format(compressor), archive_dir_name='repo') |
|
96 | self.temp_file, kind='t{}'.format(compressor), archive_dir_name='repo') | |
97 | out_dir = tempfile.mkdtemp() |
|
97 | out_dir = tempfile.mkdtemp() | |
98 | out_file = tarfile.open(self.temp_file, 'r|{}'.format(compressor)) |
|
98 | out_file = tarfile.open(self.temp_file, 'r|{}'.format(compressor)) | |
99 | out_file.extractall(out_dir) |
|
99 | out_file.extractall(out_dir) | |
100 | out_file.close() |
|
100 | out_file.close() | |
101 | dest = lambda inp: os.path.join(out_dir, 'repo/' + inp) |
|
101 | dest = lambda inp: os.path.join(out_dir, 'repo/' + inp) | |
102 |
|
102 | |||
103 | assert oct(os.stat(dest('not_executable')).st_mode) == '0100644' |
|
103 | assert oct(os.stat(dest('not_executable')).st_mode) == '0100644' | |
104 |
|
104 | |||
105 | def test_archive_zip(self): |
|
105 | def test_archive_zip(self): | |
106 | self.tip.archive_repo(self.temp_file, kind='zip', archive_dir_name='repo') |
|
106 | self.tip.archive_repo(self.temp_file, kind='zip', archive_dir_name='repo') | |
107 | out = zipfile.ZipFile(self.temp_file) |
|
107 | out = zipfile.ZipFile(self.temp_file) | |
108 |
|
108 | |||
109 | for x in range(5): |
|
109 | for x in range(5): | |
110 | node_path = '%d/file_%d.txt' % (x, x) |
|
110 | node_path = '%d/file_%d.txt' % (x, x) | |
111 | decompressed = StringIO.StringIO() |
|
111 | decompressed = StringIO.StringIO() | |
112 | decompressed.write(out.read('repo/' + node_path)) |
|
112 | decompressed.write(out.read('repo/' + node_path)) | |
113 | assert decompressed.getvalue() == \ |
|
113 | assert decompressed.getvalue() == \ | |
114 | self.tip.get_node(node_path).content |
|
114 | self.tip.get_node(node_path).content | |
115 | decompressed.close() |
|
115 | decompressed.close() | |
116 |
|
116 | |||
117 | def test_archive_zip_with_metadata(self): |
|
117 | def test_archive_zip_with_metadata(self): | |
118 | self.tip.archive_repo(self.temp_file, kind='zip', |
|
118 | self.tip.archive_repo(self.temp_file, kind='zip', | |
119 | archive_dir_name='repo', write_metadata=True) |
|
119 | archive_dir_name='repo', write_metadata=True) | |
120 |
|
120 | |||
121 | out = zipfile.ZipFile(self.temp_file) |
|
121 | out = zipfile.ZipFile(self.temp_file) | |
122 | metafile = out.read('repo/.archival.txt') |
|
122 | metafile = out.read('repo/.archival.txt') | |
123 |
|
123 | |||
124 | raw_id = self.tip.raw_id |
|
124 | raw_id = self.tip.raw_id | |
125 | assert 'commit_id:%s' % raw_id in metafile |
|
125 | assert 'commit_id:%s' % raw_id in metafile | |
126 |
|
126 | |||
127 | for x in range(5): |
|
127 | for x in range(5): | |
128 | node_path = '%d/file_%d.txt' % (x, x) |
|
128 | node_path = '%d/file_%d.txt' % (x, x) | |
129 | decompressed = StringIO.StringIO() |
|
129 | decompressed = StringIO.StringIO() | |
130 | decompressed.write(out.read('repo/' + node_path)) |
|
130 | decompressed.write(out.read('repo/' + node_path)) | |
131 | assert decompressed.getvalue() == \ |
|
131 | assert decompressed.getvalue() == \ | |
132 | self.tip.get_node(node_path).content |
|
132 | self.tip.get_node(node_path).content | |
133 | decompressed.close() |
|
133 | decompressed.close() | |
134 |
|
134 | |||
135 | def test_archive_wrong_kind(self): |
|
135 | def test_archive_wrong_kind(self): | |
136 | with pytest.raises(ImproperArchiveTypeError): |
|
136 | with pytest.raises(ImproperArchiveTypeError): | |
137 | self.tip.archive_repo(self.temp_file, kind='wrong kind') |
|
137 | self.tip.archive_repo(self.temp_file, kind='wrong kind') | |
138 |
|
138 | |||
139 |
|
139 | |||
140 | @pytest.fixture() |
|
140 | @pytest.fixture() | |
141 | def base_commit(): |
|
141 | def base_commit(): | |
142 | """ |
|
142 | """ | |
143 | Prepare a `base.BaseCommit` just enough for `_validate_archive_prefix`. |
|
143 | Prepare a `base.BaseCommit` just enough for `_validate_archive_prefix`. | |
144 | """ |
|
144 | """ | |
145 | commit = base.BaseCommit() |
|
145 | commit = base.BaseCommit() | |
146 | commit.repository = mock.Mock() |
|
146 | commit.repository = mock.Mock() | |
147 | commit.repository.name = u'fake_repo' |
|
147 | commit.repository.name = u'fake_repo' | |
148 | commit.short_id = 'fake_id' |
|
148 | commit.short_id = 'fake_id' | |
149 | return commit |
|
149 | return commit | |
150 |
|
150 | |||
151 |
|
151 | |||
152 | @pytest.mark.parametrize("prefix", [u"unicode-prefix", u"Ünïcödë"]) |
|
152 | @pytest.mark.parametrize("prefix", [u"unicode-prefix", u"Ünïcödë"]) | |
153 | def test_validate_archive_prefix_enforces_bytes_as_prefix(prefix, base_commit): |
|
153 | def test_validate_archive_prefix_enforces_bytes_as_prefix(prefix, base_commit): | |
154 | with pytest.raises(ValueError): |
|
154 | with pytest.raises(ValueError): | |
155 | base_commit._validate_archive_prefix(prefix) |
|
155 | base_commit._validate_archive_prefix(prefix) | |
156 |
|
156 | |||
157 |
|
157 | |||
158 | def test_validate_archive_prefix_empty_prefix(base_commit): |
|
158 | def test_validate_archive_prefix_empty_prefix(base_commit): | |
159 | # TODO: johbo: Should raise a ValueError here. |
|
159 | # TODO: johbo: Should raise a ValueError here. | |
160 | with pytest.raises(VCSError): |
|
160 | with pytest.raises(VCSError): | |
161 | base_commit._validate_archive_prefix('') |
|
161 | base_commit._validate_archive_prefix('') | |
162 |
|
162 | |||
163 |
|
163 | |||
164 | def test_validate_archive_prefix_with_leading_slash(base_commit): |
|
164 | def test_validate_archive_prefix_with_leading_slash(base_commit): | |
165 | # TODO: johbo: Should raise a ValueError here. |
|
165 | # TODO: johbo: Should raise a ValueError here. | |
166 | with pytest.raises(VCSError): |
|
166 | with pytest.raises(VCSError): | |
167 | base_commit._validate_archive_prefix('/any') |
|
167 | base_commit._validate_archive_prefix('/any') | |
168 |
|
168 | |||
169 |
|
169 | |||
170 | def test_validate_archive_prefix_falls_back_to_repository_name(base_commit): |
|
170 | def test_validate_archive_prefix_falls_back_to_repository_name(base_commit): | |
171 | prefix = base_commit._validate_archive_prefix(None) |
|
171 | prefix = base_commit._validate_archive_prefix(None) | |
172 | expected_prefix = base_commit._ARCHIVE_PREFIX_TEMPLATE.format( |
|
172 | expected_prefix = base_commit._ARCHIVE_PREFIX_TEMPLATE.format( | |
173 | repo_name='fake_repo', |
|
173 | repo_name='fake_repo', | |
174 | short_id='fake_id') |
|
174 | short_id='fake_id') | |
175 | assert isinstance(prefix, str) |
|
175 | assert isinstance(prefix, str) | |
176 | assert prefix == expected_prefix |
|
176 | assert prefix == expected_prefix |
General Comments 0
You need to be logged in to leave comments.
Login now