##// END OF EJS Templates
python3: fixed usage of .next() and .func_name
super-admin -
r4936:0d6cd344 default
parent child Browse files
Show More
@@ -1,479 +1,479 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2020 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import re
22 22 import logging
23 23 import formencode
24 24 import formencode.htmlfill
25 25 import datetime
26 26 from pyramid.interfaces import IRoutesMapper
27 27
28 28 from pyramid.httpexceptions import HTTPFound
29 29 from pyramid.renderers import render
30 30 from pyramid.response import Response
31 31
32 32 from rhodecode.apps._base import BaseAppView, DataGridAppView
33 33 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
34 34 from rhodecode import events
35 35
36 36 from rhodecode.lib import helpers as h
37 37 from rhodecode.lib.auth import (
38 38 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
39 39 from rhodecode.lib.utils2 import aslist, safe_unicode
40 40 from rhodecode.model.db import (
41 41 or_, coalesce, User, UserIpMap, UserSshKeys)
42 42 from rhodecode.model.forms import (
43 43 ApplicationPermissionsForm, ObjectPermissionsForm, UserPermissionsForm)
44 44 from rhodecode.model.meta import Session
45 45 from rhodecode.model.permission import PermissionModel
46 46 from rhodecode.model.settings import SettingsModel
47 47
48 48
49 49 log = logging.getLogger(__name__)
50 50
51 51
52 52 class AdminPermissionsView(BaseAppView, DataGridAppView):
53 53 def load_default_context(self):
54 54 c = self._get_local_tmpl_context()
55 55 PermissionModel().set_global_permission_choices(
56 56 c, gettext_translator=self.request.translate)
57 57 return c
58 58
59 59 @LoginRequired()
60 60 @HasPermissionAllDecorator('hg.admin')
61 61 def permissions_application(self):
62 62 c = self.load_default_context()
63 63 c.active = 'application'
64 64
65 65 c.user = User.get_default_user(refresh=True)
66 66
67 67 app_settings = c.rc_config
68 68
69 69 defaults = {
70 70 'anonymous': c.user.active,
71 71 'default_register_message': app_settings.get(
72 72 'rhodecode_register_message')
73 73 }
74 74 defaults.update(c.user.get_default_perms())
75 75
76 76 data = render('rhodecode:templates/admin/permissions/permissions.mako',
77 77 self._get_template_context(c), self.request)
78 78 html = formencode.htmlfill.render(
79 79 data,
80 80 defaults=defaults,
81 81 encoding="UTF-8",
82 82 force_defaults=False
83 83 )
84 84 return Response(html)
85 85
86 86 @LoginRequired()
87 87 @HasPermissionAllDecorator('hg.admin')
88 88 @CSRFRequired()
89 89 def permissions_application_update(self):
90 90 _ = self.request.translate
91 91 c = self.load_default_context()
92 92 c.active = 'application'
93 93
94 94 _form = ApplicationPermissionsForm(
95 95 self.request.translate,
96 96 [x[0] for x in c.register_choices],
97 97 [x[0] for x in c.password_reset_choices],
98 98 [x[0] for x in c.extern_activate_choices])()
99 99
100 100 try:
101 101 form_result = _form.to_python(dict(self.request.POST))
102 102 form_result.update({'perm_user_name': User.DEFAULT_USER})
103 103 PermissionModel().update_application_permissions(form_result)
104 104
105 105 settings = [
106 106 ('register_message', 'default_register_message'),
107 107 ]
108 108 for setting, form_key in settings:
109 109 sett = SettingsModel().create_or_update_setting(
110 110 setting, form_result[form_key])
111 111 Session().add(sett)
112 112
113 113 Session().commit()
114 114 h.flash(_('Application permissions updated successfully'),
115 115 category='success')
116 116
117 117 except formencode.Invalid as errors:
118 118 defaults = errors.value
119 119
120 120 data = render(
121 121 'rhodecode:templates/admin/permissions/permissions.mako',
122 122 self._get_template_context(c), self.request)
123 123 html = formencode.htmlfill.render(
124 124 data,
125 125 defaults=defaults,
126 126 errors=errors.error_dict or {},
127 127 prefix_error=False,
128 128 encoding="UTF-8",
129 129 force_defaults=False
130 130 )
131 131 return Response(html)
132 132
133 133 except Exception:
134 134 log.exception("Exception during update of permissions")
135 135 h.flash(_('Error occurred during update of permissions'),
136 136 category='error')
137 137
138 138 affected_user_ids = [User.get_default_user_id()]
139 139 PermissionModel().trigger_permission_flush(affected_user_ids)
140 140
141 141 raise HTTPFound(h.route_path('admin_permissions_application'))
142 142
143 143 @LoginRequired()
144 144 @HasPermissionAllDecorator('hg.admin')
145 145 def permissions_objects(self):
146 146 c = self.load_default_context()
147 147 c.active = 'objects'
148 148
149 149 c.user = User.get_default_user(refresh=True)
150 150 defaults = {}
151 151 defaults.update(c.user.get_default_perms())
152 152
153 153 data = render(
154 154 'rhodecode:templates/admin/permissions/permissions.mako',
155 155 self._get_template_context(c), self.request)
156 156 html = formencode.htmlfill.render(
157 157 data,
158 158 defaults=defaults,
159 159 encoding="UTF-8",
160 160 force_defaults=False
161 161 )
162 162 return Response(html)
163 163
164 164 @LoginRequired()
165 165 @HasPermissionAllDecorator('hg.admin')
166 166 @CSRFRequired()
167 167 def permissions_objects_update(self):
168 168 _ = self.request.translate
169 169 c = self.load_default_context()
170 170 c.active = 'objects'
171 171
172 172 _form = ObjectPermissionsForm(
173 173 self.request.translate,
174 174 [x[0] for x in c.repo_perms_choices],
175 175 [x[0] for x in c.group_perms_choices],
176 176 [x[0] for x in c.user_group_perms_choices],
177 177 )()
178 178
179 179 try:
180 180 form_result = _form.to_python(dict(self.request.POST))
181 181 form_result.update({'perm_user_name': User.DEFAULT_USER})
182 182 PermissionModel().update_object_permissions(form_result)
183 183
184 184 Session().commit()
185 185 h.flash(_('Object permissions updated successfully'),
186 186 category='success')
187 187
188 188 except formencode.Invalid as errors:
189 189 defaults = errors.value
190 190
191 191 data = render(
192 192 'rhodecode:templates/admin/permissions/permissions.mako',
193 193 self._get_template_context(c), self.request)
194 194 html = formencode.htmlfill.render(
195 195 data,
196 196 defaults=defaults,
197 197 errors=errors.error_dict or {},
198 198 prefix_error=False,
199 199 encoding="UTF-8",
200 200 force_defaults=False
201 201 )
202 202 return Response(html)
203 203 except Exception:
204 204 log.exception("Exception during update of permissions")
205 205 h.flash(_('Error occurred during update of permissions'),
206 206 category='error')
207 207
208 208 affected_user_ids = [User.get_default_user_id()]
209 209 PermissionModel().trigger_permission_flush(affected_user_ids)
210 210
211 211 raise HTTPFound(h.route_path('admin_permissions_object'))
212 212
213 213 @LoginRequired()
214 214 @HasPermissionAllDecorator('hg.admin')
215 215 def permissions_branch(self):
216 216 c = self.load_default_context()
217 217 c.active = 'branch'
218 218
219 219 c.user = User.get_default_user(refresh=True)
220 220 defaults = {}
221 221 defaults.update(c.user.get_default_perms())
222 222
223 223 data = render(
224 224 'rhodecode:templates/admin/permissions/permissions.mako',
225 225 self._get_template_context(c), self.request)
226 226 html = formencode.htmlfill.render(
227 227 data,
228 228 defaults=defaults,
229 229 encoding="UTF-8",
230 230 force_defaults=False
231 231 )
232 232 return Response(html)
233 233
234 234 @LoginRequired()
235 235 @HasPermissionAllDecorator('hg.admin')
236 236 def permissions_global(self):
237 237 c = self.load_default_context()
238 238 c.active = 'global'
239 239
240 240 c.user = User.get_default_user(refresh=True)
241 241 defaults = {}
242 242 defaults.update(c.user.get_default_perms())
243 243
244 244 data = render(
245 245 'rhodecode:templates/admin/permissions/permissions.mako',
246 246 self._get_template_context(c), self.request)
247 247 html = formencode.htmlfill.render(
248 248 data,
249 249 defaults=defaults,
250 250 encoding="UTF-8",
251 251 force_defaults=False
252 252 )
253 253 return Response(html)
254 254
255 255 @LoginRequired()
256 256 @HasPermissionAllDecorator('hg.admin')
257 257 @CSRFRequired()
258 258 def permissions_global_update(self):
259 259 _ = self.request.translate
260 260 c = self.load_default_context()
261 261 c.active = 'global'
262 262
263 263 _form = UserPermissionsForm(
264 264 self.request.translate,
265 265 [x[0] for x in c.repo_create_choices],
266 266 [x[0] for x in c.repo_create_on_write_choices],
267 267 [x[0] for x in c.repo_group_create_choices],
268 268 [x[0] for x in c.user_group_create_choices],
269 269 [x[0] for x in c.fork_choices],
270 270 [x[0] for x in c.inherit_default_permission_choices])()
271 271
272 272 try:
273 273 form_result = _form.to_python(dict(self.request.POST))
274 274 form_result.update({'perm_user_name': User.DEFAULT_USER})
275 275 PermissionModel().update_user_permissions(form_result)
276 276
277 277 Session().commit()
278 278 h.flash(_('Global permissions updated successfully'),
279 279 category='success')
280 280
281 281 except formencode.Invalid as errors:
282 282 defaults = errors.value
283 283
284 284 data = render(
285 285 'rhodecode:templates/admin/permissions/permissions.mako',
286 286 self._get_template_context(c), self.request)
287 287 html = formencode.htmlfill.render(
288 288 data,
289 289 defaults=defaults,
290 290 errors=errors.error_dict or {},
291 291 prefix_error=False,
292 292 encoding="UTF-8",
293 293 force_defaults=False
294 294 )
295 295 return Response(html)
296 296 except Exception:
297 297 log.exception("Exception during update of permissions")
298 298 h.flash(_('Error occurred during update of permissions'),
299 299 category='error')
300 300
301 301 affected_user_ids = [User.get_default_user_id()]
302 302 PermissionModel().trigger_permission_flush(affected_user_ids)
303 303
304 304 raise HTTPFound(h.route_path('admin_permissions_global'))
305 305
306 306 @LoginRequired()
307 307 @HasPermissionAllDecorator('hg.admin')
308 308 def permissions_ips(self):
309 309 c = self.load_default_context()
310 310 c.active = 'ips'
311 311
312 312 c.user = User.get_default_user(refresh=True)
313 313 c.user_ip_map = (
314 314 UserIpMap.query().filter(UserIpMap.user == c.user).all())
315 315
316 316 return self._get_template_context(c)
317 317
318 318 @LoginRequired()
319 319 @HasPermissionAllDecorator('hg.admin')
320 320 def permissions_overview(self):
321 321 c = self.load_default_context()
322 322 c.active = 'perms'
323 323
324 324 c.user = User.get_default_user(refresh=True)
325 325 c.perm_user = c.user.AuthUser()
326 326 return self._get_template_context(c)
327 327
328 328 @LoginRequired()
329 329 @HasPermissionAllDecorator('hg.admin')
330 330 def auth_token_access(self):
331 331 from rhodecode import CONFIG
332 332
333 333 c = self.load_default_context()
334 334 c.active = 'auth_token_access'
335 335
336 336 c.user = User.get_default_user(refresh=True)
337 337 c.perm_user = c.user.AuthUser()
338 338
339 339 mapper = self.request.registry.queryUtility(IRoutesMapper)
340 340 c.view_data = []
341 341
342 342 _argument_prog = re.compile('\{(.*?)\}|:\((.*)\)')
343 343 introspector = self.request.registry.introspector
344 344
345 345 view_intr = {}
346 346 for view_data in introspector.get_category('views'):
347 347 intr = view_data['introspectable']
348 348
349 349 if 'route_name' in intr and intr['attr']:
350 350 view_intr[intr['route_name']] = '{}:{}'.format(
351 str(intr['derived_callable'].func_name), intr['attr']
351 str(intr['derived_callable'].__name__), intr['attr']
352 352 )
353 353
354 354 c.whitelist_key = 'api_access_controllers_whitelist'
355 355 c.whitelist_file = CONFIG.get('__file__')
356 356 whitelist_views = aslist(
357 357 CONFIG.get(c.whitelist_key), sep=',')
358 358
359 359 for route_info in mapper.get_routes():
360 360 if not route_info.name.startswith('__'):
361 361 routepath = route_info.pattern
362 362
363 363 def replace(matchobj):
364 364 if matchobj.group(1):
365 365 return "{%s}" % matchobj.group(1).split(':')[0]
366 366 else:
367 367 return "{%s}" % matchobj.group(2)
368 368
369 369 routepath = _argument_prog.sub(replace, routepath)
370 370
371 371 if not routepath.startswith('/'):
372 372 routepath = '/' + routepath
373 373
374 374 view_fqn = view_intr.get(route_info.name, 'NOT AVAILABLE')
375 375 active = view_fqn in whitelist_views
376 376 c.view_data.append((route_info.name, view_fqn, routepath, active))
377 377
378 378 c.whitelist_views = whitelist_views
379 379 return self._get_template_context(c)
380 380
381 381 def ssh_enabled(self):
382 382 return self.request.registry.settings.get(
383 383 'ssh.generate_authorized_keyfile')
384 384
385 385 @LoginRequired()
386 386 @HasPermissionAllDecorator('hg.admin')
387 387 def ssh_keys(self):
388 388 c = self.load_default_context()
389 389 c.active = 'ssh_keys'
390 390 c.ssh_enabled = self.ssh_enabled()
391 391 return self._get_template_context(c)
392 392
393 393 @LoginRequired()
394 394 @HasPermissionAllDecorator('hg.admin')
395 395 def ssh_keys_data(self):
396 396 _ = self.request.translate
397 397 self.load_default_context()
398 398 column_map = {
399 399 'fingerprint': 'ssh_key_fingerprint',
400 400 'username': User.username
401 401 }
402 402 draw, start, limit = self._extract_chunk(self.request)
403 403 search_q, order_by, order_dir = self._extract_ordering(
404 404 self.request, column_map=column_map)
405 405
406 406 ssh_keys_data_total_count = UserSshKeys.query()\
407 407 .count()
408 408
409 409 # json generate
410 410 base_q = UserSshKeys.query().join(UserSshKeys.user)
411 411
412 412 if search_q:
413 413 like_expression = u'%{}%'.format(safe_unicode(search_q))
414 414 base_q = base_q.filter(or_(
415 415 User.username.ilike(like_expression),
416 416 UserSshKeys.ssh_key_fingerprint.ilike(like_expression),
417 417 ))
418 418
419 419 users_data_total_filtered_count = base_q.count()
420 420
421 421 sort_col = self._get_order_col(order_by, UserSshKeys)
422 422 if sort_col:
423 423 if order_dir == 'asc':
424 424 # handle null values properly to order by NULL last
425 425 if order_by in ['created_on']:
426 426 sort_col = coalesce(sort_col, datetime.date.max)
427 427 sort_col = sort_col.asc()
428 428 else:
429 429 # handle null values properly to order by NULL last
430 430 if order_by in ['created_on']:
431 431 sort_col = coalesce(sort_col, datetime.date.min)
432 432 sort_col = sort_col.desc()
433 433
434 434 base_q = base_q.order_by(sort_col)
435 435 base_q = base_q.offset(start).limit(limit)
436 436
437 437 ssh_keys = base_q.all()
438 438
439 439 ssh_keys_data = []
440 440 for ssh_key in ssh_keys:
441 441 ssh_keys_data.append({
442 442 "username": h.gravatar_with_user(self.request, ssh_key.user.username),
443 443 "fingerprint": ssh_key.ssh_key_fingerprint,
444 444 "description": ssh_key.description,
445 445 "created_on": h.format_date(ssh_key.created_on),
446 446 "accessed_on": h.format_date(ssh_key.accessed_on),
447 447 "action": h.link_to(
448 448 _('Edit'), h.route_path('edit_user_ssh_keys',
449 449 user_id=ssh_key.user.user_id))
450 450 })
451 451
452 452 data = ({
453 453 'draw': draw,
454 454 'data': ssh_keys_data,
455 455 'recordsTotal': ssh_keys_data_total_count,
456 456 'recordsFiltered': users_data_total_filtered_count,
457 457 })
458 458
459 459 return data
460 460
461 461 @LoginRequired()
462 462 @HasPermissionAllDecorator('hg.admin')
463 463 @CSRFRequired()
464 464 def ssh_keys_update(self):
465 465 _ = self.request.translate
466 466 self.load_default_context()
467 467
468 468 ssh_enabled = self.ssh_enabled()
469 469 key_file = self.request.registry.settings.get(
470 470 'ssh.authorized_keys_file_path')
471 471 if ssh_enabled:
472 472 events.trigger(SshKeyFileChangeEvent(), self.request.registry)
473 473 h.flash(_('Updated SSH keys file: {}').format(key_file),
474 474 category='success')
475 475 else:
476 476 h.flash(_('SSH key support is disabled in .ini file'),
477 477 category='warning')
478 478
479 479 raise HTTPFound(h.route_path('admin_permissions_ssh_keys'))
@@ -1,121 +1,121 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2012-2020 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import time
22 22 import logging
23 23
24 24 from pyramid.exceptions import ConfigurationError
25 25 from zope.interface import implementer
26 26
27 27 from rhodecode.authentication.interface import IAuthnPluginRegistry
28 28 from rhodecode.model.settings import SettingsModel
29 29 from rhodecode.lib.utils2 import safe_str
30 30 from rhodecode.lib.statsd_client import StatsdClient
31 31 from rhodecode.lib import rc_cache
32 32
33 33 log = logging.getLogger(__name__)
34 34
35 35
36 36 @implementer(IAuthnPluginRegistry)
37 37 class AuthenticationPluginRegistry(object):
38 38
39 39 # INI settings key to set a fallback authentication plugin.
40 40 fallback_plugin_key = 'rhodecode.auth_plugin_fallback'
41 41
42 42 def __init__(self, settings):
43 43 self._plugins = {}
44 44 self._fallback_plugin = settings.get(self.fallback_plugin_key, None)
45 45
46 46 def add_authn_plugin(self, config, plugin):
47 47 plugin_id = plugin.get_id()
48 48 if plugin_id in self._plugins.keys():
49 49 raise ConfigurationError(
50 50 'Cannot register authentication plugin twice: "%s"', plugin_id)
51 51 else:
52 52 log.debug('Register authentication plugin: "%s"', plugin_id)
53 53 self._plugins[plugin_id] = plugin
54 54
55 55 def get_plugins(self):
56 56 def sort_key(plugin):
57 57 return str.lower(safe_str(plugin.get_display_name()))
58 58
59 59 return sorted(self._plugins.values(), key=sort_key)
60 60
61 61 def get_plugin(self, plugin_id):
62 62 return self._plugins.get(plugin_id, None)
63 63
64 64 def get_plugin_by_uid(self, plugin_uid):
65 65 for plugin in self._plugins.values():
66 66 if plugin.uid == plugin_uid:
67 67 return plugin
68 68
69 69 def get_plugins_for_authentication(self, cache=True):
70 70 """
71 71 Returns a list of plugins which should be consulted when authenticating
72 72 a user. It only returns plugins which are enabled and active.
73 73 Additionally it includes the fallback plugin from the INI file, if
74 74 `rhodecode.auth_plugin_fallback` is set to a plugin ID.
75 75 """
76 76
77 77 cache_namespace_uid = 'cache_auth_plugins'
78 78 region = rc_cache.get_or_create_region('cache_general', cache_namespace_uid)
79 79
80 80 @region.conditional_cache_on_arguments(condition=cache)
81 81 def _get_auth_plugins(name, key, fallback_plugin):
82 82 plugins = []
83 83
84 84 # Add all enabled and active plugins to the list. We iterate over the
85 85 # auth_plugins setting from DB because it also represents the ordering.
86 86 enabled_plugins = SettingsModel().get_auth_plugins()
87 87 raw_settings = SettingsModel().get_all_settings(cache=False)
88 88 for plugin_id in enabled_plugins:
89 89 plugin = self.get_plugin(plugin_id)
90 90 if plugin is not None and plugin.is_active(
91 91 plugin_cached_settings=raw_settings):
92 92
93 93 # inject settings into plugin, we can re-use the DB fetched settings here
94 94 plugin._settings = plugin._propagate_settings(raw_settings)
95 95 plugins.append(plugin)
96 96
97 97 # Add the fallback plugin from ini file.
98 98 if fallback_plugin:
99 99 log.warn(
100 100 'Using fallback authentication plugin from INI file: "%s"',
101 101 fallback_plugin)
102 102 plugin = self.get_plugin(fallback_plugin)
103 103 if plugin is not None and plugin not in plugins:
104 104 plugin._settings = plugin._propagate_settings(raw_settings)
105 105 plugins.append(plugin)
106 106 return plugins
107 107
108 108 start = time.time()
109 109 plugins = _get_auth_plugins('rhodecode_auth_plugins', 'v1', self._fallback_plugin)
110 110
111 111 compute_time = time.time() - start
112 log.debug('cached method:%s took %.4fs', _get_auth_plugins.func_name, compute_time)
112 log.debug('cached method:%s took %.4fs', _get_auth_plugins.__name__, compute_time)
113 113
114 114 statsd = StatsdClient.statsd
115 115 if statsd:
116 116 elapsed_time_ms = round(1000.0 * compute_time) # use ms only
117 117 statsd.timing("rhodecode_auth_plugins_timing.histogram", elapsed_time_ms,
118 118 use_decimals=False)
119 119
120 120 return plugins
121 121
@@ -1,199 +1,199 b''
1 1 # Copyright (C) 2016-2020 RhodeCode GmbH
2 2 #
3 3 # This program is free software: you can redistribute it and/or modify
4 4 # it under the terms of the GNU Affero General Public License, version 3
5 5 # (only), as published by the Free Software Foundation.
6 6 #
7 7 # This program is distributed in the hope that it will be useful,
8 8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 10 # GNU General Public License for more details.
11 11 #
12 12 # You should have received a copy of the GNU Affero General Public License
13 13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
14 14 #
15 15 # This program is dual-licensed. If you wish to learn more about the
16 16 # RhodeCode Enterprise Edition, including its added features, Support services,
17 17 # and proprietary license terms, please see https://rhodecode.com/licenses/
18 18
19 19 import logging
20 20 import os
21 21 import string
22 22 import functools
23 23 import collections
24 24 import urllib.request, urllib.parse, urllib.error
25 25
26 26 log = logging.getLogger('rhodecode.' + __name__)
27 27
28 28
29 29 class HookResponse(object):
30 30 def __init__(self, status, output):
31 31 self.status = status
32 32 self.output = output
33 33
34 34 def __add__(self, other):
35 35 other_status = getattr(other, 'status', 0)
36 36 new_status = max(self.status, other_status)
37 37 other_output = getattr(other, 'output', '')
38 38 new_output = self.output + other_output
39 39
40 40 return HookResponse(new_status, new_output)
41 41
42 42 def __bool__(self):
43 43 return self.status == 0
44 44
45 45
46 46 class DotDict(dict):
47 47
48 48 def __contains__(self, k):
49 49 try:
50 50 return dict.__contains__(self, k) or hasattr(self, k)
51 51 except:
52 52 return False
53 53
54 54 # only called if k not found in normal places
55 55 def __getattr__(self, k):
56 56 try:
57 57 return object.__getattribute__(self, k)
58 58 except AttributeError:
59 59 try:
60 60 return self[k]
61 61 except KeyError:
62 62 raise AttributeError(k)
63 63
64 64 def __setattr__(self, k, v):
65 65 try:
66 66 object.__getattribute__(self, k)
67 67 except AttributeError:
68 68 try:
69 69 self[k] = v
70 70 except:
71 71 raise AttributeError(k)
72 72 else:
73 73 object.__setattr__(self, k, v)
74 74
75 75 def __delattr__(self, k):
76 76 try:
77 77 object.__getattribute__(self, k)
78 78 except AttributeError:
79 79 try:
80 80 del self[k]
81 81 except KeyError:
82 82 raise AttributeError(k)
83 83 else:
84 84 object.__delattr__(self, k)
85 85
86 86 def toDict(self):
87 87 return unserialize(self)
88 88
89 89 def __repr__(self):
90 90 keys = list(self.keys())
91 91 keys.sort()
92 92 args = ', '.join(['%s=%r' % (key, self[key]) for key in keys])
93 93 return '%s(%s)' % (self.__class__.__name__, args)
94 94
95 95 @staticmethod
96 96 def fromDict(d):
97 97 return serialize(d)
98 98
99 99
100 100 def serialize(x):
101 101 if isinstance(x, dict):
102 102 return DotDict((k, serialize(v)) for k, v in x.items())
103 103 elif isinstance(x, (list, tuple)):
104 104 return type(x)(serialize(v) for v in x)
105 105 else:
106 106 return x
107 107
108 108
109 109 def unserialize(x):
110 110 if isinstance(x, dict):
111 111 return dict((k, unserialize(v)) for k, v in x.items())
112 112 elif isinstance(x, (list, tuple)):
113 113 return type(x)(unserialize(v) for v in x)
114 114 else:
115 115 return x
116 116
117 117
118 118 def _verify_kwargs(func_name, expected_parameters, kwargs):
119 119 """
120 120 Verify that exactly `expected_parameters` are passed in as `kwargs`.
121 121 """
122 122 expected_parameters = set(expected_parameters)
123 123 kwargs_keys = set(kwargs.keys())
124 124 if kwargs_keys != expected_parameters:
125 125 missing_kwargs = expected_parameters - kwargs_keys
126 126 unexpected_kwargs = kwargs_keys - expected_parameters
127 127 raise AssertionError(
128 128 "func:%s: missing parameters: %r, unexpected parameters: %s" %
129 129 (func_name, missing_kwargs, unexpected_kwargs))
130 130
131 131
132 132 def has_kwargs(required_args):
133 133 """
134 134 decorator to verify extension calls arguments.
135 135
136 136 :param required_args:
137 137 """
138 138 def wrap(func):
139 139 def wrapper(*args, **kwargs):
140 _verify_kwargs(func.func_name, required_args.keys(), kwargs)
140 _verify_kwargs(func.__name__, required_args.keys(), kwargs)
141 141 # in case there's `calls` defined on module we store the data
142 maybe_log_call(func.func_name, args, kwargs)
143 log.debug('Calling rcextensions function %s', func.func_name)
142 maybe_log_call(func.__name__, args, kwargs)
143 log.debug('Calling rcextensions function %s', func.__name__)
144 144 return func(*args, **kwargs)
145 145 return wrapper
146 146 return wrap
147 147
148 148
149 149 def maybe_log_call(name, args, kwargs):
150 150 from rhodecode.config import rcextensions
151 151 if hasattr(rcextensions, 'calls'):
152 152 calls = rcextensions.calls
153 153 calls[name].append((args, kwargs))
154 154
155 155
156 156 def str2bool(_str):
157 157 """
158 158 returns True/False value from given string, it tries to translate the
159 159 string into boolean
160 160
161 161 :param _str: string value to translate into boolean
162 162 :rtype: boolean
163 163 :returns: boolean from given string
164 164 """
165 165 if _str is None:
166 166 return False
167 167 if _str in (True, False):
168 168 return _str
169 169 _str = str(_str).strip().lower()
170 170 return _str in ('t', 'true', 'y', 'yes', 'on', '1')
171 171
172 172
173 173 def aslist(obj, sep=None, strip=True):
174 174 """
175 175 Returns given string separated by sep as list
176 176
177 177 :param obj:
178 178 :param sep:
179 179 :param strip:
180 180 """
181 181 if isinstance(obj, (str,)):
182 182 lst = obj.split(sep)
183 183 if strip:
184 184 lst = [v.strip() for v in lst]
185 185 return lst
186 186 elif isinstance(obj, (list, tuple)):
187 187 return obj
188 188 elif obj is None:
189 189 return []
190 190 else:
191 191 return [obj]
192 192
193 193
194 194 class UrlTemplate(string.Template):
195 195
196 196 def safe_substitute(self, **kws):
197 197 # url encode the kw for usage in url
198 198 kws = {k: urllib.parse.quote(str(v)) for k, v in kws.items()}
199 199 return super(UrlTemplate, self).safe_substitute(**kws)
@@ -1,839 +1,839 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Utilities for writing code that runs on Python 2 and 3"""
3 3
4 4 # Copyright (c) 2010-2015 Benjamin Peterson
5 5 #
6 6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 7 # of this software and associated documentation files (the "Software"), to deal
8 8 # in the Software without restriction, including without limitation the rights
9 9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 10 # copies of the Software, and to permit persons to whom the Software is
11 11 # furnished to do so, subject to the following conditions:
12 12 #
13 13 # The above copyright notice and this permission notice shall be included in all
14 14 # copies or substantial portions of the Software.
15 15 #
16 16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 22 # SOFTWARE.
23 23
24 24
25 25
26 26 import functools
27 27 import itertools
28 28 import operator
29 29 import sys
30 30 import types
31 31
32 32 __author__ = "Benjamin Peterson <benjamin@python.org>"
33 33 __version__ = "1.9.0"
34 34
35 35
36 36 # Useful for very coarse version differentiation.
37 37 PY2 = sys.version_info[0] == 2
38 38 PY3 = sys.version_info[0] == 3
39 39
40 40 if PY3:
41 41 string_types = str,
42 42 integer_types = int,
43 43 class_types = type,
44 44 text_type = str
45 45 binary_type = bytes
46 46
47 47 MAXSIZE = sys.maxsize
48 48 else:
49 49 string_types = str,
50 50 integer_types = int
51 51 class_types = (type, types.ClassType)
52 52 text_type = unicode
53 53 binary_type = str
54 54
55 55 if sys.platform.startswith("java"):
56 56 # Jython always uses 32 bits.
57 57 MAXSIZE = int((1 << 31) - 1)
58 58 else:
59 59 # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
60 60 class X(object):
61 61 def __len__(self):
62 62 return 1 << 31
63 63 try:
64 64 len(X())
65 65 except OverflowError:
66 66 # 32-bit
67 67 MAXSIZE = int((1 << 31) - 1)
68 68 else:
69 69 # 64-bit
70 70 MAXSIZE = int((1 << 63) - 1)
71 71 del X
72 72
73 73
74 74 def _add_doc(func, doc):
75 75 """Add documentation to a function."""
76 76 func.__doc__ = doc
77 77
78 78
79 79 def _import_module(name):
80 80 """Import module, returning the module after the last dot."""
81 81 __import__(name)
82 82 return sys.modules[name]
83 83
84 84
85 85 class _LazyDescr(object):
86 86
87 87 def __init__(self, name):
88 88 self.name = name
89 89
90 90 def __get__(self, obj, tp):
91 91 result = self._resolve()
92 92 setattr(obj, self.name, result) # Invokes __set__.
93 93 try:
94 94 # This is a bit ugly, but it avoids running this again by
95 95 # removing this descriptor.
96 96 delattr(obj.__class__, self.name)
97 97 except AttributeError:
98 98 pass
99 99 return result
100 100
101 101
102 102 class MovedModule(_LazyDescr):
103 103
104 104 def __init__(self, name, old, new=None):
105 105 super(MovedModule, self).__init__(name)
106 106 if PY3:
107 107 if new is None:
108 108 new = name
109 109 self.mod = new
110 110 else:
111 111 self.mod = old
112 112
113 113 def _resolve(self):
114 114 return _import_module(self.mod)
115 115
116 116 def __getattr__(self, attr):
117 117 _module = self._resolve()
118 118 value = getattr(_module, attr)
119 119 setattr(self, attr, value)
120 120 return value
121 121
122 122
123 123 class _LazyModule(types.ModuleType):
124 124
125 125 def __init__(self, name):
126 126 super(_LazyModule, self).__init__(name)
127 127 self.__doc__ = self.__class__.__doc__
128 128
129 129 def __dir__(self):
130 130 attrs = ["__doc__", "__name__"]
131 131 attrs += [attr.name for attr in self._moved_attributes]
132 132 return attrs
133 133
134 134 # Subclasses should override this
135 135 _moved_attributes = []
136 136
137 137
138 138 class MovedAttribute(_LazyDescr):
139 139
140 140 def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
141 141 super(MovedAttribute, self).__init__(name)
142 142 if PY3:
143 143 if new_mod is None:
144 144 new_mod = name
145 145 self.mod = new_mod
146 146 if new_attr is None:
147 147 if old_attr is None:
148 148 new_attr = name
149 149 else:
150 150 new_attr = old_attr
151 151 self.attr = new_attr
152 152 else:
153 153 self.mod = old_mod
154 154 if old_attr is None:
155 155 old_attr = name
156 156 self.attr = old_attr
157 157
158 158 def _resolve(self):
159 159 module = _import_module(self.mod)
160 160 return getattr(module, self.attr)
161 161
162 162
163 163 class _SixMetaPathImporter(object):
164 164 """
165 165 A meta path importer to import six.moves and its submodules.
166 166
167 167 This class implements a PEP302 finder and loader. It should be compatible
168 168 with Python 2.5 and all existing versions of Python3
169 169 """
170 170 def __init__(self, six_module_name):
171 171 self.name = six_module_name
172 172 self.known_modules = {}
173 173
174 174 def _add_module(self, mod, *fullnames):
175 175 for fullname in fullnames:
176 176 self.known_modules[self.name + "." + fullname] = mod
177 177
178 178 def _get_module(self, fullname):
179 179 return self.known_modules[self.name + "." + fullname]
180 180
181 181 def find_module(self, fullname, path=None):
182 182 if fullname in self.known_modules:
183 183 return self
184 184 return None
185 185
186 186 def __get_module(self, fullname):
187 187 try:
188 188 return self.known_modules[fullname]
189 189 except KeyError:
190 190 raise ImportError("This loader does not know module " + fullname)
191 191
192 192 def load_module(self, fullname):
193 193 try:
194 194 # in case of a reload
195 195 return sys.modules[fullname]
196 196 except KeyError:
197 197 pass
198 198 mod = self.__get_module(fullname)
199 199 if isinstance(mod, MovedModule):
200 200 mod = mod._resolve()
201 201 else:
202 202 mod.__loader__ = self
203 203 sys.modules[fullname] = mod
204 204 return mod
205 205
206 206 def is_package(self, fullname):
207 207 """
208 208 Return true, if the named module is a package.
209 209
210 210 We need this method to get correct spec objects with
211 211 Python 3.4 (see PEP451)
212 212 """
213 213 return hasattr(self.__get_module(fullname), "__path__")
214 214
215 215 def get_code(self, fullname):
216 216 """Return None
217 217
218 218 Required, if is_package is implemented"""
219 219 self.__get_module(fullname) # eventually raises ImportError
220 220 return None
221 221 get_source = get_code # same as get_code
222 222
223 223 _importer = _SixMetaPathImporter(__name__)
224 224
225 225
226 226 class _MovedItems(_LazyModule):
227 227 """Lazy loading of moved objects"""
228 228 __path__ = [] # mark as package
229 229
230 230
231 231 _moved_attributes = [
232 232 MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
233 233 MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
234 234 MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
235 235 MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
236 236 MovedAttribute("intern", "__builtin__", "sys"),
237 237 MovedAttribute("map", "itertools", "builtins", "imap", "map"),
238 238 MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
239 239 MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
240 240 MovedAttribute("reduce", "__builtin__", "functools"),
241 241 MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),
242 242 MovedAttribute("StringIO", "StringIO", "io"),
243 243 MovedAttribute("UserDict", "UserDict", "collections"),
244 244 MovedAttribute("UserList", "UserList", "collections"),
245 245 MovedAttribute("UserString", "UserString", "collections"),
246 246 MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
247 247 MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
248 248 MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
249 249
250 250 MovedModule("builtins", "__builtin__"),
251 251 MovedModule("configparser", "ConfigParser"),
252 252 MovedModule("copyreg", "copy_reg"),
253 253 MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
254 254 MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"),
255 255 MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
256 256 MovedModule("http_cookies", "Cookie", "http.cookies"),
257 257 MovedModule("html_entities", "htmlentitydefs", "html.entities"),
258 258 MovedModule("html_parser", "HTMLParser", "html.parser"),
259 259 MovedModule("http_client", "httplib", "http.client"),
260 260 MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
261 261 MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),
262 262 MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
263 263 MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
264 264 MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
265 265 MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
266 266 MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
267 267 MovedModule("cPickle", "cPickle", "pickle"),
268 268 MovedModule("queue", "Queue"),
269 269 MovedModule("reprlib", "repr"),
270 270 MovedModule("socketserver", "SocketServer"),
271 271 MovedModule("_thread", "thread", "_thread"),
272 272 MovedModule("tkinter", "Tkinter"),
273 273 MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
274 274 MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
275 275 MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
276 276 MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
277 277 MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
278 278 MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
279 279 MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
280 280 MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
281 281 MovedModule("tkinter_colorchooser", "tkColorChooser",
282 282 "tkinter.colorchooser"),
283 283 MovedModule("tkinter_commondialog", "tkCommonDialog",
284 284 "tkinter.commondialog"),
285 285 MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
286 286 MovedModule("tkinter_font", "tkFont", "tkinter.font"),
287 287 MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
288 288 MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
289 289 "tkinter.simpledialog"),
290 290 MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
291 291 MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
292 292 MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
293 293 MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
294 294 MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
295 295 MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
296 296 MovedModule("winreg", "_winreg"),
297 297 ]
298 298 for attr in _moved_attributes:
299 299 setattr(_MovedItems, attr.name, attr)
300 300 if isinstance(attr, MovedModule):
301 301 _importer._add_module(attr, "moves." + attr.name)
302 302 del attr
303 303
304 304 _MovedItems._moved_attributes = _moved_attributes
305 305
306 306 moves = _MovedItems(__name__ + ".moves")
307 307 _importer._add_module(moves, "moves")
308 308
309 309
310 310 class Module_six_moves_urllib_parse(_LazyModule):
311 311 """Lazy loading of moved objects in six.moves.urllib_parse"""
312 312
313 313
314 314 _urllib_parse_moved_attributes = [
315 315 MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
316 316 MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
317 317 MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
318 318 MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
319 319 MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
320 320 MovedAttribute("urljoin", "urlparse", "urllib.parse"),
321 321 MovedAttribute("urlparse", "urlparse", "urllib.parse"),
322 322 MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
323 323 MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
324 324 MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
325 325 MovedAttribute("quote", "urllib", "urllib.parse"),
326 326 MovedAttribute("quote_plus", "urllib", "urllib.parse"),
327 327 MovedAttribute("unquote", "urllib", "urllib.parse"),
328 328 MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
329 329 MovedAttribute("urlencode", "urllib", "urllib.parse"),
330 330 MovedAttribute("splitquery", "urllib", "urllib.parse"),
331 331 MovedAttribute("splittag", "urllib", "urllib.parse"),
332 332 MovedAttribute("splituser", "urllib", "urllib.parse"),
333 333 MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),
334 334 MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),
335 335 MovedAttribute("uses_params", "urlparse", "urllib.parse"),
336 336 MovedAttribute("uses_query", "urlparse", "urllib.parse"),
337 337 MovedAttribute("uses_relative", "urlparse", "urllib.parse"),
338 338 ]
339 339 for attr in _urllib_parse_moved_attributes:
340 340 setattr(Module_six_moves_urllib_parse, attr.name, attr)
341 341 del attr
342 342
343 343 Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
344 344
345 345 _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
346 346 "moves.urllib_parse", "moves.urllib.parse")
347 347
348 348
349 349 class Module_six_moves_urllib_error(_LazyModule):
350 350 """Lazy loading of moved objects in six.moves.urllib_error"""
351 351
352 352
353 353 _urllib_error_moved_attributes = [
354 354 MovedAttribute("URLError", "urllib2", "urllib.error"),
355 355 MovedAttribute("HTTPError", "urllib2", "urllib.error"),
356 356 MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
357 357 ]
358 358 for attr in _urllib_error_moved_attributes:
359 359 setattr(Module_six_moves_urllib_error, attr.name, attr)
360 360 del attr
361 361
362 362 Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
363 363
364 364 _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
365 365 "moves.urllib_error", "moves.urllib.error")
366 366
367 367
368 368 class Module_six_moves_urllib_request(_LazyModule):
369 369 """Lazy loading of moved objects in six.moves.urllib_request"""
370 370
371 371
372 372 _urllib_request_moved_attributes = [
373 373 MovedAttribute("urlopen", "urllib2", "urllib.request"),
374 374 MovedAttribute("install_opener", "urllib2", "urllib.request"),
375 375 MovedAttribute("build_opener", "urllib2", "urllib.request"),
376 376 MovedAttribute("pathname2url", "urllib", "urllib.request"),
377 377 MovedAttribute("url2pathname", "urllib", "urllib.request"),
378 378 MovedAttribute("getproxies", "urllib", "urllib.request"),
379 379 MovedAttribute("Request", "urllib2", "urllib.request"),
380 380 MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
381 381 MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
382 382 MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
383 383 MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
384 384 MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
385 385 MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
386 386 MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
387 387 MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
388 388 MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
389 389 MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
390 390 MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
391 391 MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
392 392 MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
393 393 MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
394 394 MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
395 395 MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
396 396 MovedAttribute("FileHandler", "urllib2", "urllib.request"),
397 397 MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
398 398 MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
399 399 MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
400 400 MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
401 401 MovedAttribute("urlretrieve", "urllib", "urllib.request"),
402 402 MovedAttribute("urlcleanup", "urllib", "urllib.request"),
403 403 MovedAttribute("URLopener", "urllib", "urllib.request"),
404 404 MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
405 405 MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
406 406 ]
407 407 for attr in _urllib_request_moved_attributes:
408 408 setattr(Module_six_moves_urllib_request, attr.name, attr)
409 409 del attr
410 410
411 411 Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
412 412
413 413 _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
414 414 "moves.urllib_request", "moves.urllib.request")
415 415
416 416
417 417 class Module_six_moves_urllib_response(_LazyModule):
418 418 """Lazy loading of moved objects in six.moves.urllib_response"""
419 419
420 420
421 421 _urllib_response_moved_attributes = [
422 422 MovedAttribute("addbase", "urllib", "urllib.response"),
423 423 MovedAttribute("addclosehook", "urllib", "urllib.response"),
424 424 MovedAttribute("addinfo", "urllib", "urllib.response"),
425 425 MovedAttribute("addinfourl", "urllib", "urllib.response"),
426 426 ]
427 427 for attr in _urllib_response_moved_attributes:
428 428 setattr(Module_six_moves_urllib_response, attr.name, attr)
429 429 del attr
430 430
431 431 Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
432 432
433 433 _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
434 434 "moves.urllib_response", "moves.urllib.response")
435 435
436 436
437 437 class Module_six_moves_urllib_robotparser(_LazyModule):
438 438 """Lazy loading of moved objects in six.moves.urllib_robotparser"""
439 439
440 440
441 441 _urllib_robotparser_moved_attributes = [
442 442 MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
443 443 ]
444 444 for attr in _urllib_robotparser_moved_attributes:
445 445 setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
446 446 del attr
447 447
448 448 Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
449 449
450 450 _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
451 451 "moves.urllib_robotparser", "moves.urllib.robotparser")
452 452
453 453
454 454 class Module_six_moves_urllib(types.ModuleType):
455 455 """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
456 456 __path__ = [] # mark as package
457 457 parse = _importer._get_module("moves.urllib_parse")
458 458 error = _importer._get_module("moves.urllib_error")
459 459 request = _importer._get_module("moves.urllib_request")
460 460 response = _importer._get_module("moves.urllib_response")
461 461 robotparser = _importer._get_module("moves.urllib_robotparser")
462 462
463 463 def __dir__(self):
464 464 return ['parse', 'error', 'request', 'response', 'robotparser']
465 465
466 466 _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),
467 467 "moves.urllib")
468 468
469 469
470 470 def add_move(move):
471 471 """Add an item to six.moves."""
472 472 setattr(_MovedItems, move.name, move)
473 473
474 474
475 475 def remove_move(name):
476 476 """Remove item from six.moves."""
477 477 try:
478 478 delattr(_MovedItems, name)
479 479 except AttributeError:
480 480 try:
481 481 del moves.__dict__[name]
482 482 except KeyError:
483 483 raise AttributeError("no such move, %r" % (name,))
484 484
485 485
486 486 if PY3:
487 487 _meth_func = "__func__"
488 488 _meth_self = "__self__"
489 489
490 490 _func_closure = "__closure__"
491 491 _func_code = "__code__"
492 492 _func_defaults = "__defaults__"
493 493 _func_globals = "__globals__"
494 494 else:
495 495 _meth_func = "im_func"
496 496 _meth_self = "im_self"
497 497
498 498 _func_closure = "func_closure"
499 499 _func_code = "func_code"
500 500 _func_defaults = "func_defaults"
501 501 _func_globals = "func_globals"
502 502
503 503
504 504 try:
505 505 advance_iterator = next
506 506 except NameError:
507 507 def advance_iterator(it):
508 return it.next()
508 return next(it)
509 509 next = advance_iterator
510 510
511 511
512 512 try:
513 513 callable = callable
514 514 except NameError:
515 515 def callable(obj):
516 516 return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
517 517
518 518
519 519 if PY3:
520 520 def get_unbound_function(unbound):
521 521 return unbound
522 522
523 523 create_bound_method = types.MethodType
524 524
525 525 Iterator = object
526 526 else:
527 527 def get_unbound_function(unbound):
528 528 return unbound.im_func
529 529
530 530 def create_bound_method(func, obj):
531 531 return types.MethodType(func, obj, obj.__class__)
532 532
533 533 class Iterator(object):
534 534
535 535 def next(self):
536 536 return type(self).__next__(self)
537 537
538 538 callable = callable
539 539 _add_doc(get_unbound_function,
540 540 """Get the function out of a possibly unbound function""")
541 541
542 542
543 543 get_method_function = operator.attrgetter(_meth_func)
544 544 get_method_self = operator.attrgetter(_meth_self)
545 545 get_function_closure = operator.attrgetter(_func_closure)
546 546 get_function_code = operator.attrgetter(_func_code)
547 547 get_function_defaults = operator.attrgetter(_func_defaults)
548 548 get_function_globals = operator.attrgetter(_func_globals)
549 549
550 550
551 551 if PY3:
552 552 def iterkeys(d, **kw):
553 553 return iter(d.keys(**kw))
554 554
555 555 def itervalues(d, **kw):
556 556 return iter(d.values(**kw))
557 557
558 558 def iteritems(d, **kw):
559 559 return iter(d.items(**kw))
560 560
561 561 def iterlists(d, **kw):
562 562 return iter(d.lists(**kw))
563 563
564 564 viewkeys = operator.methodcaller("keys")
565 565
566 566 viewvalues = operator.methodcaller("values")
567 567
568 568 viewitems = operator.methodcaller("items")
569 569 else:
570 570 def iterkeys(d, **kw):
571 571 return iter(d.iterkeys(**kw))
572 572
573 573 def itervalues(d, **kw):
574 574 return iter(d.itervalues(**kw))
575 575
576 576 def iteritems(d, **kw):
577 577 return iter(d.iteritems(**kw))
578 578
579 579 def iterlists(d, **kw):
580 580 return iter(d.iterlists(**kw))
581 581
582 582 viewkeys = operator.methodcaller("viewkeys")
583 583
584 584 viewvalues = operator.methodcaller("viewvalues")
585 585
586 586 viewitems = operator.methodcaller("viewitems")
587 587
588 588 _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
589 589 _add_doc(itervalues, "Return an iterator over the values of a dictionary.")
590 590 _add_doc(iteritems,
591 591 "Return an iterator over the (key, value) pairs of a dictionary.")
592 592 _add_doc(iterlists,
593 593 "Return an iterator over the (key, [values]) pairs of a dictionary.")
594 594
595 595
596 596 if PY3:
597 597 def b(s):
598 598 return s.encode("latin-1")
599 599 def u(s):
600 600 return s
601 601 unichr = chr
602 602 if sys.version_info[1] <= 1:
603 603 def int2byte(i):
604 604 return bytes((i,))
605 605 else:
606 606 # This is about 2x faster than the implementation above on 3.2+
607 607 int2byte = operator.methodcaller("to_bytes", 1, "big")
608 608 byte2int = operator.itemgetter(0)
609 609 indexbytes = operator.getitem
610 610 iterbytes = iter
611 611 import io
612 612 StringIO = io.StringIO
613 613 BytesIO = io.BytesIO
614 614 _assertCountEqual = "assertCountEqual"
615 615 _assertRaisesRegex = "assertRaisesRegex"
616 616 _assertRegex = "assertRegex"
617 617 else:
618 618 def b(s):
619 619 return s
620 620 # Workaround for standalone backslash
621 621 def u(s):
622 622 return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
623 623 unichr = unichr
624 624 int2byte = chr
625 625 def byte2int(bs):
626 626 return ord(bs[0])
627 627 def indexbytes(buf, i):
628 628 return ord(buf[i])
629 629 iterbytes = functools.partial(itertools.imap, ord)
630 630 from io import StringIO
631 631 StringIO = BytesIO = StringIO.StringIO
632 632 _assertCountEqual = "assertItemsEqual"
633 633 _assertRaisesRegex = "assertRaisesRegexp"
634 634 _assertRegex = "assertRegexpMatches"
635 635 _add_doc(b, """Byte literal""")
636 636 _add_doc(u, """Text literal""")
637 637
638 638
639 639 def assertCountEqual(self, *args, **kwargs):
640 640 return getattr(self, _assertCountEqual)(*args, **kwargs)
641 641
642 642
643 643 def assertRaisesRegex(self, *args, **kwargs):
644 644 return getattr(self, _assertRaisesRegex)(*args, **kwargs)
645 645
646 646
647 647 def assertRegex(self, *args, **kwargs):
648 648 return getattr(self, _assertRegex)(*args, **kwargs)
649 649
650 650
651 651 if PY3:
652 652 exec_ = getattr(moves.builtins, "exec")
653 653
654 654
655 655 def reraise(tp, value, tb=None):
656 656 if value is None:
657 657 value = tp()
658 658 if value.__traceback__ is not tb:
659 659 raise value.with_traceback(tb)
660 660 raise value
661 661
662 662 else:
663 663 def exec_(_code_, _globs_=None, _locs_=None):
664 664 """Execute code in a namespace."""
665 665 if _globs_ is None:
666 666 frame = sys._getframe(1)
667 667 _globs_ = frame.f_globals
668 668 if _locs_ is None:
669 669 _locs_ = frame.f_locals
670 670 del frame
671 671 elif _locs_ is None:
672 672 _locs_ = _globs_
673 673 exec("""exec _code_ in _globs_, _locs_""")
674 674
675 675
676 676 exec_("""def reraise(tp, value, tb=None):
677 677 raise tp, value, tb
678 678 """)
679 679
680 680
681 681 if sys.version_info[:2] == (3, 2):
682 682 exec_("""def raise_from(value, from_value):
683 683 if from_value is None:
684 684 raise value
685 685 raise value from from_value
686 686 """)
687 687 elif sys.version_info[:2] > (3, 2):
688 688 exec_("""def raise_from(value, from_value):
689 689 raise value from from_value
690 690 """)
691 691 else:
692 692 def raise_from(value, from_value):
693 693 raise value
694 694
695 695
696 696 print_ = getattr(moves.builtins, "print", None)
697 697 if print_ is None:
698 698 def print_(*args, **kwargs):
699 699 """The new-style print function for Python 2.4 and 2.5."""
700 700 fp = kwargs.pop("file", sys.stdout)
701 701 if fp is None:
702 702 return
703 703 def write(data):
704 704 if not isinstance(data, str):
705 705 data = str(data)
706 706 # If the file has an encoding, encode unicode with it.
707 707 if (isinstance(fp, file) and
708 708 isinstance(data, unicode) and
709 709 fp.encoding is not None):
710 710 errors = getattr(fp, "errors", None)
711 711 if errors is None:
712 712 errors = "strict"
713 713 data = data.encode(fp.encoding, errors)
714 714 fp.write(data)
715 715 want_unicode = False
716 716 sep = kwargs.pop("sep", None)
717 717 if sep is not None:
718 718 if isinstance(sep, unicode):
719 719 want_unicode = True
720 720 elif not isinstance(sep, str):
721 721 raise TypeError("sep must be None or a string")
722 722 end = kwargs.pop("end", None)
723 723 if end is not None:
724 724 if isinstance(end, unicode):
725 725 want_unicode = True
726 726 elif not isinstance(end, str):
727 727 raise TypeError("end must be None or a string")
728 728 if kwargs:
729 729 raise TypeError("invalid keyword arguments to print()")
730 730 if not want_unicode:
731 731 for arg in args:
732 732 if isinstance(arg, unicode):
733 733 want_unicode = True
734 734 break
735 735 if want_unicode:
736 736 newline = unicode("\n")
737 737 space = unicode(" ")
738 738 else:
739 739 newline = "\n"
740 740 space = " "
741 741 if sep is None:
742 742 sep = space
743 743 if end is None:
744 744 end = newline
745 745 for i, arg in enumerate(args):
746 746 if i:
747 747 write(sep)
748 748 write(arg)
749 749 write(end)
750 750 if sys.version_info[:2] < (3, 3):
751 751 _print = print_
752 752 def print_(*args, **kwargs):
753 753 fp = kwargs.get("file", sys.stdout)
754 754 flush = kwargs.pop("flush", False)
755 755 _print(*args, **kwargs)
756 756 if flush and fp is not None:
757 757 fp.flush()
758 758
759 759 _add_doc(reraise, """Reraise an exception.""")
760 760
761 761 if sys.version_info[0:2] < (3, 4):
762 762 def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
763 763 updated=functools.WRAPPER_UPDATES):
764 764 def wrapper(f):
765 765 f = functools.wraps(wrapped, assigned, updated)(f)
766 766 f.__wrapped__ = wrapped
767 767 return f
768 768 return wrapper
769 769 else:
770 770 wraps = functools.wraps
771 771
772 772 def with_metaclass(meta, *bases):
773 773 """Create a base class with a metaclass."""
774 774 # This requires a bit of explanation: the basic idea is to make a dummy
775 775 # metaclass for one level of class instantiation that replaces itself with
776 776 # the actual metaclass.
777 777 class metaclass(meta):
778 778 def __new__(cls, name, this_bases, d):
779 779 return meta(name, bases, d)
780 780 return type.__new__(metaclass, 'temporary_class', (), {})
781 781
782 782
783 783 def add_metaclass(metaclass):
784 784 """Class decorator for creating a class with a metaclass."""
785 785 def wrapper(cls):
786 786 orig_vars = cls.__dict__.copy()
787 787 slots = orig_vars.get('__slots__')
788 788 if slots is not None:
789 789 if isinstance(slots, str):
790 790 slots = [slots]
791 791 for slots_var in slots:
792 792 orig_vars.pop(slots_var)
793 793 orig_vars.pop('__dict__', None)
794 794 orig_vars.pop('__weakref__', None)
795 795 return metaclass(cls.__name__, cls.__bases__, orig_vars)
796 796 return wrapper
797 797
798 798
799 799 def python_2_unicode_compatible(klass):
800 800 """
801 801 A decorator that defines __unicode__ and __str__ methods under Python 2.
802 802 Under Python 3 it does nothing.
803 803
804 804 To support Python 2 and 3 with a single code base, define a __str__ method
805 805 returning text and apply this decorator to the class.
806 806 """
807 807 if PY2:
808 808 if '__str__' not in klass.__dict__:
809 809 raise ValueError("@python_2_unicode_compatible cannot be applied "
810 810 "to %s because it doesn't define __str__()." %
811 811 klass.__name__)
812 812 klass.__unicode__ = klass.__str__
813 813 klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
814 814 return klass
815 815
816 816
817 817 # Complete the moves implementation.
818 818 # This code is at the end of this module to speed up module loading.
819 819 # Turn this module into a package.
820 820 __path__ = [] # required for PEP 302 and PEP 451
821 821 __package__ = __name__ # see PEP 366 @ReservedAssignment
822 822 if globals().get("__spec__") is not None:
823 823 __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable
824 824 # Remove other six meta path importers, since they cause problems. This can
825 825 # happen if six is removed from sys.modules and then reloaded. (Setuptools does
826 826 # this for some reason.)
827 827 if sys.meta_path:
828 828 for i, importer in enumerate(sys.meta_path):
829 829 # Here's some real nastiness: Another "instance" of the six module might
830 830 # be floating around. Therefore, we can't use isinstance() to check for
831 831 # the six meta path importer, since the other six instance will have
832 832 # inserted an importer with different class.
833 833 if (type(importer).__name__ == "_SixMetaPathImporter" and
834 834 importer.name == __name__):
835 835 del sys.meta_path[i]
836 836 break
837 837 del i, importer
838 838 # Finally, add the importer to the meta path import hook.
839 839 sys.meta_path.append(_importer)
@@ -1,2155 +1,2155 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2020 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Helper functions
23 23
24 24 Consists of functions to typically be used within templates, but also
25 25 available to Controllers. This module is available to both as 'h'.
26 26 """
27 27 import base64
28 28 import collections
29 29
30 30 import os
31 31 import random
32 32 import hashlib
33 33 from io import StringIO
34 34 import textwrap
35 35 import urllib.request, urllib.parse, urllib.error
36 36 import math
37 37 import logging
38 38 import re
39 39 import time
40 40 import string
41 41 import hashlib
42 42 import regex
43 43 from collections import OrderedDict
44 44
45 45 import pygments
46 46 import itertools
47 47 import fnmatch
48 48 import bleach
49 49
50 50 from datetime import datetime
51 51 from functools import partial
52 52 from pygments.formatters.html import HtmlFormatter
53 53 from pygments.lexers import (
54 54 get_lexer_by_name, get_lexer_for_filename, get_lexer_for_mimetype)
55 55
56 56 from pyramid.threadlocal import get_current_request
57 57 from tempita import looper
58 58 from webhelpers2.html import literal, HTML, escape
59 59 from webhelpers2.html._autolink import _auto_link_urls
60 60 from webhelpers2.html.tools import (
61 61 button_to, highlight, js_obfuscate, strip_links, strip_tags)
62 62
63 63 from webhelpers2.text import (
64 64 chop_at, collapse, convert_accented_entities,
65 65 convert_misc_entities, lchop, plural, rchop, remove_formatting,
66 66 replace_whitespace, urlify, truncate, wrap_paragraphs)
67 67 from webhelpers2.date import time_ago_in_words
68 68
69 69 from webhelpers2.html.tags import (
70 70 _input, NotGiven, _make_safe_id_component as safeid,
71 71 form as insecure_form,
72 72 auto_discovery_link, checkbox, end_form, file,
73 73 hidden, image, javascript_link, link_to, link_to_if, link_to_unless, ol,
74 74 select as raw_select, stylesheet_link, submit, text, password, textarea,
75 75 ul, radio, Options)
76 76
77 77 from webhelpers2.number import format_byte_size
78 78
79 79 from rhodecode.lib.action_parser import action_parser
80 80 from rhodecode.lib.pagination import Page, RepoPage, SqlPage
81 81 from rhodecode.lib.ext_json import json
82 82 from rhodecode.lib.utils import repo_name_slug, get_custom_lexer
83 83 from rhodecode.lib.utils2 import (
84 84 str2bool, safe_unicode, safe_str,
85 85 get_commit_safe, datetime_to_time, time_to_datetime, time_to_utcdatetime,
86 86 AttributeDict, safe_int, md5, md5_safe, get_host_info)
87 87 from rhodecode.lib.markup_renderer import MarkupRenderer, relative_links
88 88 from rhodecode.lib.vcs.exceptions import CommitDoesNotExistError
89 89 from rhodecode.lib.vcs.backends.base import BaseChangeset, EmptyCommit
90 90 from rhodecode.lib.vcs.conf.settings import ARCHIVE_SPECS
91 91 from rhodecode.lib.index.search_utils import get_matching_line_offsets
92 92 from rhodecode.config.conf import DATE_FORMAT, DATETIME_FORMAT
93 93 from rhodecode.model.changeset_status import ChangesetStatusModel
94 94 from rhodecode.model.db import Permission, User, Repository, UserApiKeys, FileStore
95 95 from rhodecode.model.repo_group import RepoGroupModel
96 96 from rhodecode.model.settings import IssueTrackerSettingsModel
97 97
98 98
99 99 log = logging.getLogger(__name__)
100 100
101 101
102 102 DEFAULT_USER = User.DEFAULT_USER
103 103 DEFAULT_USER_EMAIL = User.DEFAULT_USER_EMAIL
104 104
105 105
106 106 def asset(path, ver=None, **kwargs):
107 107 """
108 108 Helper to generate a static asset file path for rhodecode assets
109 109
110 110 eg. h.asset('images/image.png', ver='3923')
111 111
112 112 :param path: path of asset
113 113 :param ver: optional version query param to append as ?ver=
114 114 """
115 115 request = get_current_request()
116 116 query = {}
117 117 query.update(kwargs)
118 118 if ver:
119 119 query = {'ver': ver}
120 120 return request.static_path(
121 121 'rhodecode:public/{}'.format(path), _query=query)
122 122
123 123
124 124 default_html_escape_table = {
125 125 ord('&'): u'&amp;',
126 126 ord('<'): u'&lt;',
127 127 ord('>'): u'&gt;',
128 128 ord('"'): u'&quot;',
129 129 ord("'"): u'&#39;',
130 130 }
131 131
132 132
133 133 def html_escape(text, html_escape_table=default_html_escape_table):
134 134 """Produce entities within text."""
135 135 return text.translate(html_escape_table)
136 136
137 137
138 138 def chop_at_smart(s, sub, inclusive=False, suffix_if_chopped=None):
139 139 """
140 140 Truncate string ``s`` at the first occurrence of ``sub``.
141 141
142 142 If ``inclusive`` is true, truncate just after ``sub`` rather than at it.
143 143 """
144 144 suffix_if_chopped = suffix_if_chopped or ''
145 145 pos = s.find(sub)
146 146 if pos == -1:
147 147 return s
148 148
149 149 if inclusive:
150 150 pos += len(sub)
151 151
152 152 chopped = s[:pos]
153 153 left = s[pos:].strip()
154 154
155 155 if left and suffix_if_chopped:
156 156 chopped += suffix_if_chopped
157 157
158 158 return chopped
159 159
160 160
161 161 def shorter(text, size=20, prefix=False):
162 162 postfix = '...'
163 163 if len(text) > size:
164 164 if prefix:
165 165 # shorten in front
166 166 return postfix + text[-(size - len(postfix)):]
167 167 else:
168 168 return text[:size - len(postfix)] + postfix
169 169 return text
170 170
171 171
172 172 def reset(name, value=None, id=NotGiven, type="reset", **attrs):
173 173 """
174 174 Reset button
175 175 """
176 176 return _input(type, name, value, id, attrs)
177 177
178 178
179 179 def select(name, selected_values, options, id=NotGiven, **attrs):
180 180
181 181 if isinstance(options, (list, tuple)):
182 182 options_iter = options
183 183 # Handle old value,label lists ... where value also can be value,label lists
184 184 options = Options()
185 185 for opt in options_iter:
186 186 if isinstance(opt, tuple) and len(opt) == 2:
187 187 value, label = opt
188 188 elif isinstance(opt, str):
189 189 value = label = opt
190 190 else:
191 191 raise ValueError('invalid select option type %r' % type(opt))
192 192
193 193 if isinstance(value, (list, tuple)):
194 194 option_group = options.add_optgroup(label)
195 195 for opt2 in value:
196 196 if isinstance(opt2, tuple) and len(opt2) == 2:
197 197 group_value, group_label = opt2
198 198 elif isinstance(opt2, str):
199 199 group_value = group_label = opt2
200 200 else:
201 201 raise ValueError('invalid select option type %r' % type(opt2))
202 202
203 203 option_group.add_option(group_label, group_value)
204 204 else:
205 205 options.add_option(label, value)
206 206
207 207 return raw_select(name, selected_values, options, id=id, **attrs)
208 208
209 209
210 210 def branding(name, length=40):
211 211 return truncate(name, length, indicator="")
212 212
213 213
214 214 def FID(raw_id, path):
215 215 """
216 216 Creates a unique ID for filenode based on it's hash of path and commit
217 217 it's safe to use in urls
218 218
219 219 :param raw_id:
220 220 :param path:
221 221 """
222 222
223 223 return 'c-%s-%s' % (short_id(raw_id), md5_safe(path)[:12])
224 224
225 225
226 226 class _GetError(object):
227 227 """Get error from form_errors, and represent it as span wrapped error
228 228 message
229 229
230 230 :param field_name: field to fetch errors for
231 231 :param form_errors: form errors dict
232 232 """
233 233
234 234 def __call__(self, field_name, form_errors):
235 235 tmpl = """<span class="error_msg">%s</span>"""
236 236 if form_errors and field_name in form_errors:
237 237 return literal(tmpl % form_errors.get(field_name))
238 238
239 239
240 240 get_error = _GetError()
241 241
242 242
243 243 class _ToolTip(object):
244 244
245 245 def __call__(self, tooltip_title, trim_at=50):
246 246 """
247 247 Special function just to wrap our text into nice formatted
248 248 autowrapped text
249 249
250 250 :param tooltip_title:
251 251 """
252 252 tooltip_title = escape(tooltip_title)
253 253 tooltip_title = tooltip_title.replace('<', '&lt;').replace('>', '&gt;')
254 254 return tooltip_title
255 255
256 256
257 257 tooltip = _ToolTip()
258 258
259 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 262 def files_breadcrumbs(repo_name, repo_type, commit_id, file_path, landing_ref_name=None, at_ref=None,
263 263 limit_items=False, linkify_last_item=False, hide_last_item=False,
264 264 copy_path_icon=True):
265 265 if isinstance(file_path, str):
266 266 file_path = safe_unicode(file_path)
267 267
268 268 if at_ref:
269 269 route_qry = {'at': at_ref}
270 270 default_landing_ref = at_ref or landing_ref_name or commit_id
271 271 else:
272 272 route_qry = None
273 273 default_landing_ref = commit_id
274 274
275 275 # first segment is a `HOME` link to repo files root location
276 276 root_name = literal(u'<i class="icon-home"></i>')
277 277
278 278 url_segments = [
279 279 link_to(
280 280 root_name,
281 281 repo_files_by_ref_url(
282 282 repo_name,
283 283 repo_type,
284 284 f_path=None, # None here is a special case for SVN repos,
285 285 # that won't prefix with a ref
286 286 ref_name=default_landing_ref,
287 287 commit_id=commit_id,
288 288 query=route_qry
289 289 )
290 290 )]
291 291
292 292 path_segments = file_path.split('/')
293 293 last_cnt = len(path_segments) - 1
294 294 for cnt, segment in enumerate(path_segments):
295 295 if not segment:
296 296 continue
297 297 segment_html = escape(segment)
298 298
299 299 last_item = cnt == last_cnt
300 300
301 301 if last_item and hide_last_item:
302 302 # iterate over and hide last element
303 303 continue
304 304
305 305 if last_item and linkify_last_item is False:
306 306 # plain version
307 307 url_segments.append(segment_html)
308 308 else:
309 309 url_segments.append(
310 310 link_to(
311 311 segment_html,
312 312 repo_files_by_ref_url(
313 313 repo_name,
314 314 repo_type,
315 315 f_path='/'.join(path_segments[:cnt + 1]),
316 316 ref_name=default_landing_ref,
317 317 commit_id=commit_id,
318 318 query=route_qry
319 319 ),
320 320 ))
321 321
322 322 limited_url_segments = url_segments[:1] + ['...'] + url_segments[-5:]
323 323 if limit_items and len(limited_url_segments) < len(url_segments):
324 324 url_segments = limited_url_segments
325 325
326 326 full_path = file_path
327 327 if copy_path_icon:
328 328 icon = files_icon.format(escape(full_path))
329 329 else:
330 330 icon = ''
331 331
332 332 if file_path == '':
333 333 return root_name
334 334 else:
335 335 return literal(' / '.join(url_segments) + icon)
336 336
337 337
338 338 def files_url_data(request):
339 339 import urllib.request, urllib.parse, urllib.error
340 340 matchdict = request.matchdict
341 341
342 342 if 'f_path' not in matchdict:
343 343 matchdict['f_path'] = ''
344 344 else:
345 345 matchdict['f_path'] = urllib.parse.quote(safe_str(matchdict['f_path']))
346 346 if 'commit_id' not in matchdict:
347 347 matchdict['commit_id'] = 'tip'
348 348
349 349 return json.dumps(matchdict)
350 350
351 351
352 352 def repo_files_by_ref_url(db_repo_name, db_repo_type, f_path, ref_name, commit_id, query=None, ):
353 353 _is_svn = is_svn(db_repo_type)
354 354 final_f_path = f_path
355 355
356 356 if _is_svn:
357 357 """
358 358 For SVN the ref_name cannot be used as a commit_id, it needs to be prefixed with
359 359 actually commit_id followed by the ref_name. This should be done only in case
360 360 This is a initial landing url, without additional paths.
361 361
362 362 like: /1000/tags/1.0.0/?at=tags/1.0.0
363 363 """
364 364
365 365 if ref_name and ref_name != 'tip':
366 366 # NOTE(marcink): for svn the ref_name is actually the stored path, so we prefix it
367 367 # for SVN we only do this magic prefix if it's root, .eg landing revision
368 368 # of files link. If we are in the tree we don't need this since we traverse the url
369 369 # that has everything stored
370 370 if f_path in ['', '/']:
371 371 final_f_path = '/'.join([ref_name, f_path])
372 372
373 373 # SVN always needs a commit_id explicitly, without a named REF
374 374 default_commit_id = commit_id
375 375 else:
376 376 """
377 377 For git and mercurial we construct a new URL using the names instead of commit_id
378 378 like: /master/some_path?at=master
379 379 """
380 380 # We currently do not support branches with slashes
381 381 if '/' in ref_name:
382 382 default_commit_id = commit_id
383 383 else:
384 384 default_commit_id = ref_name
385 385
386 386 # sometimes we pass f_path as None, to indicate explicit no prefix,
387 387 # we translate it to string to not have None
388 388 final_f_path = final_f_path or ''
389 389
390 390 files_url = route_path(
391 391 'repo_files',
392 392 repo_name=db_repo_name,
393 393 commit_id=default_commit_id,
394 394 f_path=final_f_path,
395 395 _query=query
396 396 )
397 397 return files_url
398 398
399 399
400 400 def code_highlight(code, lexer, formatter, use_hl_filter=False):
401 401 """
402 402 Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``.
403 403
404 404 If ``outfile`` is given and a valid file object (an object
405 405 with a ``write`` method), the result will be written to it, otherwise
406 406 it is returned as a string.
407 407 """
408 408 if use_hl_filter:
409 409 # add HL filter
410 410 from rhodecode.lib.index import search_utils
411 411 lexer.add_filter(search_utils.ElasticSearchHLFilter())
412 412 return pygments.format(pygments.lex(code, lexer), formatter)
413 413
414 414
415 415 class CodeHtmlFormatter(HtmlFormatter):
416 416 """
417 417 My code Html Formatter for source codes
418 418 """
419 419
420 420 def wrap(self, source, outfile):
421 421 return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
422 422
423 423 def _wrap_code(self, source):
424 424 for cnt, it in enumerate(source):
425 425 i, t = it
426 426 t = '<div id="L%s">%s</div>' % (cnt + 1, t)
427 427 yield i, t
428 428
429 429 def _wrap_tablelinenos(self, inner):
430 430 dummyoutfile = StringIO.StringIO()
431 431 lncount = 0
432 432 for t, line in inner:
433 433 if t:
434 434 lncount += 1
435 435 dummyoutfile.write(line)
436 436
437 437 fl = self.linenostart
438 438 mw = len(str(lncount + fl - 1))
439 439 sp = self.linenospecial
440 440 st = self.linenostep
441 441 la = self.lineanchors
442 442 aln = self.anchorlinenos
443 443 nocls = self.noclasses
444 444 if sp:
445 445 lines = []
446 446
447 447 for i in range(fl, fl + lncount):
448 448 if i % st == 0:
449 449 if i % sp == 0:
450 450 if aln:
451 451 lines.append('<a href="#%s%d" class="special">%*d</a>' %
452 452 (la, i, mw, i))
453 453 else:
454 454 lines.append('<span class="special">%*d</span>' % (mw, i))
455 455 else:
456 456 if aln:
457 457 lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i))
458 458 else:
459 459 lines.append('%*d' % (mw, i))
460 460 else:
461 461 lines.append('')
462 462 ls = '\n'.join(lines)
463 463 else:
464 464 lines = []
465 465 for i in range(fl, fl + lncount):
466 466 if i % st == 0:
467 467 if aln:
468 468 lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i))
469 469 else:
470 470 lines.append('%*d' % (mw, i))
471 471 else:
472 472 lines.append('')
473 473 ls = '\n'.join(lines)
474 474
475 475 # in case you wonder about the seemingly redundant <div> here: since the
476 476 # content in the other cell also is wrapped in a div, some browsers in
477 477 # some configurations seem to mess up the formatting...
478 478 if nocls:
479 479 yield 0, ('<table class="%stable">' % self.cssclass +
480 480 '<tr><td><div class="linenodiv" '
481 481 'style="background-color: #f0f0f0; padding-right: 10px">'
482 482 '<pre style="line-height: 125%">' +
483 483 ls + '</pre></div></td><td id="hlcode" class="code">')
484 484 else:
485 485 yield 0, ('<table class="%stable">' % self.cssclass +
486 486 '<tr><td class="linenos"><div class="linenodiv"><pre>' +
487 487 ls + '</pre></div></td><td id="hlcode" class="code">')
488 488 yield 0, dummyoutfile.getvalue()
489 489 yield 0, '</td></tr></table>'
490 490
491 491
492 492 class SearchContentCodeHtmlFormatter(CodeHtmlFormatter):
493 493 def __init__(self, **kw):
494 494 # only show these line numbers if set
495 495 self.only_lines = kw.pop('only_line_numbers', [])
496 496 self.query_terms = kw.pop('query_terms', [])
497 497 self.max_lines = kw.pop('max_lines', 5)
498 498 self.line_context = kw.pop('line_context', 3)
499 499 self.url = kw.pop('url', None)
500 500
501 501 super(CodeHtmlFormatter, self).__init__(**kw)
502 502
503 503 def _wrap_code(self, source):
504 504 for cnt, it in enumerate(source):
505 505 i, t = it
506 506 t = '<pre>%s</pre>' % t
507 507 yield i, t
508 508
509 509 def _wrap_tablelinenos(self, inner):
510 510 yield 0, '<table class="code-highlight %stable">' % self.cssclass
511 511
512 512 last_shown_line_number = 0
513 513 current_line_number = 1
514 514
515 515 for t, line in inner:
516 516 if not t:
517 517 yield t, line
518 518 continue
519 519
520 520 if current_line_number in self.only_lines:
521 521 if last_shown_line_number + 1 != current_line_number:
522 522 yield 0, '<tr>'
523 523 yield 0, '<td class="line">...</td>'
524 524 yield 0, '<td id="hlcode" class="code"></td>'
525 525 yield 0, '</tr>'
526 526
527 527 yield 0, '<tr>'
528 528 if self.url:
529 529 yield 0, '<td class="line"><a href="%s#L%i">%i</a></td>' % (
530 530 self.url, current_line_number, current_line_number)
531 531 else:
532 532 yield 0, '<td class="line"><a href="">%i</a></td>' % (
533 533 current_line_number)
534 534 yield 0, '<td id="hlcode" class="code">' + line + '</td>'
535 535 yield 0, '</tr>'
536 536
537 537 last_shown_line_number = current_line_number
538 538
539 539 current_line_number += 1
540 540
541 541 yield 0, '</table>'
542 542
543 543
544 544 def hsv_to_rgb(h, s, v):
545 545 """ Convert hsv color values to rgb """
546 546
547 547 if s == 0.0:
548 548 return v, v, v
549 549 i = int(h * 6.0) # XXX assume int() truncates!
550 550 f = (h * 6.0) - i
551 551 p = v * (1.0 - s)
552 552 q = v * (1.0 - s * f)
553 553 t = v * (1.0 - s * (1.0 - f))
554 554 i = i % 6
555 555 if i == 0:
556 556 return v, t, p
557 557 if i == 1:
558 558 return q, v, p
559 559 if i == 2:
560 560 return p, v, t
561 561 if i == 3:
562 562 return p, q, v
563 563 if i == 4:
564 564 return t, p, v
565 565 if i == 5:
566 566 return v, p, q
567 567
568 568
569 569 def unique_color_generator(n=10000, saturation=0.10, lightness=0.95):
570 570 """
571 571 Generator for getting n of evenly distributed colors using
572 572 hsv color and golden ratio. It always return same order of colors
573 573
574 574 :param n: number of colors to generate
575 575 :param saturation: saturation of returned colors
576 576 :param lightness: lightness of returned colors
577 577 :returns: RGB tuple
578 578 """
579 579
580 580 golden_ratio = 0.618033988749895
581 581 h = 0.22717784590367374
582 582
583 583 for _ in range(n):
584 584 h += golden_ratio
585 585 h %= 1
586 586 HSV_tuple = [h, saturation, lightness]
587 587 RGB_tuple = hsv_to_rgb(*HSV_tuple)
588 588 yield map(lambda x: str(int(x * 256)), RGB_tuple)
589 589
590 590
591 591 def color_hasher(n=10000, saturation=0.10, lightness=0.95):
592 592 """
593 593 Returns a function which when called with an argument returns a unique
594 594 color for that argument, eg.
595 595
596 596 :param n: number of colors to generate
597 597 :param saturation: saturation of returned colors
598 598 :param lightness: lightness of returned colors
599 599 :returns: css RGB string
600 600
601 601 >>> color_hash = color_hasher()
602 602 >>> color_hash('hello')
603 603 'rgb(34, 12, 59)'
604 604 >>> color_hash('hello')
605 605 'rgb(34, 12, 59)'
606 606 >>> color_hash('other')
607 607 'rgb(90, 224, 159)'
608 608 """
609 609
610 610 color_dict = {}
611 611 cgenerator = unique_color_generator(
612 612 saturation=saturation, lightness=lightness)
613 613
614 614 def get_color_string(thing):
615 615 if thing in color_dict:
616 616 col = color_dict[thing]
617 617 else:
618 col = color_dict[thing] = cgenerator.next()
618 col = color_dict[thing] = next(cgenerator)
619 619 return "rgb(%s)" % (', '.join(col))
620 620
621 621 return get_color_string
622 622
623 623
624 624 def get_lexer_safe(mimetype=None, filepath=None):
625 625 """
626 626 Tries to return a relevant pygments lexer using mimetype/filepath name,
627 627 defaulting to plain text if none could be found
628 628 """
629 629 lexer = None
630 630 try:
631 631 if mimetype:
632 632 lexer = get_lexer_for_mimetype(mimetype)
633 633 if not lexer:
634 634 lexer = get_lexer_for_filename(filepath)
635 635 except pygments.util.ClassNotFound:
636 636 pass
637 637
638 638 if not lexer:
639 639 lexer = get_lexer_by_name('text')
640 640
641 641 return lexer
642 642
643 643
644 644 def get_lexer_for_filenode(filenode):
645 645 lexer = get_custom_lexer(filenode.extension) or filenode.lexer
646 646 return lexer
647 647
648 648
649 649 def pygmentize(filenode, **kwargs):
650 650 """
651 651 pygmentize function using pygments
652 652
653 653 :param filenode:
654 654 """
655 655 lexer = get_lexer_for_filenode(filenode)
656 656 return literal(code_highlight(filenode.content, lexer,
657 657 CodeHtmlFormatter(**kwargs)))
658 658
659 659
660 660 def is_following_repo(repo_name, user_id):
661 661 from rhodecode.model.scm import ScmModel
662 662 return ScmModel().is_following_repo(repo_name, user_id)
663 663
664 664
665 665 class _Message(object):
666 666 """A message returned by ``Flash.pop_messages()``.
667 667
668 668 Converting the message to a string returns the message text. Instances
669 669 also have the following attributes:
670 670
671 671 * ``message``: the message text.
672 672 * ``category``: the category specified when the message was created.
673 673 """
674 674
675 675 def __init__(self, category, message, sub_data=None):
676 676 self.category = category
677 677 self.message = message
678 678 self.sub_data = sub_data or {}
679 679
680 680 def __str__(self):
681 681 return self.message
682 682
683 683 __unicode__ = __str__
684 684
685 685 def __html__(self):
686 686 return escape(safe_unicode(self.message))
687 687
688 688
689 689 class Flash(object):
690 690 # List of allowed categories. If None, allow any category.
691 691 categories = ["warning", "notice", "error", "success"]
692 692
693 693 # Default category if none is specified.
694 694 default_category = "notice"
695 695
696 696 def __init__(self, session_key="flash", categories=None,
697 697 default_category=None):
698 698 """
699 699 Instantiate a ``Flash`` object.
700 700
701 701 ``session_key`` is the key to save the messages under in the user's
702 702 session.
703 703
704 704 ``categories`` is an optional list which overrides the default list
705 705 of categories.
706 706
707 707 ``default_category`` overrides the default category used for messages
708 708 when none is specified.
709 709 """
710 710 self.session_key = session_key
711 711 if categories is not None:
712 712 self.categories = categories
713 713 if default_category is not None:
714 714 self.default_category = default_category
715 715 if self.categories and self.default_category not in self.categories:
716 716 raise ValueError(
717 717 "unrecognized default category %r" % (self.default_category,))
718 718
719 719 def pop_messages(self, session=None, request=None):
720 720 """
721 721 Return all accumulated messages and delete them from the session.
722 722
723 723 The return value is a list of ``Message`` objects.
724 724 """
725 725 messages = []
726 726
727 727 if not session:
728 728 if not request:
729 729 request = get_current_request()
730 730 session = request.session
731 731
732 732 # Pop the 'old' pylons flash messages. They are tuples of the form
733 733 # (category, message)
734 734 for cat, msg in session.pop(self.session_key, []):
735 735 messages.append(_Message(cat, msg))
736 736
737 737 # Pop the 'new' pyramid flash messages for each category as list
738 738 # of strings.
739 739 for cat in self.categories:
740 740 for msg in session.pop_flash(queue=cat):
741 741 sub_data = {}
742 742 if hasattr(msg, 'rsplit'):
743 743 flash_data = msg.rsplit('|DELIM|', 1)
744 744 org_message = flash_data[0]
745 745 if len(flash_data) > 1:
746 746 sub_data = json.loads(flash_data[1])
747 747 else:
748 748 org_message = msg
749 749
750 750 messages.append(_Message(cat, org_message, sub_data=sub_data))
751 751
752 752 # Map messages from the default queue to the 'notice' category.
753 753 for msg in session.pop_flash():
754 754 messages.append(_Message('notice', msg))
755 755
756 756 session.save()
757 757 return messages
758 758
759 759 def json_alerts(self, session=None, request=None):
760 760 payloads = []
761 761 messages = flash.pop_messages(session=session, request=request) or []
762 762 for message in messages:
763 763 payloads.append({
764 764 'message': {
765 765 'message': u'{}'.format(message.message),
766 766 'level': message.category,
767 767 'force': True,
768 768 'subdata': message.sub_data
769 769 }
770 770 })
771 771 return json.dumps(payloads)
772 772
773 773 def __call__(self, message, category=None, ignore_duplicate=True,
774 774 session=None, request=None):
775 775
776 776 if not session:
777 777 if not request:
778 778 request = get_current_request()
779 779 session = request.session
780 780
781 781 session.flash(
782 782 message, queue=category, allow_duplicate=not ignore_duplicate)
783 783
784 784
785 785 flash = Flash()
786 786
787 787 #==============================================================================
788 788 # SCM FILTERS available via h.
789 789 #==============================================================================
790 790 from rhodecode.lib.vcs.utils import author_name, author_email
791 791 from rhodecode.lib.utils2 import age, age_from_seconds
792 792 from rhodecode.model.db import User, ChangesetStatus
793 793
794 794
795 795 email = author_email
796 796
797 797
798 798 def capitalize(raw_text):
799 799 return raw_text.capitalize()
800 800
801 801
802 802 def short_id(long_id):
803 803 return long_id[:12]
804 804
805 805
806 806 def hide_credentials(url):
807 807 from rhodecode.lib.utils2 import credentials_filter
808 808 return credentials_filter(url)
809 809
810 810
811 811 import pytz
812 812 import tzlocal
813 813 local_timezone = tzlocal.get_localzone()
814 814
815 815
816 816 def get_timezone(datetime_iso, time_is_local=False):
817 817 tzinfo = '+00:00'
818 818
819 819 # detect if we have a timezone info, otherwise, add it
820 820 if time_is_local and isinstance(datetime_iso, datetime) and not datetime_iso.tzinfo:
821 821 force_timezone = os.environ.get('RC_TIMEZONE', '')
822 822 if force_timezone:
823 823 force_timezone = pytz.timezone(force_timezone)
824 824 timezone = force_timezone or local_timezone
825 825 offset = timezone.localize(datetime_iso).strftime('%z')
826 826 tzinfo = '{}:{}'.format(offset[:-2], offset[-2:])
827 827 return tzinfo
828 828
829 829
830 830 def age_component(datetime_iso, value=None, time_is_local=False, tooltip=True):
831 831 title = value or format_date(datetime_iso)
832 832 tzinfo = get_timezone(datetime_iso, time_is_local=time_is_local)
833 833
834 834 return literal(
835 835 '<time class="timeago {cls}" title="{tt_title}" datetime="{dt}{tzinfo}">{title}</time>'.format(
836 836 cls='tooltip' if tooltip else '',
837 837 tt_title=('{title}{tzinfo}'.format(title=title, tzinfo=tzinfo)) if tooltip else '',
838 838 title=title, dt=datetime_iso, tzinfo=tzinfo
839 839 ))
840 840
841 841
842 842 def _shorten_commit_id(commit_id, commit_len=None):
843 843 if commit_len is None:
844 844 request = get_current_request()
845 845 commit_len = request.call_context.visual.show_sha_length
846 846 return commit_id[:commit_len]
847 847
848 848
849 849 def show_id(commit, show_idx=None, commit_len=None):
850 850 """
851 851 Configurable function that shows ID
852 852 by default it's r123:fffeeefffeee
853 853
854 854 :param commit: commit instance
855 855 """
856 856 if show_idx is None:
857 857 request = get_current_request()
858 858 show_idx = request.call_context.visual.show_revision_number
859 859
860 860 raw_id = _shorten_commit_id(commit.raw_id, commit_len=commit_len)
861 861 if show_idx:
862 862 return 'r%s:%s' % (commit.idx, raw_id)
863 863 else:
864 864 return '%s' % (raw_id, )
865 865
866 866
867 867 def format_date(date):
868 868 """
869 869 use a standardized formatting for dates used in RhodeCode
870 870
871 871 :param date: date/datetime object
872 872 :return: formatted date
873 873 """
874 874
875 875 if date:
876 876 _fmt = "%a, %d %b %Y %H:%M:%S"
877 877 return safe_unicode(date.strftime(_fmt))
878 878
879 879 return u""
880 880
881 881
882 882 class _RepoChecker(object):
883 883
884 884 def __init__(self, backend_alias):
885 885 self._backend_alias = backend_alias
886 886
887 887 def __call__(self, repository):
888 888 if hasattr(repository, 'alias'):
889 889 _type = repository.alias
890 890 elif hasattr(repository, 'repo_type'):
891 891 _type = repository.repo_type
892 892 else:
893 893 _type = repository
894 894 return _type == self._backend_alias
895 895
896 896
897 897 is_git = _RepoChecker('git')
898 898 is_hg = _RepoChecker('hg')
899 899 is_svn = _RepoChecker('svn')
900 900
901 901
902 902 def get_repo_type_by_name(repo_name):
903 903 repo = Repository.get_by_repo_name(repo_name)
904 904 if repo:
905 905 return repo.repo_type
906 906
907 907
908 908 def is_svn_without_proxy(repository):
909 909 if is_svn(repository):
910 910 from rhodecode.model.settings import VcsSettingsModel
911 911 conf = VcsSettingsModel().get_ui_settings_as_config_obj()
912 912 return not str2bool(conf.get('vcs_svn_proxy', 'http_requests_enabled'))
913 913 return False
914 914
915 915
916 916 def discover_user(author):
917 917 """
918 918 Tries to discover RhodeCode User based on the author string. Author string
919 919 is typically `FirstName LastName <email@address.com>`
920 920 """
921 921
922 922 # if author is already an instance use it for extraction
923 923 if isinstance(author, User):
924 924 return author
925 925
926 926 # Valid email in the attribute passed, see if they're in the system
927 927 _email = author_email(author)
928 928 if _email != '':
929 929 user = User.get_by_email(_email, case_insensitive=True, cache=True)
930 930 if user is not None:
931 931 return user
932 932
933 933 # Maybe it's a username, we try to extract it and fetch by username ?
934 934 _author = author_name(author)
935 935 user = User.get_by_username(_author, case_insensitive=True, cache=True)
936 936 if user is not None:
937 937 return user
938 938
939 939 return None
940 940
941 941
942 942 def email_or_none(author):
943 943 # extract email from the commit string
944 944 _email = author_email(author)
945 945
946 946 # If we have an email, use it, otherwise
947 947 # see if it contains a username we can get an email from
948 948 if _email != '':
949 949 return _email
950 950 else:
951 951 user = User.get_by_username(
952 952 author_name(author), case_insensitive=True, cache=True)
953 953
954 954 if user is not None:
955 955 return user.email
956 956
957 957 # No valid email, not a valid user in the system, none!
958 958 return None
959 959
960 960
961 961 def link_to_user(author, length=0, **kwargs):
962 962 user = discover_user(author)
963 963 # user can be None, but if we have it already it means we can re-use it
964 964 # in the person() function, so we save 1 intensive-query
965 965 if user:
966 966 author = user
967 967
968 968 display_person = person(author, 'username_or_name_or_email')
969 969 if length:
970 970 display_person = shorter(display_person, length)
971 971
972 972 if user and user.username != user.DEFAULT_USER:
973 973 return link_to(
974 974 escape(display_person),
975 975 route_path('user_profile', username=user.username),
976 976 **kwargs)
977 977 else:
978 978 return escape(display_person)
979 979
980 980
981 981 def link_to_group(users_group_name, **kwargs):
982 982 return link_to(
983 983 escape(users_group_name),
984 984 route_path('user_group_profile', user_group_name=users_group_name),
985 985 **kwargs)
986 986
987 987
988 988 def person(author, show_attr="username_and_name"):
989 989 user = discover_user(author)
990 990 if user:
991 991 return getattr(user, show_attr)
992 992 else:
993 993 _author = author_name(author)
994 994 _email = email(author)
995 995 return _author or _email
996 996
997 997
998 998 def author_string(email):
999 999 if email:
1000 1000 user = User.get_by_email(email, case_insensitive=True, cache=True)
1001 1001 if user:
1002 1002 if user.first_name or user.last_name:
1003 1003 return '%s %s &lt;%s&gt;' % (
1004 1004 user.first_name, user.last_name, email)
1005 1005 else:
1006 1006 return email
1007 1007 else:
1008 1008 return email
1009 1009 else:
1010 1010 return None
1011 1011
1012 1012
1013 1013 def person_by_id(id_, show_attr="username_and_name"):
1014 1014 # attr to return from fetched user
1015 1015 person_getter = lambda usr: getattr(usr, show_attr)
1016 1016
1017 1017 #maybe it's an ID ?
1018 1018 if str(id_).isdigit() or isinstance(id_, int):
1019 1019 id_ = int(id_)
1020 1020 user = User.get(id_)
1021 1021 if user is not None:
1022 1022 return person_getter(user)
1023 1023 return id_
1024 1024
1025 1025
1026 1026 def gravatar_with_user(request, author, show_disabled=False, tooltip=False):
1027 1027 _render = request.get_partial_renderer('rhodecode:templates/base/base.mako')
1028 1028 return _render('gravatar_with_user', author, show_disabled=show_disabled, tooltip=tooltip)
1029 1029
1030 1030
1031 1031 tags_paterns = OrderedDict((
1032 1032 ('lang', (re.compile(r'\[(lang|language)\ \=\&gt;\ *([a-zA-Z\-\/\#\+\.]*)\]'),
1033 1033 '<div class="metatag" tag="lang">\\2</div>')),
1034 1034
1035 1035 ('see', (re.compile(r'\[see\ \=\&gt;\ *([a-zA-Z0-9\/\=\?\&amp;\ \:\/\.\-]*)\]'),
1036 1036 '<div class="metatag" tag="see">see: \\1 </div>')),
1037 1037
1038 1038 ('url', (re.compile(r'\[url\ \=\&gt;\ \[([a-zA-Z0-9\ \.\-\_]+)\]\((http://|https://|/)(.*?)\)\]'),
1039 1039 '<div class="metatag" tag="url"> <a href="\\2\\3">\\1</a> </div>')),
1040 1040
1041 1041 ('license', (re.compile(r'\[license\ \=\&gt;\ *([a-zA-Z0-9\/\=\?\&amp;\ \:\/\.\-]*)\]'),
1042 1042 '<div class="metatag" tag="license"><a href="http:\/\/www.opensource.org/licenses/\\1">\\1</a></div>')),
1043 1043
1044 1044 ('ref', (re.compile(r'\[(requires|recommends|conflicts|base)\ \=\&gt;\ *([a-zA-Z0-9\-\/]*)\]'),
1045 1045 '<div class="metatag" tag="ref \\1">\\1: <a href="/\\2">\\2</a></div>')),
1046 1046
1047 1047 ('state', (re.compile(r'\[(stable|featured|stale|dead|dev|deprecated)\]'),
1048 1048 '<div class="metatag" tag="state \\1">\\1</div>')),
1049 1049
1050 1050 # label in grey
1051 1051 ('label', (re.compile(r'\[([a-z]+)\]'),
1052 1052 '<div class="metatag" tag="label">\\1</div>')),
1053 1053
1054 1054 # generic catch all in grey
1055 1055 ('generic', (re.compile(r'\[([a-zA-Z0-9\.\-\_]+)\]'),
1056 1056 '<div class="metatag" tag="generic">\\1</div>')),
1057 1057 ))
1058 1058
1059 1059
1060 1060 def extract_metatags(value):
1061 1061 """
1062 1062 Extract supported meta-tags from given text value
1063 1063 """
1064 1064 tags = []
1065 1065 if not value:
1066 1066 return tags, ''
1067 1067
1068 1068 for key, val in tags_paterns.items():
1069 1069 pat, replace_html = val
1070 1070 tags.extend([(key, x.group()) for x in pat.finditer(value)])
1071 1071 value = pat.sub('', value)
1072 1072
1073 1073 return tags, value
1074 1074
1075 1075
1076 1076 def style_metatag(tag_type, value):
1077 1077 """
1078 1078 converts tags from value into html equivalent
1079 1079 """
1080 1080 if not value:
1081 1081 return ''
1082 1082
1083 1083 html_value = value
1084 1084 tag_data = tags_paterns.get(tag_type)
1085 1085 if tag_data:
1086 1086 pat, replace_html = tag_data
1087 1087 # convert to plain `unicode` instead of a markup tag to be used in
1088 1088 # regex expressions. safe_unicode doesn't work here
1089 1089 html_value = pat.sub(replace_html, unicode(value))
1090 1090
1091 1091 return html_value
1092 1092
1093 1093
1094 1094 def bool2icon(value, show_at_false=True):
1095 1095 """
1096 1096 Returns boolean value of a given value, represented as html element with
1097 1097 classes that will represent icons
1098 1098
1099 1099 :param value: given value to convert to html node
1100 1100 """
1101 1101
1102 1102 if value: # does bool conversion
1103 1103 return HTML.tag('i', class_="icon-true", title='True')
1104 1104 else: # not true as bool
1105 1105 if show_at_false:
1106 1106 return HTML.tag('i', class_="icon-false", title='False')
1107 1107 return HTML.tag('i')
1108 1108
1109 1109
1110 1110 def b64(inp):
1111 1111 return base64.b64encode(inp)
1112 1112
1113 1113 #==============================================================================
1114 1114 # PERMS
1115 1115 #==============================================================================
1116 1116 from rhodecode.lib.auth import (
1117 1117 HasPermissionAny, HasPermissionAll,
1118 1118 HasRepoPermissionAny, HasRepoPermissionAll, HasRepoGroupPermissionAll,
1119 1119 HasRepoGroupPermissionAny, HasRepoPermissionAnyApi, get_csrf_token,
1120 1120 csrf_token_key, AuthUser)
1121 1121
1122 1122
1123 1123 #==============================================================================
1124 1124 # GRAVATAR URL
1125 1125 #==============================================================================
1126 1126 class InitialsGravatar(object):
1127 1127 def __init__(self, email_address, first_name, last_name, size=30,
1128 1128 background=None, text_color='#fff'):
1129 1129 self.size = size
1130 1130 self.first_name = first_name
1131 1131 self.last_name = last_name
1132 1132 self.email_address = email_address
1133 1133 self.background = background or self.str2color(email_address)
1134 1134 self.text_color = text_color
1135 1135
1136 1136 def get_color_bank(self):
1137 1137 """
1138 1138 returns a predefined list of colors that gravatars can use.
1139 1139 Those are randomized distinct colors that guarantee readability and
1140 1140 uniqueness.
1141 1141
1142 1142 generated with: http://phrogz.net/css/distinct-colors.html
1143 1143 """
1144 1144 return [
1145 1145 '#bf3030', '#a67f53', '#00ff00', '#5989b3', '#392040', '#d90000',
1146 1146 '#402910', '#204020', '#79baf2', '#a700b3', '#bf6060', '#7f5320',
1147 1147 '#008000', '#003059', '#ee00ff', '#ff0000', '#8c4b00', '#007300',
1148 1148 '#005fb3', '#de73e6', '#ff4040', '#ffaa00', '#3df255', '#203140',
1149 1149 '#47004d', '#591616', '#664400', '#59b365', '#0d2133', '#83008c',
1150 1150 '#592d2d', '#bf9f60', '#73e682', '#1d3f73', '#73006b', '#402020',
1151 1151 '#b2862d', '#397341', '#597db3', '#e600d6', '#a60000', '#736039',
1152 1152 '#00b318', '#79aaf2', '#330d30', '#ff8080', '#403010', '#16591f',
1153 1153 '#002459', '#8c4688', '#e50000', '#ffbf40', '#00732e', '#102340',
1154 1154 '#bf60ac', '#8c4646', '#cc8800', '#00a642', '#1d3473', '#b32d98',
1155 1155 '#660e00', '#ffd580', '#80ffb2', '#7391e6', '#733967', '#d97b6c',
1156 1156 '#8c5e00', '#59b389', '#3967e6', '#590047', '#73281d', '#665200',
1157 1157 '#00e67a', '#2d50b3', '#8c2377', '#734139', '#b2982d', '#16593a',
1158 1158 '#001859', '#ff00aa', '#a65e53', '#ffcc00', '#0d3321', '#2d3959',
1159 1159 '#731d56', '#401610', '#4c3d00', '#468c6c', '#002ca6', '#d936a3',
1160 1160 '#d94c36', '#403920', '#36d9a3', '#0d1733', '#592d4a', '#993626',
1161 1161 '#cca300', '#00734d', '#46598c', '#8c005e', '#7f1100', '#8c7000',
1162 1162 '#00a66f', '#7382e6', '#b32d74', '#d9896c', '#ffe680', '#1d7362',
1163 1163 '#364cd9', '#73003d', '#d93a00', '#998a4d', '#59b3a1', '#5965b3',
1164 1164 '#e5007a', '#73341d', '#665f00', '#00b38f', '#0018b3', '#59163a',
1165 1165 '#b2502d', '#bfb960', '#00ffcc', '#23318c', '#a6537f', '#734939',
1166 1166 '#b2a700', '#104036', '#3d3df2', '#402031', '#e56739', '#736f39',
1167 1167 '#79f2ea', '#000059', '#401029', '#4c1400', '#ffee00', '#005953',
1168 1168 '#101040', '#990052', '#402820', '#403d10', '#00ffee', '#0000d9',
1169 1169 '#ff80c4', '#a66953', '#eeff00', '#00ccbe', '#8080ff', '#e673a1',
1170 1170 '#a62c00', '#474d00', '#1a3331', '#46468c', '#733950', '#662900',
1171 1171 '#858c23', '#238c85', '#0f0073', '#b20047', '#d9986c', '#becc00',
1172 1172 '#396f73', '#281d73', '#ff0066', '#ff6600', '#dee673', '#59adb3',
1173 1173 '#6559b3', '#590024', '#b2622d', '#98b32d', '#36ced9', '#332d59',
1174 1174 '#40001a', '#733f1d', '#526600', '#005359', '#242040', '#bf6079',
1175 1175 '#735039', '#cef23d', '#007780', '#5630bf', '#66001b', '#b24700',
1176 1176 '#acbf60', '#1d6273', '#25008c', '#731d34', '#a67453', '#50592d',
1177 1177 '#00ccff', '#6600ff', '#ff0044', '#4c1f00', '#8a994d', '#79daf2',
1178 1178 '#a173e6', '#d93662', '#402310', '#aaff00', '#2d98b3', '#8c40ff',
1179 1179 '#592d39', '#ff8c40', '#354020', '#103640', '#1a0040', '#331a20',
1180 1180 '#331400', '#334d00', '#1d5673', '#583973', '#7f0022', '#4c3626',
1181 1181 '#88cc00', '#36a3d9', '#3d0073', '#d9364c', '#33241a', '#698c23',
1182 1182 '#5995b3', '#300059', '#e57382', '#7f3300', '#366600', '#00aaff',
1183 1183 '#3a1659', '#733941', '#663600', '#74b32d', '#003c59', '#7f53a6',
1184 1184 '#73000f', '#ff8800', '#baf279', '#79caf2', '#291040', '#a6293a',
1185 1185 '#b2742d', '#587339', '#0077b3', '#632699', '#400009', '#d9a66c',
1186 1186 '#294010', '#2d4a59', '#aa00ff', '#4c131b', '#b25f00', '#5ce600',
1187 1187 '#267399', '#a336d9', '#990014', '#664e33', '#86bf60', '#0088ff',
1188 1188 '#7700b3', '#593a16', '#073300', '#1d4b73', '#ac60bf', '#e59539',
1189 1189 '#4f8c46', '#368dd9', '#5c0073'
1190 1190 ]
1191 1191
1192 1192 def rgb_to_hex_color(self, rgb_tuple):
1193 1193 """
1194 1194 Converts an rgb_tuple passed to an hex color.
1195 1195
1196 1196 :param rgb_tuple: tuple with 3 ints represents rgb color space
1197 1197 """
1198 1198 return '#' + ("".join(map(chr, rgb_tuple)).encode('hex'))
1199 1199
1200 1200 def email_to_int_list(self, email_str):
1201 1201 """
1202 1202 Get every byte of the hex digest value of email and turn it to integer.
1203 1203 It's going to be always between 0-255
1204 1204 """
1205 1205 digest = md5_safe(email_str.lower())
1206 1206 return [int(digest[i * 2:i * 2 + 2], 16) for i in range(16)]
1207 1207
1208 1208 def pick_color_bank_index(self, email_str, color_bank):
1209 1209 return self.email_to_int_list(email_str)[0] % len(color_bank)
1210 1210
1211 1211 def str2color(self, email_str):
1212 1212 """
1213 1213 Tries to map in a stable algorithm an email to color
1214 1214
1215 1215 :param email_str:
1216 1216 """
1217 1217 color_bank = self.get_color_bank()
1218 1218 # pick position (module it's length so we always find it in the
1219 1219 # bank even if it's smaller than 256 values
1220 1220 pos = self.pick_color_bank_index(email_str, color_bank)
1221 1221 return color_bank[pos]
1222 1222
1223 1223 def normalize_email(self, email_address):
1224 1224 import unicodedata
1225 1225 # default host used to fill in the fake/missing email
1226 1226 default_host = u'localhost'
1227 1227
1228 1228 if not email_address:
1229 1229 email_address = u'%s@%s' % (User.DEFAULT_USER, default_host)
1230 1230
1231 1231 email_address = safe_unicode(email_address)
1232 1232
1233 1233 if u'@' not in email_address:
1234 1234 email_address = u'%s@%s' % (email_address, default_host)
1235 1235
1236 1236 if email_address.endswith(u'@'):
1237 1237 email_address = u'%s%s' % (email_address, default_host)
1238 1238
1239 1239 email_address = unicodedata.normalize('NFKD', email_address)\
1240 1240 .encode('ascii', 'ignore')
1241 1241 return email_address
1242 1242
1243 1243 def get_initials(self):
1244 1244 """
1245 1245 Returns 2 letter initials calculated based on the input.
1246 1246 The algorithm picks first given email address, and takes first letter
1247 1247 of part before @, and then the first letter of server name. In case
1248 1248 the part before @ is in a format of `somestring.somestring2` it replaces
1249 1249 the server letter with first letter of somestring2
1250 1250
1251 1251 In case function was initialized with both first and lastname, this
1252 1252 overrides the extraction from email by first letter of the first and
1253 1253 last name. We add special logic to that functionality, In case Full name
1254 1254 is compound, like Guido Von Rossum, we use last part of the last name
1255 1255 (Von Rossum) picking `R`.
1256 1256
1257 1257 Function also normalizes the non-ascii characters to they ascii
1258 1258 representation, eg Δ„ => A
1259 1259 """
1260 1260 import unicodedata
1261 1261 # replace non-ascii to ascii
1262 1262 first_name = unicodedata.normalize(
1263 1263 'NFKD', safe_unicode(self.first_name)).encode('ascii', 'ignore')
1264 1264 last_name = unicodedata.normalize(
1265 1265 'NFKD', safe_unicode(self.last_name)).encode('ascii', 'ignore')
1266 1266
1267 1267 # do NFKD encoding, and also make sure email has proper format
1268 1268 email_address = self.normalize_email(self.email_address)
1269 1269
1270 1270 # first push the email initials
1271 1271 prefix, server = email_address.split('@', 1)
1272 1272
1273 1273 # check if prefix is maybe a 'first_name.last_name' syntax
1274 1274 _dot_split = prefix.rsplit('.', 1)
1275 1275 if len(_dot_split) == 2 and _dot_split[1]:
1276 1276 initials = [_dot_split[0][0], _dot_split[1][0]]
1277 1277 else:
1278 1278 initials = [prefix[0], server[0]]
1279 1279
1280 1280 # then try to replace either first_name or last_name
1281 1281 fn_letter = (first_name or " ")[0].strip()
1282 1282 ln_letter = (last_name.split(' ', 1)[-1] or " ")[0].strip()
1283 1283
1284 1284 if fn_letter:
1285 1285 initials[0] = fn_letter
1286 1286
1287 1287 if ln_letter:
1288 1288 initials[1] = ln_letter
1289 1289
1290 1290 return ''.join(initials).upper()
1291 1291
1292 1292 def get_img_data_by_type(self, font_family, img_type):
1293 1293 default_user = """
1294 1294 <svg xmlns="http://www.w3.org/2000/svg"
1295 1295 version="1.1" x="0px" y="0px" width="{size}" height="{size}"
1296 1296 viewBox="-15 -10 439.165 429.164"
1297 1297
1298 1298 xml:space="preserve"
1299 1299 style="background:{background};" >
1300 1300
1301 1301 <path d="M204.583,216.671c50.664,0,91.74-48.075,
1302 1302 91.74-107.378c0-82.237-41.074-107.377-91.74-107.377
1303 1303 c-50.668,0-91.74,25.14-91.74,107.377C112.844,
1304 1304 168.596,153.916,216.671,
1305 1305 204.583,216.671z" fill="{text_color}"/>
1306 1306 <path d="M407.164,374.717L360.88,
1307 1307 270.454c-2.117-4.771-5.836-8.728-10.465-11.138l-71.83-37.392
1308 1308 c-1.584-0.823-3.502-0.663-4.926,0.415c-20.316,
1309 1309 15.366-44.203,23.488-69.076,23.488c-24.877,
1310 1310 0-48.762-8.122-69.078-23.488
1311 1311 c-1.428-1.078-3.346-1.238-4.93-0.415L58.75,
1312 1312 259.316c-4.631,2.41-8.346,6.365-10.465,11.138L2.001,374.717
1313 1313 c-3.191,7.188-2.537,15.412,1.75,22.005c4.285,
1314 1314 6.592,11.537,10.526,19.4,10.526h362.861c7.863,0,15.117-3.936,
1315 1315 19.402-10.527 C409.699,390.129,
1316 1316 410.355,381.902,407.164,374.717z" fill="{text_color}"/>
1317 1317 </svg>""".format(
1318 1318 size=self.size,
1319 1319 background='#979797', # @grey4
1320 1320 text_color=self.text_color,
1321 1321 font_family=font_family)
1322 1322
1323 1323 return {
1324 1324 "default_user": default_user
1325 1325 }[img_type]
1326 1326
1327 1327 def get_img_data(self, svg_type=None):
1328 1328 """
1329 1329 generates the svg metadata for image
1330 1330 """
1331 1331 fonts = [
1332 1332 '-apple-system',
1333 1333 'BlinkMacSystemFont',
1334 1334 'Segoe UI',
1335 1335 'Roboto',
1336 1336 'Oxygen-Sans',
1337 1337 'Ubuntu',
1338 1338 'Cantarell',
1339 1339 'Helvetica Neue',
1340 1340 'sans-serif'
1341 1341 ]
1342 1342 font_family = ','.join(fonts)
1343 1343 if svg_type:
1344 1344 return self.get_img_data_by_type(font_family, svg_type)
1345 1345
1346 1346 initials = self.get_initials()
1347 1347 img_data = """
1348 1348 <svg xmlns="http://www.w3.org/2000/svg" pointer-events="none"
1349 1349 width="{size}" height="{size}"
1350 1350 style="width: 100%; height: 100%; background-color: {background}"
1351 1351 viewBox="0 0 {size} {size}">
1352 1352 <text text-anchor="middle" y="50%" x="50%" dy="0.35em"
1353 1353 pointer-events="auto" fill="{text_color}"
1354 1354 font-family="{font_family}"
1355 1355 style="font-weight: 400; font-size: {f_size}px;">{text}
1356 1356 </text>
1357 1357 </svg>""".format(
1358 1358 size=self.size,
1359 1359 f_size=self.size/2.05, # scale the text inside the box nicely
1360 1360 background=self.background,
1361 1361 text_color=self.text_color,
1362 1362 text=initials.upper(),
1363 1363 font_family=font_family)
1364 1364
1365 1365 return img_data
1366 1366
1367 1367 def generate_svg(self, svg_type=None):
1368 1368 img_data = self.get_img_data(svg_type)
1369 1369 return "data:image/svg+xml;base64,%s" % base64.b64encode(img_data)
1370 1370
1371 1371
1372 1372 def initials_gravatar(request, email_address, first_name, last_name, size=30, store_on_disk=False):
1373 1373
1374 1374 svg_type = None
1375 1375 if email_address == User.DEFAULT_USER_EMAIL:
1376 1376 svg_type = 'default_user'
1377 1377
1378 1378 klass = InitialsGravatar(email_address, first_name, last_name, size)
1379 1379
1380 1380 if store_on_disk:
1381 1381 from rhodecode.apps.file_store import utils as store_utils
1382 1382 from rhodecode.apps.file_store.exceptions import FileNotAllowedException, \
1383 1383 FileOverSizeException
1384 1384 from rhodecode.model.db import Session
1385 1385
1386 1386 image_key = md5_safe(email_address.lower()
1387 1387 + first_name.lower() + last_name.lower())
1388 1388
1389 1389 storage = store_utils.get_file_storage(request.registry.settings)
1390 1390 filename = '{}.svg'.format(image_key)
1391 1391 subdir = 'gravatars'
1392 1392 # since final name has a counter, we apply the 0
1393 1393 uid = storage.apply_counter(0, store_utils.uid_filename(filename, randomized=False))
1394 1394 store_uid = os.path.join(subdir, uid)
1395 1395
1396 1396 db_entry = FileStore.get_by_store_uid(store_uid)
1397 1397 if db_entry:
1398 1398 return request.route_path('download_file', fid=store_uid)
1399 1399
1400 1400 img_data = klass.get_img_data(svg_type=svg_type)
1401 1401 img_file = store_utils.bytes_to_file_obj(img_data)
1402 1402
1403 1403 try:
1404 1404 store_uid, metadata = storage.save_file(
1405 1405 img_file, filename, directory=subdir,
1406 1406 extensions=['.svg'], randomized_name=False)
1407 1407 except (FileNotAllowedException, FileOverSizeException):
1408 1408 raise
1409 1409
1410 1410 try:
1411 1411 entry = FileStore.create(
1412 1412 file_uid=store_uid, filename=metadata["filename"],
1413 1413 file_hash=metadata["sha256"], file_size=metadata["size"],
1414 1414 file_display_name=filename,
1415 1415 file_description=u'user gravatar `{}`'.format(safe_unicode(filename)),
1416 1416 hidden=True, check_acl=False, user_id=1
1417 1417 )
1418 1418 Session().add(entry)
1419 1419 Session().commit()
1420 1420 log.debug('Stored upload in DB as %s', entry)
1421 1421 except Exception:
1422 1422 raise
1423 1423
1424 1424 return request.route_path('download_file', fid=store_uid)
1425 1425
1426 1426 else:
1427 1427 return klass.generate_svg(svg_type=svg_type)
1428 1428
1429 1429
1430 1430 def gravatar_external(request, gravatar_url_tmpl, email_address, size=30):
1431 1431 return safe_str(gravatar_url_tmpl)\
1432 1432 .replace('{email}', email_address) \
1433 1433 .replace('{md5email}', md5_safe(email_address.lower())) \
1434 1434 .replace('{netloc}', request.host) \
1435 1435 .replace('{scheme}', request.scheme) \
1436 1436 .replace('{size}', safe_str(size))
1437 1437
1438 1438
1439 1439 def gravatar_url(email_address, size=30, request=None):
1440 1440 request = request or get_current_request()
1441 1441 _use_gravatar = request.call_context.visual.use_gravatar
1442 1442
1443 1443 email_address = email_address or User.DEFAULT_USER_EMAIL
1444 1444 if isinstance(email_address, unicode):
1445 1445 # hashlib crashes on unicode items
1446 1446 email_address = safe_str(email_address)
1447 1447
1448 1448 # empty email or default user
1449 1449 if not email_address or email_address == User.DEFAULT_USER_EMAIL:
1450 1450 return initials_gravatar(request, User.DEFAULT_USER_EMAIL, '', '', size=size)
1451 1451
1452 1452 if _use_gravatar:
1453 1453 gravatar_url_tmpl = request.call_context.visual.gravatar_url \
1454 1454 or User.DEFAULT_GRAVATAR_URL
1455 1455 return gravatar_external(request, gravatar_url_tmpl, email_address, size=size)
1456 1456
1457 1457 else:
1458 1458 return initials_gravatar(request, email_address, '', '', size=size)
1459 1459
1460 1460
1461 1461 def breadcrumb_repo_link(repo):
1462 1462 """
1463 1463 Makes a breadcrumbs path link to repo
1464 1464
1465 1465 ex::
1466 1466 group >> subgroup >> repo
1467 1467
1468 1468 :param repo: a Repository instance
1469 1469 """
1470 1470
1471 1471 path = [
1472 1472 link_to(group.name, route_path('repo_group_home', repo_group_name=group.group_name),
1473 1473 title='last change:{}'.format(format_date(group.last_commit_change)))
1474 1474 for group in repo.groups_with_parents
1475 1475 ] + [
1476 1476 link_to(repo.just_name, route_path('repo_summary', repo_name=repo.repo_name),
1477 1477 title='last change:{}'.format(format_date(repo.last_commit_change)))
1478 1478 ]
1479 1479
1480 1480 return literal(' &raquo; '.join(path))
1481 1481
1482 1482
1483 1483 def breadcrumb_repo_group_link(repo_group):
1484 1484 """
1485 1485 Makes a breadcrumbs path link to repo
1486 1486
1487 1487 ex::
1488 1488 group >> subgroup
1489 1489
1490 1490 :param repo_group: a Repository Group instance
1491 1491 """
1492 1492
1493 1493 path = [
1494 1494 link_to(group.name,
1495 1495 route_path('repo_group_home', repo_group_name=group.group_name),
1496 1496 title='last change:{}'.format(format_date(group.last_commit_change)))
1497 1497 for group in repo_group.parents
1498 1498 ] + [
1499 1499 link_to(repo_group.name,
1500 1500 route_path('repo_group_home', repo_group_name=repo_group.group_name),
1501 1501 title='last change:{}'.format(format_date(repo_group.last_commit_change)))
1502 1502 ]
1503 1503
1504 1504 return literal(' &raquo; '.join(path))
1505 1505
1506 1506
1507 1507 def format_byte_size_binary(file_size):
1508 1508 """
1509 1509 Formats file/folder sizes to standard.
1510 1510 """
1511 1511 if file_size is None:
1512 1512 file_size = 0
1513 1513
1514 1514 formatted_size = format_byte_size(file_size, binary=True)
1515 1515 return formatted_size
1516 1516
1517 1517
1518 1518 def urlify_text(text_, safe=True, **href_attrs):
1519 1519 """
1520 1520 Extract urls from text and make html links out of them
1521 1521 """
1522 1522
1523 1523 url_pat = re.compile(r'''(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@#.&+]'''
1524 1524 '''|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)''')
1525 1525
1526 1526 def url_func(match_obj):
1527 1527 url_full = match_obj.groups()[0]
1528 1528 a_options = dict(href_attrs)
1529 1529 a_options['href'] = url_full
1530 1530 a_text = url_full
1531 1531 return HTML.tag("a", a_text, **a_options)
1532 1532
1533 1533 _new_text = url_pat.sub(url_func, text_)
1534 1534
1535 1535 if safe:
1536 1536 return literal(_new_text)
1537 1537 return _new_text
1538 1538
1539 1539
1540 1540 def urlify_commits(text_, repo_name):
1541 1541 """
1542 1542 Extract commit ids from text and make link from them
1543 1543
1544 1544 :param text_:
1545 1545 :param repo_name: repo name to build the URL with
1546 1546 """
1547 1547
1548 1548 url_pat = re.compile(r'(^|\s)([0-9a-fA-F]{12,40})($|\s)')
1549 1549
1550 1550 def url_func(match_obj):
1551 1551 commit_id = match_obj.groups()[1]
1552 1552 pref = match_obj.groups()[0]
1553 1553 suf = match_obj.groups()[2]
1554 1554
1555 1555 tmpl = (
1556 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 1557 '%(commit_id)s</a>%(suf)s'
1558 1558 )
1559 1559 return tmpl % {
1560 1560 'pref': pref,
1561 1561 'cls': 'revision-link',
1562 1562 'url': route_url(
1563 1563 'repo_commit', repo_name=repo_name, commit_id=commit_id),
1564 1564 'commit_id': commit_id,
1565 1565 'suf': suf,
1566 1566 'hovercard_alt': 'Commit: {}'.format(commit_id),
1567 1567 'hovercard_url': route_url(
1568 1568 'hovercard_repo_commit', repo_name=repo_name, commit_id=commit_id)
1569 1569 }
1570 1570
1571 1571 new_text = url_pat.sub(url_func, text_)
1572 1572
1573 1573 return new_text
1574 1574
1575 1575
1576 1576 def _process_url_func(match_obj, repo_name, uid, entry,
1577 1577 return_raw_data=False, link_format='html'):
1578 1578 pref = ''
1579 1579 if match_obj.group().startswith(' '):
1580 1580 pref = ' '
1581 1581
1582 1582 issue_id = ''.join(match_obj.groups())
1583 1583
1584 1584 if link_format == 'html':
1585 1585 tmpl = (
1586 1586 '%(pref)s<a class="tooltip %(cls)s" href="%(url)s" title="%(title)s">'
1587 1587 '%(issue-prefix)s%(id-repr)s'
1588 1588 '</a>')
1589 1589 elif link_format == 'html+hovercard':
1590 1590 tmpl = (
1591 1591 '%(pref)s<a class="tooltip-hovercard %(cls)s" href="%(url)s" data-hovercard-url="%(hovercard_url)s">'
1592 1592 '%(issue-prefix)s%(id-repr)s'
1593 1593 '</a>')
1594 1594 elif link_format in ['rst', 'rst+hovercard']:
1595 1595 tmpl = '`%(issue-prefix)s%(id-repr)s <%(url)s>`_'
1596 1596 elif link_format in ['markdown', 'markdown+hovercard']:
1597 1597 tmpl = '[%(pref)s%(issue-prefix)s%(id-repr)s](%(url)s)'
1598 1598 else:
1599 1599 raise ValueError('Bad link_format:{}'.format(link_format))
1600 1600
1601 1601 (repo_name_cleaned,
1602 1602 parent_group_name) = RepoGroupModel()._get_group_name_and_parent(repo_name)
1603 1603
1604 1604 # variables replacement
1605 1605 named_vars = {
1606 1606 'id': issue_id,
1607 1607 'repo': repo_name,
1608 1608 'repo_name': repo_name_cleaned,
1609 1609 'group_name': parent_group_name,
1610 1610 # set dummy keys so we always have them
1611 1611 'hostname': '',
1612 1612 'netloc': '',
1613 1613 'scheme': ''
1614 1614 }
1615 1615
1616 1616 request = get_current_request()
1617 1617 if request:
1618 1618 # exposes, hostname, netloc, scheme
1619 1619 host_data = get_host_info(request)
1620 1620 named_vars.update(host_data)
1621 1621
1622 1622 # named regex variables
1623 1623 named_vars.update(match_obj.groupdict())
1624 1624 _url = string.Template(entry['url']).safe_substitute(**named_vars)
1625 1625 desc = string.Template(escape(entry['desc'])).safe_substitute(**named_vars)
1626 1626 hovercard_url = string.Template(entry.get('hovercard_url', '')).safe_substitute(**named_vars)
1627 1627
1628 1628 def quote_cleaner(input_str):
1629 1629 """Remove quotes as it's HTML"""
1630 1630 return input_str.replace('"', '')
1631 1631
1632 1632 data = {
1633 1633 'pref': pref,
1634 1634 'cls': quote_cleaner('issue-tracker-link'),
1635 1635 'url': quote_cleaner(_url),
1636 1636 'id-repr': issue_id,
1637 1637 'issue-prefix': entry['pref'],
1638 1638 'serv': entry['url'],
1639 1639 'title': bleach.clean(desc, strip=True),
1640 1640 'hovercard_url': hovercard_url
1641 1641 }
1642 1642
1643 1643 if return_raw_data:
1644 1644 return {
1645 1645 'id': issue_id,
1646 1646 'url': _url
1647 1647 }
1648 1648 return tmpl % data
1649 1649
1650 1650
1651 1651 def get_active_pattern_entries(repo_name):
1652 1652 repo = None
1653 1653 if repo_name:
1654 1654 # Retrieving repo_name to avoid invalid repo_name to explode on
1655 1655 # IssueTrackerSettingsModel but still passing invalid name further down
1656 1656 repo = Repository.get_by_repo_name(repo_name, cache=True)
1657 1657
1658 1658 settings_model = IssueTrackerSettingsModel(repo=repo)
1659 1659 active_entries = settings_model.get_settings(cache=True)
1660 1660 return active_entries
1661 1661
1662 1662
1663 1663 pr_pattern_re = regex.compile(r'(?:(?:^!)|(?: !))(\d+)')
1664 1664
1665 1665 allowed_link_formats = [
1666 1666 'html', 'rst', 'markdown', 'html+hovercard', 'rst+hovercard', 'markdown+hovercard']
1667 1667
1668 1668 compile_cache = {
1669 1669
1670 1670 }
1671 1671
1672 1672
1673 1673 def process_patterns(text_string, repo_name, link_format='html', active_entries=None):
1674 1674
1675 1675 if link_format not in allowed_link_formats:
1676 1676 raise ValueError('Link format can be only one of:{} got {}'.format(
1677 1677 allowed_link_formats, link_format))
1678 1678 issues_data = []
1679 1679 errors = []
1680 1680 new_text = text_string
1681 1681
1682 1682 if active_entries is None:
1683 1683 log.debug('Fetch active issue tracker patterns for repo: %s', repo_name)
1684 1684 active_entries = get_active_pattern_entries(repo_name)
1685 1685
1686 1686 log.debug('Got %s pattern entries to process', len(active_entries))
1687 1687
1688 1688 for uid, entry in active_entries.items():
1689 1689
1690 1690 if not (entry['pat'] and entry['url']):
1691 1691 log.debug('skipping due to missing data')
1692 1692 continue
1693 1693
1694 1694 log.debug('issue tracker entry: uid: `%s` PAT:%s URL:%s PREFIX:%s',
1695 1695 uid, entry['pat'], entry['url'], entry['pref'])
1696 1696
1697 1697 if entry.get('pat_compiled'):
1698 1698 pattern = entry['pat_compiled']
1699 1699 elif entry['pat'] in compile_cache:
1700 1700 pattern = compile_cache[entry['pat']]
1701 1701 else:
1702 1702 try:
1703 1703 pattern = regex.compile(r'%s' % entry['pat'])
1704 1704 except regex.error as e:
1705 1705 regex_err = ValueError('{}:{}'.format(entry['pat'], e))
1706 1706 log.exception('issue tracker pattern: `%s` failed to compile', regex_err)
1707 1707 errors.append(regex_err)
1708 1708 continue
1709 1709 compile_cache[entry['pat']] = pattern
1710 1710
1711 1711 data_func = partial(
1712 1712 _process_url_func, repo_name=repo_name, entry=entry, uid=uid,
1713 1713 return_raw_data=True)
1714 1714
1715 1715 for match_obj in pattern.finditer(text_string):
1716 1716 issues_data.append(data_func(match_obj))
1717 1717
1718 1718 url_func = partial(
1719 1719 _process_url_func, repo_name=repo_name, entry=entry, uid=uid,
1720 1720 link_format=link_format)
1721 1721
1722 1722 new_text = pattern.sub(url_func, new_text)
1723 1723 log.debug('processed prefix:uid `%s`', uid)
1724 1724
1725 1725 # finally use global replace, eg !123 -> pr-link, those will not catch
1726 1726 # if already similar pattern exists
1727 1727 server_url = '${scheme}://${netloc}'
1728 1728 pr_entry = {
1729 1729 'pref': '!',
1730 1730 'url': server_url + '/_admin/pull-requests/${id}',
1731 1731 'desc': 'Pull Request !${id}',
1732 1732 'hovercard_url': server_url + '/_hovercard/pull_request/${id}'
1733 1733 }
1734 1734 pr_url_func = partial(
1735 1735 _process_url_func, repo_name=repo_name, entry=pr_entry, uid=None,
1736 1736 link_format=link_format+'+hovercard')
1737 1737 new_text = pr_pattern_re.sub(pr_url_func, new_text)
1738 1738 log.debug('processed !pr pattern')
1739 1739
1740 1740 return new_text, issues_data, errors
1741 1741
1742 1742
1743 1743 def urlify_commit_message(commit_text, repository=None, active_pattern_entries=None,
1744 1744 issues_container_callback=None, error_container=None):
1745 1745 """
1746 1746 Parses given text message and makes proper links.
1747 1747 issues are linked to given issue-server, and rest is a commit link
1748 1748 """
1749 1749
1750 1750 def escaper(_text):
1751 1751 return _text.replace('<', '&lt;').replace('>', '&gt;')
1752 1752
1753 1753 new_text = escaper(commit_text)
1754 1754
1755 1755 # extract http/https links and make them real urls
1756 1756 new_text = urlify_text(new_text, safe=False)
1757 1757
1758 1758 # urlify commits - extract commit ids and make link out of them, if we have
1759 1759 # the scope of repository present.
1760 1760 if repository:
1761 1761 new_text = urlify_commits(new_text, repository)
1762 1762
1763 1763 # process issue tracker patterns
1764 1764 new_text, issues, errors = process_patterns(
1765 1765 new_text, repository or '', active_entries=active_pattern_entries)
1766 1766
1767 1767 if issues_container_callback is not None:
1768 1768 for issue in issues:
1769 1769 issues_container_callback(issue)
1770 1770
1771 1771 if error_container is not None:
1772 1772 error_container.extend(errors)
1773 1773
1774 1774 return literal(new_text)
1775 1775
1776 1776
1777 1777 def render_binary(repo_name, file_obj):
1778 1778 """
1779 1779 Choose how to render a binary file
1780 1780 """
1781 1781
1782 1782 # unicode
1783 1783 filename = file_obj.name
1784 1784
1785 1785 # images
1786 1786 for ext in ['*.png', '*.jpeg', '*.jpg', '*.ico', '*.gif']:
1787 1787 if fnmatch.fnmatch(filename, pat=ext):
1788 1788 src = route_path(
1789 1789 'repo_file_raw', repo_name=repo_name,
1790 1790 commit_id=file_obj.commit.raw_id,
1791 1791 f_path=file_obj.path)
1792 1792
1793 1793 return literal(
1794 1794 '<img class="rendered-binary" alt="rendered-image" src="{}">'.format(src))
1795 1795
1796 1796
1797 1797 def renderer_from_filename(filename, exclude=None):
1798 1798 """
1799 1799 choose a renderer based on filename, this works only for text based files
1800 1800 """
1801 1801
1802 1802 # ipython
1803 1803 for ext in ['*.ipynb']:
1804 1804 if fnmatch.fnmatch(filename, pat=ext):
1805 1805 return 'jupyter'
1806 1806
1807 1807 is_markup = MarkupRenderer.renderer_from_filename(filename, exclude=exclude)
1808 1808 if is_markup:
1809 1809 return is_markup
1810 1810 return None
1811 1811
1812 1812
1813 1813 def render(source, renderer='rst', mentions=False, relative_urls=None,
1814 1814 repo_name=None, active_pattern_entries=None, issues_container_callback=None):
1815 1815
1816 1816 def maybe_convert_relative_links(html_source):
1817 1817 if relative_urls:
1818 1818 return relative_links(html_source, relative_urls)
1819 1819 return html_source
1820 1820
1821 1821 if renderer == 'plain':
1822 1822 return literal(
1823 1823 MarkupRenderer.plain(source, leading_newline=False))
1824 1824
1825 1825 elif renderer == 'rst':
1826 1826 if repo_name:
1827 1827 # process patterns on comments if we pass in repo name
1828 1828 source, issues, errors = process_patterns(
1829 1829 source, repo_name, link_format='rst',
1830 1830 active_entries=active_pattern_entries)
1831 1831 if issues_container_callback is not None:
1832 1832 for issue in issues:
1833 1833 issues_container_callback(issue)
1834 1834
1835 1835 return literal(
1836 1836 '<div class="rst-block">%s</div>' %
1837 1837 maybe_convert_relative_links(
1838 1838 MarkupRenderer.rst(source, mentions=mentions)))
1839 1839
1840 1840 elif renderer == 'markdown':
1841 1841 if repo_name:
1842 1842 # process patterns on comments if we pass in repo name
1843 1843 source, issues, errors = process_patterns(
1844 1844 source, repo_name, link_format='markdown',
1845 1845 active_entries=active_pattern_entries)
1846 1846 if issues_container_callback is not None:
1847 1847 for issue in issues:
1848 1848 issues_container_callback(issue)
1849 1849
1850 1850
1851 1851 return literal(
1852 1852 '<div class="markdown-block">%s</div>' %
1853 1853 maybe_convert_relative_links(
1854 1854 MarkupRenderer.markdown(source, flavored=True,
1855 1855 mentions=mentions)))
1856 1856
1857 1857 elif renderer == 'jupyter':
1858 1858 return literal(
1859 1859 '<div class="ipynb">%s</div>' %
1860 1860 maybe_convert_relative_links(
1861 1861 MarkupRenderer.jupyter(source)))
1862 1862
1863 1863 # None means just show the file-source
1864 1864 return None
1865 1865
1866 1866
1867 1867 def commit_status(repo, commit_id):
1868 1868 return ChangesetStatusModel().get_status(repo, commit_id)
1869 1869
1870 1870
1871 1871 def commit_status_lbl(commit_status):
1872 1872 return dict(ChangesetStatus.STATUSES).get(commit_status)
1873 1873
1874 1874
1875 1875 def commit_time(repo_name, commit_id):
1876 1876 repo = Repository.get_by_repo_name(repo_name)
1877 1877 commit = repo.get_commit(commit_id=commit_id)
1878 1878 return commit.date
1879 1879
1880 1880
1881 1881 def get_permission_name(key):
1882 1882 return dict(Permission.PERMS).get(key)
1883 1883
1884 1884
1885 1885 def journal_filter_help(request):
1886 1886 _ = request.translate
1887 1887 from rhodecode.lib.audit_logger import ACTIONS
1888 1888 actions = '\n'.join(textwrap.wrap(', '.join(sorted(ACTIONS.keys())), 80))
1889 1889
1890 1890 return _(
1891 1891 'Example filter terms:\n' +
1892 1892 ' repository:vcs\n' +
1893 1893 ' username:marcin\n' +
1894 1894 ' username:(NOT marcin)\n' +
1895 1895 ' action:*push*\n' +
1896 1896 ' ip:127.0.0.1\n' +
1897 1897 ' date:20120101\n' +
1898 1898 ' date:[20120101100000 TO 20120102]\n' +
1899 1899 '\n' +
1900 1900 'Actions: {actions}\n' +
1901 1901 '\n' +
1902 1902 'Generate wildcards using \'*\' character:\n' +
1903 1903 ' "repository:vcs*" - search everything starting with \'vcs\'\n' +
1904 1904 ' "repository:*vcs*" - search for repository containing \'vcs\'\n' +
1905 1905 '\n' +
1906 1906 'Optional AND / OR operators in queries\n' +
1907 1907 ' "repository:vcs OR repository:test"\n' +
1908 1908 ' "username:test AND repository:test*"\n'
1909 1909 ).format(actions=actions)
1910 1910
1911 1911
1912 1912 def not_mapped_error(repo_name):
1913 1913 from rhodecode.translation import _
1914 1914 flash(_('%s repository is not mapped to db perhaps'
1915 1915 ' it was created or renamed from the filesystem'
1916 1916 ' please run the application again'
1917 1917 ' in order to rescan repositories') % repo_name, category='error')
1918 1918
1919 1919
1920 1920 def ip_range(ip_addr):
1921 1921 from rhodecode.model.db import UserIpMap
1922 1922 s, e = UserIpMap._get_ip_range(ip_addr)
1923 1923 return '%s - %s' % (s, e)
1924 1924
1925 1925
1926 1926 def form(url, method='post', needs_csrf_token=True, **attrs):
1927 1927 """Wrapper around webhelpers.tags.form to prevent CSRF attacks."""
1928 1928 if method.lower() != 'get' and needs_csrf_token:
1929 1929 raise Exception(
1930 1930 'Forms to POST/PUT/DELETE endpoints should have (in general) a ' +
1931 1931 'CSRF token. If the endpoint does not require such token you can ' +
1932 1932 'explicitly set the parameter needs_csrf_token to false.')
1933 1933
1934 1934 return insecure_form(url, method=method, **attrs)
1935 1935
1936 1936
1937 1937 def secure_form(form_url, method="POST", multipart=False, **attrs):
1938 1938 """Start a form tag that points the action to an url. This
1939 1939 form tag will also include the hidden field containing
1940 1940 the auth token.
1941 1941
1942 1942 The url options should be given either as a string, or as a
1943 1943 ``url()`` function. The method for the form defaults to POST.
1944 1944
1945 1945 Options:
1946 1946
1947 1947 ``multipart``
1948 1948 If set to True, the enctype is set to "multipart/form-data".
1949 1949 ``method``
1950 1950 The method to use when submitting the form, usually either
1951 1951 "GET" or "POST". If "PUT", "DELETE", or another verb is used, a
1952 1952 hidden input with name _method is added to simulate the verb
1953 1953 over POST.
1954 1954
1955 1955 """
1956 1956
1957 1957 if 'request' in attrs:
1958 1958 session = attrs['request'].session
1959 1959 del attrs['request']
1960 1960 else:
1961 1961 raise ValueError(
1962 1962 'Calling this form requires request= to be passed as argument')
1963 1963
1964 1964 _form = insecure_form(form_url, method, multipart, **attrs)
1965 1965 token = literal(
1966 1966 '<input type="hidden" name="{}" value="{}">'.format(
1967 1967 csrf_token_key, get_csrf_token(session)))
1968 1968
1969 1969 return literal("%s\n%s" % (_form, token))
1970 1970
1971 1971
1972 1972 def dropdownmenu(name, selected, options, enable_filter=False, **attrs):
1973 1973 select_html = select(name, selected, options, **attrs)
1974 1974
1975 1975 select2 = """
1976 1976 <script>
1977 1977 $(document).ready(function() {
1978 1978 $('#%s').select2({
1979 1979 containerCssClass: 'drop-menu %s',
1980 1980 dropdownCssClass: 'drop-menu-dropdown',
1981 1981 dropdownAutoWidth: true%s
1982 1982 });
1983 1983 });
1984 1984 </script>
1985 1985 """
1986 1986
1987 1987 filter_option = """,
1988 1988 minimumResultsForSearch: -1
1989 1989 """
1990 1990 input_id = attrs.get('id') or name
1991 1991 extra_classes = ' '.join(attrs.pop('extra_classes', []))
1992 1992 filter_enabled = "" if enable_filter else filter_option
1993 1993 select_script = literal(select2 % (input_id, extra_classes, filter_enabled))
1994 1994
1995 1995 return literal(select_html+select_script)
1996 1996
1997 1997
1998 1998 def get_visual_attr(tmpl_context_var, attr_name):
1999 1999 """
2000 2000 A safe way to get a variable from visual variable of template context
2001 2001
2002 2002 :param tmpl_context_var: instance of tmpl_context, usually present as `c`
2003 2003 :param attr_name: name of the attribute we fetch from the c.visual
2004 2004 """
2005 2005 visual = getattr(tmpl_context_var, 'visual', None)
2006 2006 if not visual:
2007 2007 return
2008 2008 else:
2009 2009 return getattr(visual, attr_name, None)
2010 2010
2011 2011
2012 2012 def get_last_path_part(file_node):
2013 2013 if not file_node.path:
2014 2014 return u'/'
2015 2015
2016 2016 path = safe_unicode(file_node.path.split('/')[-1])
2017 2017 return u'../' + path
2018 2018
2019 2019
2020 2020 def route_url(*args, **kwargs):
2021 2021 """
2022 2022 Wrapper around pyramids `route_url` (fully qualified url) function.
2023 2023 """
2024 2024 req = get_current_request()
2025 2025 return req.route_url(*args, **kwargs)
2026 2026
2027 2027
2028 2028 def route_path(*args, **kwargs):
2029 2029 """
2030 2030 Wrapper around pyramids `route_path` function.
2031 2031 """
2032 2032 req = get_current_request()
2033 2033 return req.route_path(*args, **kwargs)
2034 2034
2035 2035
2036 2036 def route_path_or_none(*args, **kwargs):
2037 2037 try:
2038 2038 return route_path(*args, **kwargs)
2039 2039 except KeyError:
2040 2040 return None
2041 2041
2042 2042
2043 2043 def current_route_path(request, **kw):
2044 2044 new_args = request.GET.mixed()
2045 2045 new_args.update(kw)
2046 2046 return request.current_route_path(_query=new_args)
2047 2047
2048 2048
2049 2049 def curl_api_example(method, args):
2050 2050 args_json = json.dumps(OrderedDict([
2051 2051 ('id', 1),
2052 2052 ('auth_token', 'SECRET'),
2053 2053 ('method', method),
2054 2054 ('args', args)
2055 2055 ]))
2056 2056
2057 2057 return "curl {api_url} -X POST -H 'content-type:text/plain' --data-binary '{args_json}'".format(
2058 2058 api_url=route_url('apiv2'),
2059 2059 args_json=args_json
2060 2060 )
2061 2061
2062 2062
2063 2063 def api_call_example(method, args):
2064 2064 """
2065 2065 Generates an API call example via CURL
2066 2066 """
2067 2067 curl_call = curl_api_example(method, args)
2068 2068
2069 2069 return literal(
2070 2070 curl_call +
2071 2071 "<br/><br/>SECRET can be found in <a href=\"{token_url}\">auth-tokens</a> page, "
2072 2072 "and needs to be of `api calls` role."
2073 2073 .format(token_url=route_url('my_account_auth_tokens')))
2074 2074
2075 2075
2076 2076 def notification_description(notification, request):
2077 2077 """
2078 2078 Generate notification human readable description based on notification type
2079 2079 """
2080 2080 from rhodecode.model.notification import NotificationModel
2081 2081 return NotificationModel().make_description(
2082 2082 notification, translate=request.translate)
2083 2083
2084 2084
2085 2085 def go_import_header(request, db_repo=None):
2086 2086 """
2087 2087 Creates a header for go-import functionality in Go Lang
2088 2088 """
2089 2089
2090 2090 if not db_repo:
2091 2091 return
2092 2092 if 'go-get' not in request.GET:
2093 2093 return
2094 2094
2095 2095 clone_url = db_repo.clone_url()
2096 2096 prefix = re.split(r'^https?:\/\/', clone_url)[-1]
2097 2097 # we have a repo and go-get flag,
2098 2098 return literal('<meta name="go-import" content="{} {} {}">'.format(
2099 2099 prefix, db_repo.repo_type, clone_url))
2100 2100
2101 2101
2102 2102 def reviewer_as_json(*args, **kwargs):
2103 2103 from rhodecode.apps.repository.utils import reviewer_as_json as _reviewer_as_json
2104 2104 return _reviewer_as_json(*args, **kwargs)
2105 2105
2106 2106
2107 2107 def get_repo_view_type(request):
2108 2108 route_name = request.matched_route.name
2109 2109 route_to_view_type = {
2110 2110 'repo_changelog': 'commits',
2111 2111 'repo_commits': 'commits',
2112 2112 'repo_files': 'files',
2113 2113 'repo_summary': 'summary',
2114 2114 'repo_commit': 'commit'
2115 2115 }
2116 2116
2117 2117 return route_to_view_type.get(route_name)
2118 2118
2119 2119
2120 2120 def is_active(menu_entry, selected):
2121 2121 """
2122 2122 Returns active class for selecting menus in templates
2123 2123 <li class=${h.is_active('settings', current_active)}></li>
2124 2124 """
2125 2125 if not isinstance(menu_entry, list):
2126 2126 menu_entry = [menu_entry]
2127 2127
2128 2128 if selected in menu_entry:
2129 2129 return "active"
2130 2130
2131 2131
2132 2132 class IssuesRegistry(object):
2133 2133 """
2134 2134 issue_registry = IssuesRegistry()
2135 2135 some_func(issues_callback=issues_registry(...))
2136 2136 """
2137 2137
2138 2138 def __init__(self):
2139 2139 self.issues = []
2140 2140 self.unique_issues = collections.defaultdict(lambda: [])
2141 2141
2142 2142 def __call__(self, commit_dict=None):
2143 2143 def callback(issue):
2144 2144 if commit_dict and issue:
2145 2145 issue['commit'] = commit_dict
2146 2146 self.issues.append(issue)
2147 2147 self.unique_issues[issue['id']].append(issue)
2148 2148 return callback
2149 2149
2150 2150 def get_issues(self):
2151 2151 return self.issues
2152 2152
2153 2153 @property
2154 2154 def issues_unique_count(self):
2155 2155 return len(set(i['id'] for i in self.issues))
@@ -1,679 +1,679 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2014-2020 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 SimpleVCS middleware for handling protocol request (push/clone etc.)
23 23 It's implemented with basic auth function
24 24 """
25 25
26 26 import os
27 27 import re
28 28 import logging
29 29 import importlib
30 30 from functools import wraps
31 31 from io import StringIO
32 32 from lxml import etree
33 33
34 34 import time
35 35 from paste.httpheaders import REMOTE_USER, AUTH_TYPE
36 36
37 37 from pyramid.httpexceptions import (
38 38 HTTPNotFound, HTTPForbidden, HTTPNotAcceptable, HTTPInternalServerError)
39 39 from zope.cachedescriptors.property import Lazy as LazyProperty
40 40
41 41 import rhodecode
42 42 from rhodecode.authentication.base import authenticate, VCS_TYPE, loadplugin
43 43 from rhodecode.lib import rc_cache
44 44 from rhodecode.lib.auth import AuthUser, HasPermissionAnyMiddleware
45 45 from rhodecode.lib.base import (
46 46 BasicAuth, get_ip_addr, get_user_agent, vcs_operation_context)
47 47 from rhodecode.lib.exceptions import (UserCreationError, NotAllowedToCreateUserError)
48 48 from rhodecode.lib.hooks_daemon import prepare_callback_daemon
49 49 from rhodecode.lib.middleware import appenlight
50 50 from rhodecode.lib.middleware.utils import scm_app_http
51 51 from rhodecode.lib.utils import is_valid_repo, SLUG_RE
52 52 from rhodecode.lib.utils2 import safe_str, fix_PATH, str2bool, safe_unicode
53 53 from rhodecode.lib.vcs.conf import settings as vcs_settings
54 54 from rhodecode.lib.vcs.backends import base
55 55
56 56 from rhodecode.model import meta
57 57 from rhodecode.model.db import User, Repository, PullRequest
58 58 from rhodecode.model.scm import ScmModel
59 59 from rhodecode.model.pull_request import PullRequestModel
60 60 from rhodecode.model.settings import SettingsModel, VcsSettingsModel
61 61
62 62 log = logging.getLogger(__name__)
63 63
64 64
65 65 def extract_svn_txn_id(acl_repo_name, data):
66 66 """
67 67 Helper method for extraction of svn txn_id from submitted XML data during
68 68 POST operations
69 69 """
70 70 try:
71 71 root = etree.fromstring(data)
72 72 pat = re.compile(r'/txn/(?P<txn_id>.*)')
73 73 for el in root:
74 74 if el.tag == '{DAV:}source':
75 75 for sub_el in el:
76 76 if sub_el.tag == '{DAV:}href':
77 77 match = pat.search(sub_el.text)
78 78 if match:
79 79 svn_tx_id = match.groupdict()['txn_id']
80 80 txn_id = rc_cache.utils.compute_key_from_params(
81 81 acl_repo_name, svn_tx_id)
82 82 return txn_id
83 83 except Exception:
84 84 log.exception('Failed to extract txn_id')
85 85
86 86
87 87 def initialize_generator(factory):
88 88 """
89 89 Initializes the returned generator by draining its first element.
90 90
91 91 This can be used to give a generator an initializer, which is the code
92 92 up to the first yield statement. This decorator enforces that the first
93 93 produced element has the value ``"__init__"`` to make its special
94 94 purpose very explicit in the using code.
95 95 """
96 96
97 97 @wraps(factory)
98 98 def wrapper(*args, **kwargs):
99 99 gen = factory(*args, **kwargs)
100 100 try:
101 init = gen.next()
101 init = next(gen)
102 102 except StopIteration:
103 103 raise ValueError('Generator must yield at least one element.')
104 104 if init != "__init__":
105 105 raise ValueError('First yielded element must be "__init__".')
106 106 return gen
107 107 return wrapper
108 108
109 109
110 110 class SimpleVCS(object):
111 111 """Common functionality for SCM HTTP handlers."""
112 112
113 113 SCM = 'unknown'
114 114
115 115 acl_repo_name = None
116 116 url_repo_name = None
117 117 vcs_repo_name = None
118 118 rc_extras = {}
119 119
120 120 # We have to handle requests to shadow repositories different than requests
121 121 # to normal repositories. Therefore we have to distinguish them. To do this
122 122 # we use this regex which will match only on URLs pointing to shadow
123 123 # repositories.
124 124 shadow_repo_re = re.compile(
125 125 '(?P<groups>(?:{slug_pat}/)*)' # repo groups
126 126 '(?P<target>{slug_pat})/' # target repo
127 127 'pull-request/(?P<pr_id>\d+)/' # pull request
128 128 'repository$' # shadow repo
129 129 .format(slug_pat=SLUG_RE.pattern))
130 130
131 131 def __init__(self, config, registry):
132 132 self.registry = registry
133 133 self.config = config
134 134 # re-populated by specialized middleware
135 135 self.repo_vcs_config = base.Config()
136 136
137 137 rc_settings = SettingsModel().get_all_settings(cache=True, from_request=False)
138 138 realm = rc_settings.get('rhodecode_realm') or 'RhodeCode AUTH'
139 139
140 140 # authenticate this VCS request using authfunc
141 141 auth_ret_code_detection = \
142 142 str2bool(self.config.get('auth_ret_code_detection', False))
143 143 self.authenticate = BasicAuth(
144 144 '', authenticate, registry, config.get('auth_ret_code'),
145 145 auth_ret_code_detection, rc_realm=realm)
146 146 self.ip_addr = '0.0.0.0'
147 147
148 148 @LazyProperty
149 149 def global_vcs_config(self):
150 150 try:
151 151 return VcsSettingsModel().get_ui_settings_as_config_obj()
152 152 except Exception:
153 153 return base.Config()
154 154
155 155 @property
156 156 def base_path(self):
157 157 settings_path = self.repo_vcs_config.get(*VcsSettingsModel.PATH_SETTING)
158 158
159 159 if not settings_path:
160 160 settings_path = self.global_vcs_config.get(*VcsSettingsModel.PATH_SETTING)
161 161
162 162 if not settings_path:
163 163 # try, maybe we passed in explicitly as config option
164 164 settings_path = self.config.get('base_path')
165 165
166 166 if not settings_path:
167 167 raise ValueError('FATAL: base_path is empty')
168 168 return settings_path
169 169
170 170 def set_repo_names(self, environ):
171 171 """
172 172 This will populate the attributes acl_repo_name, url_repo_name,
173 173 vcs_repo_name and is_shadow_repo. In case of requests to normal (non
174 174 shadow) repositories all names are equal. In case of requests to a
175 175 shadow repository the acl-name points to the target repo of the pull
176 176 request and the vcs-name points to the shadow repo file system path.
177 177 The url-name is always the URL used by the vcs client program.
178 178
179 179 Example in case of a shadow repo:
180 180 acl_repo_name = RepoGroup/MyRepo
181 181 url_repo_name = RepoGroup/MyRepo/pull-request/3/repository
182 182 vcs_repo_name = /repo/base/path/RepoGroup/.__shadow_MyRepo_pr-3'
183 183 """
184 184 # First we set the repo name from URL for all attributes. This is the
185 185 # default if handling normal (non shadow) repo requests.
186 186 self.url_repo_name = self._get_repository_name(environ)
187 187 self.acl_repo_name = self.vcs_repo_name = self.url_repo_name
188 188 self.is_shadow_repo = False
189 189
190 190 # Check if this is a request to a shadow repository.
191 191 match = self.shadow_repo_re.match(self.url_repo_name)
192 192 if match:
193 193 match_dict = match.groupdict()
194 194
195 195 # Build acl repo name from regex match.
196 196 acl_repo_name = safe_unicode('{groups}{target}'.format(
197 197 groups=match_dict['groups'] or '',
198 198 target=match_dict['target']))
199 199
200 200 # Retrieve pull request instance by ID from regex match.
201 201 pull_request = PullRequest.get(match_dict['pr_id'])
202 202
203 203 # Only proceed if we got a pull request and if acl repo name from
204 204 # URL equals the target repo name of the pull request.
205 205 if pull_request and (acl_repo_name == pull_request.target_repo.repo_name):
206 206
207 207 # Get file system path to shadow repository.
208 208 workspace_id = PullRequestModel()._workspace_id(pull_request)
209 209 vcs_repo_name = pull_request.target_repo.get_shadow_repository_path(workspace_id)
210 210
211 211 # Store names for later usage.
212 212 self.vcs_repo_name = vcs_repo_name
213 213 self.acl_repo_name = acl_repo_name
214 214 self.is_shadow_repo = True
215 215
216 216 log.debug('Setting all VCS repository names: %s', {
217 217 'acl_repo_name': self.acl_repo_name,
218 218 'url_repo_name': self.url_repo_name,
219 219 'vcs_repo_name': self.vcs_repo_name,
220 220 })
221 221
222 222 @property
223 223 def scm_app(self):
224 224 custom_implementation = self.config['vcs.scm_app_implementation']
225 225 if custom_implementation == 'http':
226 226 log.debug('Using HTTP implementation of scm app.')
227 227 scm_app_impl = scm_app_http
228 228 else:
229 229 log.debug('Using custom implementation of scm_app: "{}"'.format(
230 230 custom_implementation))
231 231 scm_app_impl = importlib.import_module(custom_implementation)
232 232 return scm_app_impl
233 233
234 234 def _get_by_id(self, repo_name):
235 235 """
236 236 Gets a special pattern _<ID> from clone url and tries to replace it
237 237 with a repository_name for support of _<ID> non changeable urls
238 238 """
239 239
240 240 data = repo_name.split('/')
241 241 if len(data) >= 2:
242 242 from rhodecode.model.repo import RepoModel
243 243 by_id_match = RepoModel().get_repo_by_id(repo_name)
244 244 if by_id_match:
245 245 data[1] = by_id_match.repo_name
246 246
247 247 return safe_str('/'.join(data))
248 248
249 249 def _invalidate_cache(self, repo_name):
250 250 """
251 251 Set's cache for this repository for invalidation on next access
252 252
253 253 :param repo_name: full repo name, also a cache key
254 254 """
255 255 ScmModel().mark_for_invalidation(repo_name)
256 256
257 257 def is_valid_and_existing_repo(self, repo_name, base_path, scm_type):
258 258 db_repo = Repository.get_by_repo_name(repo_name)
259 259 if not db_repo:
260 260 log.debug('Repository `%s` not found inside the database.',
261 261 repo_name)
262 262 return False
263 263
264 264 if db_repo.repo_type != scm_type:
265 265 log.warning(
266 266 'Repository `%s` have incorrect scm_type, expected %s got %s',
267 267 repo_name, db_repo.repo_type, scm_type)
268 268 return False
269 269
270 270 config = db_repo._config
271 271 config.set('extensions', 'largefiles', '')
272 272 return is_valid_repo(
273 273 repo_name, base_path,
274 274 explicit_scm=scm_type, expect_scm=scm_type, config=config)
275 275
276 276 def valid_and_active_user(self, user):
277 277 """
278 278 Checks if that user is not empty, and if it's actually object it checks
279 279 if he's active.
280 280
281 281 :param user: user object or None
282 282 :return: boolean
283 283 """
284 284 if user is None:
285 285 return False
286 286
287 287 elif user.active:
288 288 return True
289 289
290 290 return False
291 291
292 292 @property
293 293 def is_shadow_repo_dir(self):
294 294 return os.path.isdir(self.vcs_repo_name)
295 295
296 296 def _check_permission(self, action, user, auth_user, repo_name, ip_addr=None,
297 297 plugin_id='', plugin_cache_active=False, cache_ttl=0):
298 298 """
299 299 Checks permissions using action (push/pull) user and repository
300 300 name. If plugin_cache and ttl is set it will use the plugin which
301 301 authenticated the user to store the cached permissions result for N
302 302 amount of seconds as in cache_ttl
303 303
304 304 :param action: push or pull action
305 305 :param user: user instance
306 306 :param repo_name: repository name
307 307 """
308 308
309 309 log.debug('AUTH_CACHE_TTL for permissions `%s` active: %s (TTL: %s)',
310 310 plugin_id, plugin_cache_active, cache_ttl)
311 311
312 312 user_id = user.user_id
313 313 cache_namespace_uid = 'cache_user_auth.{}'.format(user_id)
314 314 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
315 315
316 316 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
317 317 expiration_time=cache_ttl,
318 318 condition=plugin_cache_active)
319 319 def compute_perm_vcs(
320 320 cache_name, plugin_id, action, user_id, repo_name, ip_addr):
321 321
322 322 log.debug('auth: calculating permission access now...')
323 323 # check IP
324 324 inherit = user.inherit_default_permissions
325 325 ip_allowed = AuthUser.check_ip_allowed(
326 326 user_id, ip_addr, inherit_from_default=inherit)
327 327 if ip_allowed:
328 328 log.info('Access for IP:%s allowed', ip_addr)
329 329 else:
330 330 return False
331 331
332 332 if action == 'push':
333 333 perms = ('repository.write', 'repository.admin')
334 334 if not HasPermissionAnyMiddleware(*perms)(auth_user, repo_name):
335 335 return False
336 336
337 337 else:
338 338 # any other action need at least read permission
339 339 perms = (
340 340 'repository.read', 'repository.write', 'repository.admin')
341 341 if not HasPermissionAnyMiddleware(*perms)(auth_user, repo_name):
342 342 return False
343 343
344 344 return True
345 345
346 346 start = time.time()
347 347 log.debug('Running plugin `%s` permissions check', plugin_id)
348 348
349 349 # for environ based auth, password can be empty, but then the validation is
350 350 # on the server that fills in the env data needed for authentication
351 351 perm_result = compute_perm_vcs(
352 352 'vcs_permissions', plugin_id, action, user.user_id, repo_name, ip_addr)
353 353
354 354 auth_time = time.time() - start
355 355 log.debug('Permissions for plugin `%s` completed in %.4fs, '
356 356 'expiration time of fetched cache %.1fs.',
357 357 plugin_id, auth_time, cache_ttl)
358 358
359 359 return perm_result
360 360
361 361 def _get_http_scheme(self, environ):
362 362 try:
363 363 return environ['wsgi.url_scheme']
364 364 except Exception:
365 365 log.exception('Failed to read http scheme')
366 366 return 'http'
367 367
368 368 def _check_ssl(self, environ, start_response):
369 369 """
370 370 Checks the SSL check flag and returns False if SSL is not present
371 371 and required True otherwise
372 372 """
373 373 org_proto = environ['wsgi._org_proto']
374 374 # check if we have SSL required ! if not it's a bad request !
375 375 require_ssl = str2bool(self.repo_vcs_config.get('web', 'push_ssl'))
376 376 if require_ssl and org_proto == 'http':
377 377 log.debug(
378 378 'Bad request: detected protocol is `%s` and '
379 379 'SSL/HTTPS is required.', org_proto)
380 380 return False
381 381 return True
382 382
383 383 def _get_default_cache_ttl(self):
384 384 # take AUTH_CACHE_TTL from the `rhodecode` auth plugin
385 385 plugin = loadplugin('egg:rhodecode-enterprise-ce#rhodecode')
386 386 plugin_settings = plugin.get_settings()
387 387 plugin_cache_active, cache_ttl = plugin.get_ttl_cache(
388 388 plugin_settings) or (False, 0)
389 389 return plugin_cache_active, cache_ttl
390 390
391 391 def __call__(self, environ, start_response):
392 392 try:
393 393 return self._handle_request(environ, start_response)
394 394 except Exception:
395 395 log.exception("Exception while handling request")
396 396 appenlight.track_exception(environ)
397 397 return HTTPInternalServerError()(environ, start_response)
398 398 finally:
399 399 meta.Session.remove()
400 400
401 401 def _handle_request(self, environ, start_response):
402 402 if not self._check_ssl(environ, start_response):
403 403 reason = ('SSL required, while RhodeCode was unable '
404 404 'to detect this as SSL request')
405 405 log.debug('User not allowed to proceed, %s', reason)
406 406 return HTTPNotAcceptable(reason)(environ, start_response)
407 407
408 408 if not self.url_repo_name:
409 409 log.warning('Repository name is empty: %s', self.url_repo_name)
410 410 # failed to get repo name, we fail now
411 411 return HTTPNotFound()(environ, start_response)
412 412 log.debug('Extracted repo name is %s', self.url_repo_name)
413 413
414 414 ip_addr = get_ip_addr(environ)
415 415 user_agent = get_user_agent(environ)
416 416 username = None
417 417
418 418 # skip passing error to error controller
419 419 environ['pylons.status_code_redirect'] = True
420 420
421 421 # ======================================================================
422 422 # GET ACTION PULL or PUSH
423 423 # ======================================================================
424 424 action = self._get_action(environ)
425 425
426 426 # ======================================================================
427 427 # Check if this is a request to a shadow repository of a pull request.
428 428 # In this case only pull action is allowed.
429 429 # ======================================================================
430 430 if self.is_shadow_repo and action != 'pull':
431 431 reason = 'Only pull action is allowed for shadow repositories.'
432 432 log.debug('User not allowed to proceed, %s', reason)
433 433 return HTTPNotAcceptable(reason)(environ, start_response)
434 434
435 435 # Check if the shadow repo actually exists, in case someone refers
436 436 # to it, and it has been deleted because of successful merge.
437 437 if self.is_shadow_repo and not self.is_shadow_repo_dir:
438 438 log.debug(
439 439 'Shadow repo detected, and shadow repo dir `%s` is missing',
440 440 self.is_shadow_repo_dir)
441 441 return HTTPNotFound()(environ, start_response)
442 442
443 443 # ======================================================================
444 444 # CHECK ANONYMOUS PERMISSION
445 445 # ======================================================================
446 446 detect_force_push = False
447 447 check_branch_perms = False
448 448 if action in ['pull', 'push']:
449 449 user_obj = anonymous_user = User.get_default_user()
450 450 auth_user = user_obj.AuthUser()
451 451 username = anonymous_user.username
452 452 if anonymous_user.active:
453 453 plugin_cache_active, cache_ttl = self._get_default_cache_ttl()
454 454 # ONLY check permissions if the user is activated
455 455 anonymous_perm = self._check_permission(
456 456 action, anonymous_user, auth_user, self.acl_repo_name, ip_addr,
457 457 plugin_id='anonymous_access',
458 458 plugin_cache_active=plugin_cache_active,
459 459 cache_ttl=cache_ttl,
460 460 )
461 461 else:
462 462 anonymous_perm = False
463 463
464 464 if not anonymous_user.active or not anonymous_perm:
465 465 if not anonymous_user.active:
466 466 log.debug('Anonymous access is disabled, running '
467 467 'authentication')
468 468
469 469 if not anonymous_perm:
470 470 log.debug('Not enough credentials to access this '
471 471 'repository as anonymous user')
472 472
473 473 username = None
474 474 # ==============================================================
475 475 # DEFAULT PERM FAILED OR ANONYMOUS ACCESS IS DISABLED SO WE
476 476 # NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS
477 477 # ==============================================================
478 478
479 479 # try to auth based on environ, container auth methods
480 480 log.debug('Running PRE-AUTH for container based authentication')
481 481 pre_auth = authenticate(
482 482 '', '', environ, VCS_TYPE, registry=self.registry,
483 483 acl_repo_name=self.acl_repo_name)
484 484 if pre_auth and pre_auth.get('username'):
485 485 username = pre_auth['username']
486 486 log.debug('PRE-AUTH got %s as username', username)
487 487 if pre_auth:
488 488 log.debug('PRE-AUTH successful from %s',
489 489 pre_auth.get('auth_data', {}).get('_plugin'))
490 490
491 491 # If not authenticated by the container, running basic auth
492 492 # before inject the calling repo_name for special scope checks
493 493 self.authenticate.acl_repo_name = self.acl_repo_name
494 494
495 495 plugin_cache_active, cache_ttl = False, 0
496 496 plugin = None
497 497 if not username:
498 498 self.authenticate.realm = self.authenticate.get_rc_realm()
499 499
500 500 try:
501 501 auth_result = self.authenticate(environ)
502 502 except (UserCreationError, NotAllowedToCreateUserError) as e:
503 503 log.error(e)
504 504 reason = safe_str(e)
505 505 return HTTPNotAcceptable(reason)(environ, start_response)
506 506
507 507 if isinstance(auth_result, dict):
508 508 AUTH_TYPE.update(environ, 'basic')
509 509 REMOTE_USER.update(environ, auth_result['username'])
510 510 username = auth_result['username']
511 511 plugin = auth_result.get('auth_data', {}).get('_plugin')
512 512 log.info(
513 513 'MAIN-AUTH successful for user `%s` from %s plugin',
514 514 username, plugin)
515 515
516 516 plugin_cache_active, cache_ttl = auth_result.get(
517 517 'auth_data', {}).get('_ttl_cache') or (False, 0)
518 518 else:
519 519 return auth_result.wsgi_application(environ, start_response)
520 520
521 521 # ==============================================================
522 522 # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME
523 523 # ==============================================================
524 524 user = User.get_by_username(username)
525 525 if not self.valid_and_active_user(user):
526 526 return HTTPForbidden()(environ, start_response)
527 527 username = user.username
528 528 user_id = user.user_id
529 529
530 530 # check user attributes for password change flag
531 531 user_obj = user
532 532 auth_user = user_obj.AuthUser()
533 533 if user_obj and user_obj.username != User.DEFAULT_USER and \
534 534 user_obj.user_data.get('force_password_change'):
535 535 reason = 'password change required'
536 536 log.debug('User not allowed to authenticate, %s', reason)
537 537 return HTTPNotAcceptable(reason)(environ, start_response)
538 538
539 539 # check permissions for this repository
540 540 perm = self._check_permission(
541 541 action, user, auth_user, self.acl_repo_name, ip_addr,
542 542 plugin, plugin_cache_active, cache_ttl)
543 543 if not perm:
544 544 return HTTPForbidden()(environ, start_response)
545 545 environ['rc_auth_user_id'] = user_id
546 546
547 547 if action == 'push':
548 548 perms = auth_user.get_branch_permissions(self.acl_repo_name)
549 549 if perms:
550 550 check_branch_perms = True
551 551 detect_force_push = True
552 552
553 553 # extras are injected into UI object and later available
554 554 # in hooks executed by RhodeCode
555 555 check_locking = _should_check_locking(environ.get('QUERY_STRING'))
556 556
557 557 extras = vcs_operation_context(
558 558 environ, repo_name=self.acl_repo_name, username=username,
559 559 action=action, scm=self.SCM, check_locking=check_locking,
560 560 is_shadow_repo=self.is_shadow_repo, check_branch_perms=check_branch_perms,
561 561 detect_force_push=detect_force_push
562 562 )
563 563
564 564 # ======================================================================
565 565 # REQUEST HANDLING
566 566 # ======================================================================
567 567 repo_path = os.path.join(
568 568 safe_str(self.base_path), safe_str(self.vcs_repo_name))
569 569 log.debug('Repository path is %s', repo_path)
570 570
571 571 fix_PATH()
572 572
573 573 log.info(
574 574 '%s action on %s repo "%s" by "%s" from %s %s',
575 575 action, self.SCM, safe_str(self.url_repo_name),
576 576 safe_str(username), ip_addr, user_agent)
577 577
578 578 return self._generate_vcs_response(
579 579 environ, start_response, repo_path, extras, action)
580 580
581 581 @initialize_generator
582 582 def _generate_vcs_response(
583 583 self, environ, start_response, repo_path, extras, action):
584 584 """
585 585 Returns a generator for the response content.
586 586
587 587 This method is implemented as a generator, so that it can trigger
588 588 the cache validation after all content sent back to the client. It
589 589 also handles the locking exceptions which will be triggered when
590 590 the first chunk is produced by the underlying WSGI application.
591 591 """
592 592 txn_id = ''
593 593 if 'CONTENT_LENGTH' in environ and environ['REQUEST_METHOD'] == 'MERGE':
594 594 # case for SVN, we want to re-use the callback daemon port
595 595 # so we use the txn_id, for this we peek the body, and still save
596 596 # it as wsgi.input
597 597 data = environ['wsgi.input'].read()
598 598 environ['wsgi.input'] = StringIO(data)
599 599 txn_id = extract_svn_txn_id(self.acl_repo_name, data)
600 600
601 601 callback_daemon, extras = self._prepare_callback_daemon(
602 602 extras, environ, action, txn_id=txn_id)
603 603 log.debug('HOOKS extras is %s', extras)
604 604
605 605 http_scheme = self._get_http_scheme(environ)
606 606
607 607 config = self._create_config(extras, self.acl_repo_name, scheme=http_scheme)
608 608 app = self._create_wsgi_app(repo_path, self.url_repo_name, config)
609 609 with callback_daemon:
610 610 app.rc_extras = extras
611 611
612 612 try:
613 613 response = app(environ, start_response)
614 614 finally:
615 615 # This statement works together with the decorator
616 616 # "initialize_generator" above. The decorator ensures that
617 617 # we hit the first yield statement before the generator is
618 618 # returned back to the WSGI server. This is needed to
619 619 # ensure that the call to "app" above triggers the
620 620 # needed callback to "start_response" before the
621 621 # generator is actually used.
622 622 yield "__init__"
623 623
624 624 # iter content
625 625 for chunk in response:
626 626 yield chunk
627 627
628 628 try:
629 629 # invalidate cache on push
630 630 if action == 'push':
631 631 self._invalidate_cache(self.url_repo_name)
632 632 finally:
633 633 meta.Session.remove()
634 634
635 635 def _get_repository_name(self, environ):
636 636 """Get repository name out of the environmnent
637 637
638 638 :param environ: WSGI environment
639 639 """
640 640 raise NotImplementedError()
641 641
642 642 def _get_action(self, environ):
643 643 """Map request commands into a pull or push command.
644 644
645 645 :param environ: WSGI environment
646 646 """
647 647 raise NotImplementedError()
648 648
649 649 def _create_wsgi_app(self, repo_path, repo_name, config):
650 650 """Return the WSGI app that will finally handle the request."""
651 651 raise NotImplementedError()
652 652
653 653 def _create_config(self, extras, repo_name, scheme='http'):
654 654 """Create a safe config representation."""
655 655 raise NotImplementedError()
656 656
657 657 def _should_use_callback_daemon(self, extras, environ, action):
658 658 if extras.get('is_shadow_repo'):
659 659 # we don't want to execute hooks, and callback daemon for shadow repos
660 660 return False
661 661 return True
662 662
663 663 def _prepare_callback_daemon(self, extras, environ, action, txn_id=None):
664 664 direct_calls = vcs_settings.HOOKS_DIRECT_CALLS
665 665 if not self._should_use_callback_daemon(extras, environ, action):
666 666 # disable callback daemon for actions that don't require it
667 667 direct_calls = True
668 668
669 669 return prepare_callback_daemon(
670 670 extras, protocol=vcs_settings.HOOKS_PROTOCOL,
671 671 host=vcs_settings.HOOKS_HOST, use_direct_calls=direct_calls, txn_id=txn_id)
672 672
673 673
674 674 def _should_check_locking(query_string):
675 675 # this is kind of hacky, but due to how mercurial handles client-server
676 676 # server see all operation on commit; bookmarks, phases and
677 677 # obsolescence marker in different transaction, we don't want to check
678 678 # locking on those
679 679 return query_string not in ['cmd=listkeys']
@@ -1,412 +1,412 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2020 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Client for the VCSServer implemented based on HTTP.
23 23 """
24 24
25 25 import copy
26 26 import logging
27 27 import threading
28 28 import time
29 29 import urllib.request, urllib.error, urllib.parse
30 30 import urllib.parse
31 31 import uuid
32 32 import traceback
33 33
34 34 import pycurl
35 35 import msgpack
36 36 import requests
37 37 from requests.packages.urllib3.util.retry import Retry
38 38
39 39 import rhodecode
40 40 from rhodecode.lib import rc_cache
41 41 from rhodecode.lib.rc_cache.utils import compute_key_from_params
42 42 from rhodecode.lib.system_info import get_cert_path
43 43 from rhodecode.lib.vcs import exceptions, CurlSession
44 44 from rhodecode.lib.utils2 import str2bool
45 45
46 46 log = logging.getLogger(__name__)
47 47
48 48
49 49 # TODO: mikhail: Keep it in sync with vcsserver's
50 50 # HTTPApplication.ALLOWED_EXCEPTIONS
51 51 EXCEPTIONS_MAP = {
52 52 'KeyError': KeyError,
53 53 'URLError': urllib.error.URLError,
54 54 }
55 55
56 56
57 57 def _remote_call(url, payload, exceptions_map, session):
58 58 try:
59 59 headers = {
60 60 'X-RC-Method': payload.get('method'),
61 61 'X-RC-Repo-Name': payload.get('_repo_name')
62 62 }
63 63 response = session.post(url, data=msgpack.packb(payload), headers=headers)
64 64 except pycurl.error as e:
65 65 msg = '{}. \npycurl traceback: {}'.format(e, traceback.format_exc())
66 66 raise exceptions.HttpVCSCommunicationError(msg)
67 67 except Exception as e:
68 68 message = getattr(e, 'message', '')
69 69 if 'Failed to connect' in message:
70 70 # gevent doesn't return proper pycurl errors
71 71 raise exceptions.HttpVCSCommunicationError(e)
72 72 else:
73 73 raise
74 74
75 75 if response.status_code >= 400:
76 76 log.error('Call to %s returned non 200 HTTP code: %s',
77 77 url, response.status_code)
78 78 raise exceptions.HttpVCSCommunicationError(repr(response.content))
79 79
80 80 try:
81 81 response = msgpack.unpackb(response.content)
82 82 except Exception:
83 83 log.exception('Failed to decode response %r', response.content)
84 84 raise
85 85
86 86 error = response.get('error')
87 87 if error:
88 88 type_ = error.get('type', 'Exception')
89 89 exc = exceptions_map.get(type_, Exception)
90 90 exc = exc(error.get('message'))
91 91 try:
92 92 exc._vcs_kind = error['_vcs_kind']
93 93 except KeyError:
94 94 pass
95 95
96 96 try:
97 97 exc._vcs_server_traceback = error['traceback']
98 98 exc._vcs_server_org_exc_name = error['org_exc']
99 99 exc._vcs_server_org_exc_tb = error['org_exc_tb']
100 100 except KeyError:
101 101 pass
102 102
103 103 raise exc
104 104 return response.get('result')
105 105
106 106
107 107 def _streaming_remote_call(url, payload, exceptions_map, session, chunk_size):
108 108 try:
109 109 headers = {
110 110 'X-RC-Method': payload.get('method'),
111 111 'X-RC-Repo-Name': payload.get('_repo_name')
112 112 }
113 113 response = session.post(url, data=msgpack.packb(payload), headers=headers)
114 114 except pycurl.error as e:
115 115 msg = '{}. \npycurl traceback: {}'.format(e, traceback.format_exc())
116 116 raise exceptions.HttpVCSCommunicationError(msg)
117 117 except Exception as e:
118 118 message = getattr(e, 'message', '')
119 119 if 'Failed to connect' in message:
120 120 # gevent doesn't return proper pycurl errors
121 121 raise exceptions.HttpVCSCommunicationError(e)
122 122 else:
123 123 raise
124 124
125 125 if response.status_code >= 400:
126 126 log.error('Call to %s returned non 200 HTTP code: %s',
127 127 url, response.status_code)
128 128 raise exceptions.HttpVCSCommunicationError(repr(response.content))
129 129
130 130 return response.iter_content(chunk_size=chunk_size)
131 131
132 132
133 133 class ServiceConnection(object):
134 134 def __init__(self, server_and_port, backend_endpoint, session_factory):
135 135 self.url = urllib.parse.urlparse.urljoin('http://%s' % server_and_port, backend_endpoint)
136 136 self._session_factory = session_factory
137 137
138 138 def __getattr__(self, name):
139 139 def f(*args, **kwargs):
140 140 return self._call(name, *args, **kwargs)
141 141 return f
142 142
143 143 @exceptions.map_vcs_exceptions
144 144 def _call(self, name, *args, **kwargs):
145 145 payload = {
146 146 'id': str(uuid.uuid4()),
147 147 'method': name,
148 148 'params': {'args': args, 'kwargs': kwargs}
149 149 }
150 150 return _remote_call(
151 151 self.url, payload, EXCEPTIONS_MAP, self._session_factory())
152 152
153 153
154 154 class RemoteVCSMaker(object):
155 155
156 156 def __init__(self, server_and_port, backend_endpoint, backend_type, session_factory):
157 157 self.url = urllib.parse.urlparse.urljoin('http://%s' % server_and_port, backend_endpoint)
158 158 self.stream_url = urllib.parse.urlparse.urljoin('http://%s' % server_and_port, backend_endpoint+'/stream')
159 159
160 160 self._session_factory = session_factory
161 161 self.backend_type = backend_type
162 162
163 163 @classmethod
164 164 def init_cache_region(cls, repo_id):
165 165 cache_namespace_uid = 'cache_repo.{}'.format(repo_id)
166 166 region = rc_cache.get_or_create_region('cache_repo', cache_namespace_uid)
167 167 return region, cache_namespace_uid
168 168
169 169 def __call__(self, path, repo_id, config, with_wire=None):
170 170 log.debug('%s RepoMaker call on %s', self.backend_type.upper(), path)
171 171 return RemoteRepo(path, repo_id, config, self, with_wire=with_wire)
172 172
173 173 def __getattr__(self, name):
174 174 def remote_attr(*args, **kwargs):
175 175 return self._call(name, *args, **kwargs)
176 176 return remote_attr
177 177
178 178 @exceptions.map_vcs_exceptions
179 179 def _call(self, func_name, *args, **kwargs):
180 180 payload = {
181 181 'id': str(uuid.uuid4()),
182 182 'method': func_name,
183 183 'backend': self.backend_type,
184 184 'params': {'args': args, 'kwargs': kwargs}
185 185 }
186 186 url = self.url
187 187 return _remote_call(url, payload, EXCEPTIONS_MAP, self._session_factory())
188 188
189 189
190 190 class RemoteRepo(object):
191 191 CHUNK_SIZE = 16384
192 192
193 193 def __init__(self, path, repo_id, config, remote_maker, with_wire=None):
194 194 self.url = remote_maker.url
195 195 self.stream_url = remote_maker.stream_url
196 196 self._session = remote_maker._session_factory()
197 197
198 198 cache_repo_id = self._repo_id_sanitizer(repo_id)
199 199 _repo_name = self._get_repo_name(config, path)
200 200 self._cache_region, self._cache_namespace = \
201 201 remote_maker.init_cache_region(cache_repo_id)
202 202
203 203 with_wire = with_wire or {}
204 204
205 205 repo_state_uid = with_wire.get('repo_state_uid') or 'state'
206 206
207 207 self._wire = {
208 208 "_repo_name": _repo_name,
209 209 "path": path, # repo path
210 210 "repo_id": repo_id,
211 211 "cache_repo_id": cache_repo_id,
212 212 "config": config,
213 213 "repo_state_uid": repo_state_uid,
214 214 "context": self._create_vcs_cache_context(path, repo_state_uid)
215 215 }
216 216
217 217 if with_wire:
218 218 self._wire.update(with_wire)
219 219
220 220 # NOTE(johbo): Trading complexity for performance. Avoiding the call to
221 221 # log.debug brings a few percent gain even if is is not active.
222 222 if log.isEnabledFor(logging.DEBUG):
223 223 self._call_with_logging = True
224 224
225 225 self.cert_dir = get_cert_path(rhodecode.CONFIG.get('__file__'))
226 226
227 227 def _get_repo_name(self, config, path):
228 228 repo_store = config.get('paths', '/')
229 229 return path.split(repo_store)[-1].lstrip('/')
230 230
231 231 def _repo_id_sanitizer(self, repo_id):
232 232 pathless = repo_id.replace('/', '__').replace('-', '_')
233 233 return ''.join(char if ord(char) < 128 else '_{}_'.format(ord(char)) for char in pathless)
234 234
235 235 def __getattr__(self, name):
236 236
237 237 if name.startswith('stream:'):
238 238 def repo_remote_attr(*args, **kwargs):
239 239 return self._call_stream(name, *args, **kwargs)
240 240 else:
241 241 def repo_remote_attr(*args, **kwargs):
242 242 return self._call(name, *args, **kwargs)
243 243
244 244 return repo_remote_attr
245 245
246 246 def _base_call(self, name, *args, **kwargs):
247 247 # TODO: oliver: This is currently necessary pre-call since the
248 248 # config object is being changed for hooking scenarios
249 249 wire = copy.deepcopy(self._wire)
250 250 wire["config"] = wire["config"].serialize()
251 251 wire["config"].append(('vcs', 'ssl_dir', self.cert_dir))
252 252
253 253 payload = {
254 254 'id': str(uuid.uuid4()),
255 255 'method': name,
256 256 "_repo_name": wire['_repo_name'],
257 257 'params': {'wire': wire, 'args': args, 'kwargs': kwargs}
258 258 }
259 259
260 260 context_uid = wire.get('context')
261 261 return context_uid, payload
262 262
263 263 def get_local_cache(self, name, args):
264 264 cache_on = False
265 265 cache_key = ''
266 266 local_cache_on = str2bool(rhodecode.CONFIG.get('vcs.methods.cache'))
267 267
268 268 cache_methods = [
269 269 'branches', 'tags', 'bookmarks',
270 270 'is_large_file', 'is_binary',
271 271 'fctx_size', 'stream:fctx_node_data', 'blob_raw_length',
272 272 'node_history',
273 273 'revision', 'tree_items',
274 274 'ctx_list', 'ctx_branch', 'ctx_description',
275 275 'bulk_request',
276 276 'assert_correct_path'
277 277 ]
278 278
279 279 if local_cache_on and name in cache_methods:
280 280 cache_on = True
281 281 repo_state_uid = self._wire['repo_state_uid']
282 282 call_args = [a for a in args]
283 283 cache_key = compute_key_from_params(repo_state_uid, name, *call_args)
284 284
285 285 return cache_on, cache_key
286 286
287 287 @exceptions.map_vcs_exceptions
288 288 def _call(self, name, *args, **kwargs):
289 289 context_uid, payload = self._base_call(name, *args, **kwargs)
290 290 url = self.url
291 291
292 292 start = time.time()
293 293 cache_on, cache_key = self.get_local_cache(name, args)
294 294
295 295 @self._cache_region.conditional_cache_on_arguments(
296 296 namespace=self._cache_namespace, condition=cache_on and cache_key)
297 297 def remote_call(_cache_key):
298 298 if self._call_with_logging:
299 299 log.debug('Calling %s@%s with args:%.10240r. wire_context: %s cache_on: %s',
300 300 url, name, args, context_uid, cache_on)
301 301 return _remote_call(url, payload, EXCEPTIONS_MAP, self._session)
302 302
303 303 result = remote_call(cache_key)
304 304 if self._call_with_logging:
305 305 log.debug('Call %s@%s took: %.4fs. wire_context: %s',
306 306 url, name, time.time()-start, context_uid)
307 307 return result
308 308
309 309 @exceptions.map_vcs_exceptions
310 310 def _call_stream(self, name, *args, **kwargs):
311 311 context_uid, payload = self._base_call(name, *args, **kwargs)
312 312 payload['chunk_size'] = self.CHUNK_SIZE
313 313 url = self.stream_url
314 314
315 315 start = time.time()
316 316 cache_on, cache_key = self.get_local_cache(name, args)
317 317
318 318 # Cache is a problem because this is a stream
319 319 def streaming_remote_call(_cache_key):
320 320 if self._call_with_logging:
321 321 log.debug('Calling %s@%s with args:%.10240r. wire_context: %s cache_on: %s',
322 322 url, name, args, context_uid, cache_on)
323 323 return _streaming_remote_call(url, payload, EXCEPTIONS_MAP, self._session, self.CHUNK_SIZE)
324 324
325 325 result = streaming_remote_call(cache_key)
326 326 if self._call_with_logging:
327 327 log.debug('Call %s@%s took: %.4fs. wire_context: %s',
328 328 url, name, time.time()-start, context_uid)
329 329 return result
330 330
331 331 def __getitem__(self, key):
332 332 return self.revision(key)
333 333
334 334 def _create_vcs_cache_context(self, *args):
335 335 """
336 336 Creates a unique string which is passed to the VCSServer on every
337 337 remote call. It is used as cache key in the VCSServer.
338 338 """
339 339 hash_key = '-'.join(map(str, args))
340 340 return str(uuid.uuid5(uuid.NAMESPACE_URL, hash_key))
341 341
342 342 def invalidate_vcs_cache(self):
343 343 """
344 344 This invalidates the context which is sent to the VCSServer on every
345 345 call to a remote method. It forces the VCSServer to create a fresh
346 346 repository instance on the next call to a remote method.
347 347 """
348 348 self._wire['context'] = str(uuid.uuid4())
349 349
350 350
351 351 class VcsHttpProxy(object):
352 352
353 353 CHUNK_SIZE = 16384
354 354
355 355 def __init__(self, server_and_port, backend_endpoint):
356 356 retries = Retry(total=5, connect=None, read=None, redirect=None)
357 357
358 358 adapter = requests.adapters.HTTPAdapter(max_retries=retries)
359 359 self.base_url = urllib.parse.urlparse.urljoin('http://%s' % server_and_port, backend_endpoint)
360 360 self.session = requests.Session()
361 361 self.session.mount('http://', adapter)
362 362
363 363 def handle(self, environment, input_data, *args, **kwargs):
364 364 data = {
365 365 'environment': environment,
366 366 'input_data': input_data,
367 367 'args': args,
368 368 'kwargs': kwargs
369 369 }
370 370 result = self.session.post(
371 371 self.base_url, msgpack.packb(data), stream=True)
372 372 return self._get_result(result)
373 373
374 374 def _deserialize_and_raise(self, error):
375 375 exception = Exception(error['message'])
376 376 try:
377 377 exception._vcs_kind = error['_vcs_kind']
378 378 except KeyError:
379 379 pass
380 380 raise exception
381 381
382 382 def _iterate(self, result):
383 383 unpacker = msgpack.Unpacker()
384 384 for line in result.iter_content(chunk_size=self.CHUNK_SIZE):
385 385 unpacker.feed(line)
386 386 for chunk in unpacker:
387 387 yield chunk
388 388
389 389 def _get_result(self, result):
390 390 iterator = self._iterate(result)
391 error = iterator.next()
391 error = next(iterator)
392 392 if error:
393 393 self._deserialize_and_raise(error)
394 394
395 status = iterator.next()
396 headers = iterator.next()
395 status = next(iterator)
396 headers = next(iterator)
397 397
398 398 return iterator, status, headers
399 399
400 400
401 401 class ThreadlocalSessionFactory(object):
402 402 """
403 403 Creates one CurlSession per thread on demand.
404 404 """
405 405
406 406 def __init__(self):
407 407 self._thread_local = threading.local()
408 408
409 409 def __call__(self):
410 410 if not hasattr(self._thread_local, 'curl_session'):
411 411 self._thread_local.curl_session = CurlSession()
412 412 return self._thread_local.curl_session
@@ -1,135 +1,135 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2020 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21
22 22 import logging
23 23
24 24 import rhodecode
25 25 from rhodecode.model import meta, db
26 26 from rhodecode.lib.utils2 import obfuscate_url_pw, get_encryption_key
27 27
28 28 log = logging.getLogger(__name__)
29 29
30 30
31 31 def init_model(engine, encryption_key=None):
32 32 """
33 33 Initializes db session, bind the engine with the metadata,
34 34 Call this before using any of the tables or classes in the model,
35 35 preferably once in application start
36 36
37 37 :param engine: engine to bind to
38 38 """
39 39 engine_str = obfuscate_url_pw(str(engine.url))
40 40 log.info("RhodeCode %s initializing db for %s", rhodecode.__version__, engine_str)
41 41 meta.Base.metadata.bind = engine
42 42 db.ENCRYPTION_KEY = encryption_key
43 43
44 44
45 45 def init_model_encryption(migration_models, config=None):
46 46 from pyramid.threadlocal import get_current_registry
47 47 config = config or get_current_registry().settings
48 48 migration_models.ENCRYPTION_KEY = get_encryption_key(config)
49 49 db.ENCRYPTION_KEY = get_encryption_key(config)
50 50
51 51
52 52 class BaseModel(object):
53 53 """
54 54 Base Model for all RhodeCode models, it adds sql alchemy session
55 55 into instance of model
56 56
57 57 :param sa: If passed it reuses this session instead of creating a new one
58 58 """
59 59
60 60 cls = None # override in child class
61 61
62 62 def __init__(self, sa=None):
63 63 if sa is not None:
64 64 self.sa = sa
65 65 else:
66 66 self.sa = meta.Session()
67 67
68 68 def _get_instance(self, cls, instance, callback=None):
69 69 """
70 70 Gets instance of given cls using some simple lookup mechanism.
71 71
72 72 :param cls: classes to fetch
73 73 :param instance: int or Instance
74 74 :param callback: callback to call if all lookups failed
75 75 """
76 76
77 77 if isinstance(instance, cls):
78 78 return instance
79 79 elif isinstance(instance, int):
80 80 if isinstance(cls, tuple):
81 81 # if we pass multi instances we pick first to .get()
82 82 cls = cls[0]
83 83 return cls.get(instance)
84 84 else:
85 85 if instance:
86 86 if callback is None:
87 87 raise Exception(
88 'given object must be int, long or Instance of %s '
88 'given object must be int or Instance of %s '
89 89 'got %s, no callback provided' % (cls, type(instance))
90 90 )
91 91 else:
92 92 return callback(instance)
93 93
94 94 def _get_user(self, user):
95 95 """
96 96 Helper method to get user by ID, or username fallback
97 97
98 98 :param user: UserID, username, or User instance
99 99 """
100 100 return self._get_instance(
101 101 db.User, user, callback=db.User.get_by_username)
102 102
103 103 def _get_user_group(self, user_group):
104 104 """
105 105 Helper method to get user by ID, or username fallback
106 106
107 107 :param user_group: UserGroupID, user_group_name, or UserGroup instance
108 108 """
109 109 return self._get_instance(
110 110 db.UserGroup, user_group, callback=db.UserGroup.get_by_group_name)
111 111
112 112 def _get_repo(self, repository):
113 113 """
114 114 Helper method to get repository by ID, or repository name
115 115
116 116 :param repository: RepoID, repository name or Repository Instance
117 117 """
118 118 return self._get_instance(
119 119 db.Repository, repository, callback=db.Repository.get_by_repo_name)
120 120
121 121 def _get_perm(self, permission):
122 122 """
123 123 Helper method to get permission by ID, or permission name
124 124
125 125 :param permission: PermissionID, permission_name or Permission instance
126 126 """
127 127 return self._get_instance(
128 128 db.Permission, permission, callback=db.Permission.get_by_key)
129 129
130 130 @classmethod
131 131 def get_all(cls):
132 132 """
133 133 Returns all instances of what is defined in `cls` class variable
134 134 """
135 135 return cls.cls.getAll()
@@ -1,5838 +1,5838 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2020 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Database Models for RhodeCode Enterprise
23 23 """
24 24
25 25 import re
26 26 import os
27 27 import time
28 28 import string
29 29 import hashlib
30 30 import logging
31 31 import datetime
32 32 import uuid
33 33 import warnings
34 34 import ipaddress
35 35 import functools
36 36 import traceback
37 37 import collections
38 38
39 39 from sqlalchemy import (
40 40 or_, and_, not_, func, cast, TypeDecorator, event,
41 41 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
42 42 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
43 43 Text, Float, PickleType, BigInteger)
44 44 from sqlalchemy.sql.expression import true, false, case, null
45 45 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
46 46 from sqlalchemy.orm import (
47 47 relationship, lazyload, joinedload, class_mapper, validates, aliased)
48 48 from sqlalchemy.ext.declarative import declared_attr
49 49 from sqlalchemy.ext.hybrid import hybrid_property
50 50 from sqlalchemy.exc import IntegrityError # pragma: no cover
51 51 from sqlalchemy.dialects.mysql import LONGTEXT
52 52 from zope.cachedescriptors.property import Lazy as LazyProperty
53 53 from pyramid.threadlocal import get_current_request
54 54 from webhelpers2.text import remove_formatting
55 55
56 56 from rhodecode.translation import _
57 57 from rhodecode.lib.vcs import get_vcs_instance, VCSError
58 58 from rhodecode.lib.vcs.backends.base import (
59 59 EmptyCommit, Reference, unicode_to_reference, reference_to_unicode)
60 60 from rhodecode.lib.utils2 import (
61 61 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
62 62 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
63 63 glob2re, StrictAttributeDict, cleaned_uri, datetime_to_time)
64 64 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
65 65 JsonRaw
66 66 from rhodecode.lib.ext_json import json
67 67 from rhodecode.lib.caching_query import FromCache
68 68 from rhodecode.lib.encrypt import AESCipher, validate_and_get_enc_data
69 69 from rhodecode.lib.encrypt2 import Encryptor
70 70 from rhodecode.lib.exceptions import (
71 71 ArtifactMetadataDuplicate, ArtifactMetadataBadValueType)
72 72 from rhodecode.model.meta import Base, Session
73 73
74 74 URL_SEP = '/'
75 75 log = logging.getLogger(__name__)
76 76
77 77 # =============================================================================
78 78 # BASE CLASSES
79 79 # =============================================================================
80 80
81 81 # this is propagated from .ini file rhodecode.encrypted_values.secret or
82 82 # beaker.session.secret if first is not set.
83 83 # and initialized at environment.py
84 84 ENCRYPTION_KEY = None
85 85
86 86 # used to sort permissions by types, '#' used here is not allowed to be in
87 87 # usernames, and it's very early in sorted string.printable table.
88 88 PERMISSION_TYPE_SORT = {
89 89 'admin': '####',
90 90 'write': '###',
91 91 'read': '##',
92 92 'none': '#',
93 93 }
94 94
95 95
96 96 def display_user_sort(obj):
97 97 """
98 98 Sort function used to sort permissions in .permissions() function of
99 99 Repository, RepoGroup, UserGroup. Also it put the default user in front
100 100 of all other resources
101 101 """
102 102
103 103 if obj.username == User.DEFAULT_USER:
104 104 return '#####'
105 105 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
106 106 extra_sort_num = '1' # default
107 107
108 108 # NOTE(dan): inactive duplicates goes last
109 109 if getattr(obj, 'duplicate_perm', None):
110 110 extra_sort_num = '9'
111 111 return prefix + extra_sort_num + obj.username
112 112
113 113
114 114 def display_user_group_sort(obj):
115 115 """
116 116 Sort function used to sort permissions in .permissions() function of
117 117 Repository, RepoGroup, UserGroup. Also it put the default user in front
118 118 of all other resources
119 119 """
120 120
121 121 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
122 122 return prefix + obj.users_group_name
123 123
124 124
125 125 def _hash_key(k):
126 126 return sha1_safe(k)
127 127
128 128
129 129 def in_filter_generator(qry, items, limit=500):
130 130 """
131 131 Splits IN() into multiple with OR
132 132 e.g.::
133 133 cnt = Repository.query().filter(
134 134 or_(
135 135 *in_filter_generator(Repository.repo_id, range(100000))
136 136 )).count()
137 137 """
138 138 if not items:
139 139 # empty list will cause empty query which might cause security issues
140 140 # this can lead to hidden unpleasant results
141 141 items = [-1]
142 142
143 143 parts = []
144 144 for chunk in range(0, len(items), limit):
145 145 parts.append(
146 146 qry.in_(items[chunk: chunk + limit])
147 147 )
148 148
149 149 return parts
150 150
151 151
152 152 base_table_args = {
153 153 'extend_existing': True,
154 154 'mysql_engine': 'InnoDB',
155 155 'mysql_charset': 'utf8',
156 156 'sqlite_autoincrement': True
157 157 }
158 158
159 159
160 160 class EncryptedTextValue(TypeDecorator):
161 161 """
162 162 Special column for encrypted long text data, use like::
163 163
164 164 value = Column("encrypted_value", EncryptedValue(), nullable=False)
165 165
166 166 This column is intelligent so if value is in unencrypted form it return
167 167 unencrypted form, but on save it always encrypts
168 168 """
169 169 impl = Text
170 170
171 171 def process_bind_param(self, value, dialect):
172 172 """
173 173 Setter for storing value
174 174 """
175 175 import rhodecode
176 176 if not value:
177 177 return value
178 178
179 179 # protect against double encrypting if values is already encrypted
180 180 if value.startswith('enc$aes$') \
181 181 or value.startswith('enc$aes_hmac$') \
182 182 or value.startswith('enc2$'):
183 183 raise ValueError('value needs to be in unencrypted format, '
184 184 'ie. not starting with enc$ or enc2$')
185 185
186 186 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
187 187 if algo == 'aes':
188 188 return 'enc$aes_hmac$%s' % AESCipher(ENCRYPTION_KEY, hmac=True).encrypt(value)
189 189 elif algo == 'fernet':
190 190 return Encryptor(ENCRYPTION_KEY).encrypt(value)
191 191 else:
192 192 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
193 193
194 194 def process_result_value(self, value, dialect):
195 195 """
196 196 Getter for retrieving value
197 197 """
198 198
199 199 import rhodecode
200 200 if not value:
201 201 return value
202 202
203 203 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
204 204 enc_strict_mode = str2bool(rhodecode.CONFIG.get('rhodecode.encrypted_values.strict') or True)
205 205 if algo == 'aes':
206 206 decrypted_data = validate_and_get_enc_data(value, ENCRYPTION_KEY, enc_strict_mode)
207 207 elif algo == 'fernet':
208 208 return Encryptor(ENCRYPTION_KEY).decrypt(value)
209 209 else:
210 210 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
211 211 return decrypted_data
212 212
213 213
214 214 class BaseModel(object):
215 215 """
216 216 Base Model for all classes
217 217 """
218 218
219 219 @classmethod
220 220 def _get_keys(cls):
221 221 """return column names for this model """
222 222 return class_mapper(cls).c.keys()
223 223
224 224 def get_dict(self):
225 225 """
226 226 return dict with keys and values corresponding
227 227 to this model data """
228 228
229 229 d = {}
230 230 for k in self._get_keys():
231 231 d[k] = getattr(self, k)
232 232
233 233 # also use __json__() if present to get additional fields
234 234 _json_attr = getattr(self, '__json__', None)
235 235 if _json_attr:
236 236 # update with attributes from __json__
237 237 if callable(_json_attr):
238 238 _json_attr = _json_attr()
239 239 for k, val in _json_attr.items():
240 240 d[k] = val
241 241 return d
242 242
243 243 def get_appstruct(self):
244 244 """return list with keys and values tuples corresponding
245 245 to this model data """
246 246
247 247 lst = []
248 248 for k in self._get_keys():
249 249 lst.append((k, getattr(self, k),))
250 250 return lst
251 251
252 252 def populate_obj(self, populate_dict):
253 253 """populate model with data from given populate_dict"""
254 254
255 255 for k in self._get_keys():
256 256 if k in populate_dict:
257 257 setattr(self, k, populate_dict[k])
258 258
259 259 @classmethod
260 260 def query(cls):
261 261 return Session().query(cls)
262 262
263 263 @classmethod
264 264 def get(cls, id_):
265 265 if id_:
266 266 return cls.query().get(id_)
267 267
268 268 @classmethod
269 269 def get_or_404(cls, id_):
270 270 from pyramid.httpexceptions import HTTPNotFound
271 271
272 272 try:
273 273 id_ = int(id_)
274 274 except (TypeError, ValueError):
275 275 raise HTTPNotFound()
276 276
277 277 res = cls.query().get(id_)
278 278 if not res:
279 279 raise HTTPNotFound()
280 280 return res
281 281
282 282 @classmethod
283 283 def getAll(cls):
284 284 # deprecated and left for backward compatibility
285 285 return cls.get_all()
286 286
287 287 @classmethod
288 288 def get_all(cls):
289 289 return cls.query().all()
290 290
291 291 @classmethod
292 292 def delete(cls, id_):
293 293 obj = cls.query().get(id_)
294 294 Session().delete(obj)
295 295
296 296 @classmethod
297 297 def identity_cache(cls, session, attr_name, value):
298 298 exist_in_session = []
299 299 for (item_cls, pkey), instance in session.identity_map.items():
300 300 if cls == item_cls and getattr(instance, attr_name) == value:
301 301 exist_in_session.append(instance)
302 302 if exist_in_session:
303 303 if len(exist_in_session) == 1:
304 304 return exist_in_session[0]
305 305 log.exception(
306 306 'multiple objects with attr %s and '
307 307 'value %s found with same name: %r',
308 308 attr_name, value, exist_in_session)
309 309
310 310 def __repr__(self):
311 311 if hasattr(self, '__unicode__'):
312 312 # python repr needs to return str
313 313 try:
314 314 return safe_str(self.__unicode__())
315 315 except UnicodeDecodeError:
316 316 pass
317 317 return '<DB:%s>' % (self.__class__.__name__)
318 318
319 319
320 320 class RhodeCodeSetting(Base, BaseModel):
321 321 __tablename__ = 'rhodecode_settings'
322 322 __table_args__ = (
323 323 UniqueConstraint('app_settings_name'),
324 324 base_table_args
325 325 )
326 326
327 327 SETTINGS_TYPES = {
328 328 'str': safe_str,
329 329 'int': safe_int,
330 330 'unicode': safe_unicode,
331 331 'bool': str2bool,
332 332 'list': functools.partial(aslist, sep=',')
333 333 }
334 334 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
335 335 GLOBAL_CONF_KEY = 'app_settings'
336 336
337 337 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
338 338 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
339 339 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
340 340 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
341 341
342 342 def __init__(self, key='', val='', type='unicode'):
343 343 self.app_settings_name = key
344 344 self.app_settings_type = type
345 345 self.app_settings_value = val
346 346
347 347 @validates('_app_settings_value')
348 348 def validate_settings_value(self, key, val):
349 349 assert type(val) == unicode
350 350 return val
351 351
352 352 @hybrid_property
353 353 def app_settings_value(self):
354 354 v = self._app_settings_value
355 355 _type = self.app_settings_type
356 356 if _type:
357 357 _type = self.app_settings_type.split('.')[0]
358 358 # decode the encrypted value
359 359 if 'encrypted' in self.app_settings_type:
360 360 cipher = EncryptedTextValue()
361 361 v = safe_unicode(cipher.process_result_value(v, None))
362 362
363 363 converter = self.SETTINGS_TYPES.get(_type) or \
364 364 self.SETTINGS_TYPES['unicode']
365 365 return converter(v)
366 366
367 367 @app_settings_value.setter
368 368 def app_settings_value(self, val):
369 369 """
370 370 Setter that will always make sure we use unicode in app_settings_value
371 371
372 372 :param val:
373 373 """
374 374 val = safe_unicode(val)
375 375 # encode the encrypted value
376 376 if 'encrypted' in self.app_settings_type:
377 377 cipher = EncryptedTextValue()
378 378 val = safe_unicode(cipher.process_bind_param(val, None))
379 379 self._app_settings_value = val
380 380
381 381 @hybrid_property
382 382 def app_settings_type(self):
383 383 return self._app_settings_type
384 384
385 385 @app_settings_type.setter
386 386 def app_settings_type(self, val):
387 387 if val.split('.')[0] not in self.SETTINGS_TYPES:
388 388 raise Exception('type must be one of %s got %s'
389 389 % (self.SETTINGS_TYPES.keys(), val))
390 390 self._app_settings_type = val
391 391
392 392 @classmethod
393 393 def get_by_prefix(cls, prefix):
394 394 return RhodeCodeSetting.query()\
395 395 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
396 396 .all()
397 397
398 398 def __unicode__(self):
399 399 return u"<%s('%s:%s[%s]')>" % (
400 400 self.__class__.__name__,
401 401 self.app_settings_name, self.app_settings_value,
402 402 self.app_settings_type
403 403 )
404 404
405 405
406 406 class RhodeCodeUi(Base, BaseModel):
407 407 __tablename__ = 'rhodecode_ui'
408 408 __table_args__ = (
409 409 UniqueConstraint('ui_key'),
410 410 base_table_args
411 411 )
412 412
413 413 HOOK_REPO_SIZE = 'changegroup.repo_size'
414 414 # HG
415 415 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
416 416 HOOK_PULL = 'outgoing.pull_logger'
417 417 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
418 418 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
419 419 HOOK_PUSH = 'changegroup.push_logger'
420 420 HOOK_PUSH_KEY = 'pushkey.key_push'
421 421
422 422 HOOKS_BUILTIN = [
423 423 HOOK_PRE_PULL,
424 424 HOOK_PULL,
425 425 HOOK_PRE_PUSH,
426 426 HOOK_PRETX_PUSH,
427 427 HOOK_PUSH,
428 428 HOOK_PUSH_KEY,
429 429 ]
430 430
431 431 # TODO: johbo: Unify way how hooks are configured for git and hg,
432 432 # git part is currently hardcoded.
433 433
434 434 # SVN PATTERNS
435 435 SVN_BRANCH_ID = 'vcs_svn_branch'
436 436 SVN_TAG_ID = 'vcs_svn_tag'
437 437
438 438 ui_id = Column(
439 439 "ui_id", Integer(), nullable=False, unique=True, default=None,
440 440 primary_key=True)
441 441 ui_section = Column(
442 442 "ui_section", String(255), nullable=True, unique=None, default=None)
443 443 ui_key = Column(
444 444 "ui_key", String(255), nullable=True, unique=None, default=None)
445 445 ui_value = Column(
446 446 "ui_value", String(255), nullable=True, unique=None, default=None)
447 447 ui_active = Column(
448 448 "ui_active", Boolean(), nullable=True, unique=None, default=True)
449 449
450 450 def __repr__(self):
451 451 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
452 452 self.ui_key, self.ui_value)
453 453
454 454
455 455 class RepoRhodeCodeSetting(Base, BaseModel):
456 456 __tablename__ = 'repo_rhodecode_settings'
457 457 __table_args__ = (
458 458 UniqueConstraint(
459 459 'app_settings_name', 'repository_id',
460 460 name='uq_repo_rhodecode_setting_name_repo_id'),
461 461 base_table_args
462 462 )
463 463
464 464 repository_id = Column(
465 465 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
466 466 nullable=False)
467 467 app_settings_id = Column(
468 468 "app_settings_id", Integer(), nullable=False, unique=True,
469 469 default=None, primary_key=True)
470 470 app_settings_name = Column(
471 471 "app_settings_name", String(255), nullable=True, unique=None,
472 472 default=None)
473 473 _app_settings_value = Column(
474 474 "app_settings_value", String(4096), nullable=True, unique=None,
475 475 default=None)
476 476 _app_settings_type = Column(
477 477 "app_settings_type", String(255), nullable=True, unique=None,
478 478 default=None)
479 479
480 480 repository = relationship('Repository')
481 481
482 482 def __init__(self, repository_id, key='', val='', type='unicode'):
483 483 self.repository_id = repository_id
484 484 self.app_settings_name = key
485 485 self.app_settings_type = type
486 486 self.app_settings_value = val
487 487
488 488 @validates('_app_settings_value')
489 489 def validate_settings_value(self, key, val):
490 490 assert type(val) == unicode
491 491 return val
492 492
493 493 @hybrid_property
494 494 def app_settings_value(self):
495 495 v = self._app_settings_value
496 496 type_ = self.app_settings_type
497 497 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
498 498 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
499 499 return converter(v)
500 500
501 501 @app_settings_value.setter
502 502 def app_settings_value(self, val):
503 503 """
504 504 Setter that will always make sure we use unicode in app_settings_value
505 505
506 506 :param val:
507 507 """
508 508 self._app_settings_value = safe_unicode(val)
509 509
510 510 @hybrid_property
511 511 def app_settings_type(self):
512 512 return self._app_settings_type
513 513
514 514 @app_settings_type.setter
515 515 def app_settings_type(self, val):
516 516 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
517 517 if val not in SETTINGS_TYPES:
518 518 raise Exception('type must be one of %s got %s'
519 519 % (SETTINGS_TYPES.keys(), val))
520 520 self._app_settings_type = val
521 521
522 522 def __unicode__(self):
523 523 return u"<%s('%s:%s:%s[%s]')>" % (
524 524 self.__class__.__name__, self.repository.repo_name,
525 525 self.app_settings_name, self.app_settings_value,
526 526 self.app_settings_type
527 527 )
528 528
529 529
530 530 class RepoRhodeCodeUi(Base, BaseModel):
531 531 __tablename__ = 'repo_rhodecode_ui'
532 532 __table_args__ = (
533 533 UniqueConstraint(
534 534 'repository_id', 'ui_section', 'ui_key',
535 535 name='uq_repo_rhodecode_ui_repository_id_section_key'),
536 536 base_table_args
537 537 )
538 538
539 539 repository_id = Column(
540 540 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
541 541 nullable=False)
542 542 ui_id = Column(
543 543 "ui_id", Integer(), nullable=False, unique=True, default=None,
544 544 primary_key=True)
545 545 ui_section = Column(
546 546 "ui_section", String(255), nullable=True, unique=None, default=None)
547 547 ui_key = Column(
548 548 "ui_key", String(255), nullable=True, unique=None, default=None)
549 549 ui_value = Column(
550 550 "ui_value", String(255), nullable=True, unique=None, default=None)
551 551 ui_active = Column(
552 552 "ui_active", Boolean(), nullable=True, unique=None, default=True)
553 553
554 554 repository = relationship('Repository')
555 555
556 556 def __repr__(self):
557 557 return '<%s[%s:%s]%s=>%s]>' % (
558 558 self.__class__.__name__, self.repository.repo_name,
559 559 self.ui_section, self.ui_key, self.ui_value)
560 560
561 561
562 562 class User(Base, BaseModel):
563 563 __tablename__ = 'users'
564 564 __table_args__ = (
565 565 UniqueConstraint('username'), UniqueConstraint('email'),
566 566 Index('u_username_idx', 'username'),
567 567 Index('u_email_idx', 'email'),
568 568 base_table_args
569 569 )
570 570
571 571 DEFAULT_USER = 'default'
572 572 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
573 573 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
574 574
575 575 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
576 576 username = Column("username", String(255), nullable=True, unique=None, default=None)
577 577 password = Column("password", String(255), nullable=True, unique=None, default=None)
578 578 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
579 579 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
580 580 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
581 581 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
582 582 _email = Column("email", String(255), nullable=True, unique=None, default=None)
583 583 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
584 584 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
585 585 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
586 586
587 587 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
588 588 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
589 589 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
590 590 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
591 591 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
592 592 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
593 593
594 594 user_log = relationship('UserLog')
595 595 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all, delete-orphan')
596 596
597 597 repositories = relationship('Repository')
598 598 repository_groups = relationship('RepoGroup')
599 599 user_groups = relationship('UserGroup')
600 600
601 601 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
602 602 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
603 603
604 604 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all, delete-orphan')
605 605 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
606 606 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
607 607
608 608 group_member = relationship('UserGroupMember', cascade='all')
609 609
610 610 notifications = relationship('UserNotification', cascade='all')
611 611 # notifications assigned to this user
612 612 user_created_notifications = relationship('Notification', cascade='all')
613 613 # comments created by this user
614 614 user_comments = relationship('ChangesetComment', cascade='all')
615 615 # user profile extra info
616 616 user_emails = relationship('UserEmailMap', cascade='all')
617 617 user_ip_map = relationship('UserIpMap', cascade='all')
618 618 user_auth_tokens = relationship('UserApiKeys', cascade='all')
619 619 user_ssh_keys = relationship('UserSshKeys', cascade='all')
620 620
621 621 # gists
622 622 user_gists = relationship('Gist', cascade='all')
623 623 # user pull requests
624 624 user_pull_requests = relationship('PullRequest', cascade='all')
625 625
626 626 # external identities
627 627 external_identities = relationship(
628 628 'ExternalIdentity',
629 629 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
630 630 cascade='all')
631 631 # review rules
632 632 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
633 633
634 634 # artifacts owned
635 635 artifacts = relationship('FileStore', primaryjoin='FileStore.user_id==User.user_id')
636 636
637 637 # no cascade, set NULL
638 638 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_user_id==User.user_id')
639 639
640 640 def __unicode__(self):
641 641 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
642 642 self.user_id, self.username)
643 643
644 644 @hybrid_property
645 645 def email(self):
646 646 return self._email
647 647
648 648 @email.setter
649 649 def email(self, val):
650 650 self._email = val.lower() if val else None
651 651
652 652 @hybrid_property
653 653 def first_name(self):
654 654 from rhodecode.lib import helpers as h
655 655 if self.name:
656 656 return h.escape(self.name)
657 657 return self.name
658 658
659 659 @hybrid_property
660 660 def last_name(self):
661 661 from rhodecode.lib import helpers as h
662 662 if self.lastname:
663 663 return h.escape(self.lastname)
664 664 return self.lastname
665 665
666 666 @hybrid_property
667 667 def api_key(self):
668 668 """
669 669 Fetch if exist an auth-token with role ALL connected to this user
670 670 """
671 671 user_auth_token = UserApiKeys.query()\
672 672 .filter(UserApiKeys.user_id == self.user_id)\
673 673 .filter(or_(UserApiKeys.expires == -1,
674 674 UserApiKeys.expires >= time.time()))\
675 675 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
676 676 if user_auth_token:
677 677 user_auth_token = user_auth_token.api_key
678 678
679 679 return user_auth_token
680 680
681 681 @api_key.setter
682 682 def api_key(self, val):
683 683 # don't allow to set API key this is deprecated for now
684 684 self._api_key = None
685 685
686 686 @property
687 687 def reviewer_pull_requests(self):
688 688 return PullRequestReviewers.query() \
689 689 .options(joinedload(PullRequestReviewers.pull_request)) \
690 690 .filter(PullRequestReviewers.user_id == self.user_id) \
691 691 .all()
692 692
693 693 @property
694 694 def firstname(self):
695 695 # alias for future
696 696 return self.name
697 697
698 698 @property
699 699 def emails(self):
700 700 other = UserEmailMap.query()\
701 701 .filter(UserEmailMap.user == self) \
702 702 .order_by(UserEmailMap.email_id.asc()) \
703 703 .all()
704 704 return [self.email] + [x.email for x in other]
705 705
706 706 def emails_cached(self):
707 707 emails = UserEmailMap.query()\
708 708 .filter(UserEmailMap.user == self) \
709 709 .order_by(UserEmailMap.email_id.asc())
710 710
711 711 emails = emails.options(
712 712 FromCache("sql_cache_short", "get_user_{}_emails".format(self.user_id))
713 713 )
714 714
715 715 return [self.email] + [x.email for x in emails]
716 716
717 717 @property
718 718 def auth_tokens(self):
719 719 auth_tokens = self.get_auth_tokens()
720 720 return [x.api_key for x in auth_tokens]
721 721
722 722 def get_auth_tokens(self):
723 723 return UserApiKeys.query()\
724 724 .filter(UserApiKeys.user == self)\
725 725 .order_by(UserApiKeys.user_api_key_id.asc())\
726 726 .all()
727 727
728 728 @LazyProperty
729 729 def feed_token(self):
730 730 return self.get_feed_token()
731 731
732 732 def get_feed_token(self, cache=True):
733 733 feed_tokens = UserApiKeys.query()\
734 734 .filter(UserApiKeys.user == self)\
735 735 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
736 736 if cache:
737 737 feed_tokens = feed_tokens.options(
738 738 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
739 739
740 740 feed_tokens = feed_tokens.all()
741 741 if feed_tokens:
742 742 return feed_tokens[0].api_key
743 743 return 'NO_FEED_TOKEN_AVAILABLE'
744 744
745 745 @LazyProperty
746 746 def artifact_token(self):
747 747 return self.get_artifact_token()
748 748
749 749 def get_artifact_token(self, cache=True):
750 750 artifacts_tokens = UserApiKeys.query()\
751 751 .filter(UserApiKeys.user == self) \
752 752 .filter(or_(UserApiKeys.expires == -1,
753 753 UserApiKeys.expires >= time.time())) \
754 754 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
755 755
756 756 if cache:
757 757 artifacts_tokens = artifacts_tokens.options(
758 758 FromCache("sql_cache_short", "get_user_artifact_token_%s" % self.user_id))
759 759
760 760 artifacts_tokens = artifacts_tokens.all()
761 761 if artifacts_tokens:
762 762 return artifacts_tokens[0].api_key
763 763 return 'NO_ARTIFACT_TOKEN_AVAILABLE'
764 764
765 765 def get_or_create_artifact_token(self):
766 766 artifacts_tokens = UserApiKeys.query()\
767 767 .filter(UserApiKeys.user == self) \
768 768 .filter(or_(UserApiKeys.expires == -1,
769 769 UserApiKeys.expires >= time.time())) \
770 770 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
771 771
772 772 artifacts_tokens = artifacts_tokens.all()
773 773 if artifacts_tokens:
774 774 return artifacts_tokens[0].api_key
775 775 else:
776 776 from rhodecode.model.auth_token import AuthTokenModel
777 777 artifact_token = AuthTokenModel().create(
778 778 self, 'auto-generated-artifact-token',
779 779 lifetime=-1, role=UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
780 780 Session.commit()
781 781 return artifact_token.api_key
782 782
783 783 @classmethod
784 784 def get(cls, user_id, cache=False):
785 785 if not user_id:
786 786 return
787 787
788 788 user = cls.query()
789 789 if cache:
790 790 user = user.options(
791 791 FromCache("sql_cache_short", "get_users_%s" % user_id))
792 792 return user.get(user_id)
793 793
794 794 @classmethod
795 795 def extra_valid_auth_tokens(cls, user, role=None):
796 796 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
797 797 .filter(or_(UserApiKeys.expires == -1,
798 798 UserApiKeys.expires >= time.time()))
799 799 if role:
800 800 tokens = tokens.filter(or_(UserApiKeys.role == role,
801 801 UserApiKeys.role == UserApiKeys.ROLE_ALL))
802 802 return tokens.all()
803 803
804 804 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
805 805 from rhodecode.lib import auth
806 806
807 807 log.debug('Trying to authenticate user: %s via auth-token, '
808 808 'and roles: %s', self, roles)
809 809
810 810 if not auth_token:
811 811 return False
812 812
813 813 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
814 814 tokens_q = UserApiKeys.query()\
815 815 .filter(UserApiKeys.user_id == self.user_id)\
816 816 .filter(or_(UserApiKeys.expires == -1,
817 817 UserApiKeys.expires >= time.time()))
818 818
819 819 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
820 820
821 821 crypto_backend = auth.crypto_backend()
822 822 enc_token_map = {}
823 823 plain_token_map = {}
824 824 for token in tokens_q:
825 825 if token.api_key.startswith(crypto_backend.ENC_PREF):
826 826 enc_token_map[token.api_key] = token
827 827 else:
828 828 plain_token_map[token.api_key] = token
829 829 log.debug(
830 830 'Found %s plain and %s encrypted tokens to check for authentication for this user',
831 831 len(plain_token_map), len(enc_token_map))
832 832
833 833 # plain token match comes first
834 834 match = plain_token_map.get(auth_token)
835 835
836 836 # check encrypted tokens now
837 837 if not match:
838 838 for token_hash, token in enc_token_map.items():
839 839 # NOTE(marcink): this is expensive to calculate, but most secure
840 840 if crypto_backend.hash_check(auth_token, token_hash):
841 841 match = token
842 842 break
843 843
844 844 if match:
845 845 log.debug('Found matching token %s', match)
846 846 if match.repo_id:
847 847 log.debug('Found scope, checking for scope match of token %s', match)
848 848 if match.repo_id == scope_repo_id:
849 849 return True
850 850 else:
851 851 log.debug(
852 852 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
853 853 'and calling scope is:%s, skipping further checks',
854 854 match.repo, scope_repo_id)
855 855 return False
856 856 else:
857 857 return True
858 858
859 859 return False
860 860
861 861 @property
862 862 def ip_addresses(self):
863 863 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
864 864 return [x.ip_addr for x in ret]
865 865
866 866 @property
867 867 def username_and_name(self):
868 868 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
869 869
870 870 @property
871 871 def username_or_name_or_email(self):
872 872 full_name = self.full_name if self.full_name is not ' ' else None
873 873 return self.username or full_name or self.email
874 874
875 875 @property
876 876 def full_name(self):
877 877 return '%s %s' % (self.first_name, self.last_name)
878 878
879 879 @property
880 880 def full_name_or_username(self):
881 881 return ('%s %s' % (self.first_name, self.last_name)
882 882 if (self.first_name and self.last_name) else self.username)
883 883
884 884 @property
885 885 def full_contact(self):
886 886 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
887 887
888 888 @property
889 889 def short_contact(self):
890 890 return '%s %s' % (self.first_name, self.last_name)
891 891
892 892 @property
893 893 def is_admin(self):
894 894 return self.admin
895 895
896 896 @property
897 897 def language(self):
898 898 return self.user_data.get('language')
899 899
900 900 def AuthUser(self, **kwargs):
901 901 """
902 902 Returns instance of AuthUser for this user
903 903 """
904 904 from rhodecode.lib.auth import AuthUser
905 905 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
906 906
907 907 @hybrid_property
908 908 def user_data(self):
909 909 if not self._user_data:
910 910 return {}
911 911
912 912 try:
913 913 return json.loads(self._user_data) or {}
914 914 except TypeError:
915 915 return {}
916 916
917 917 @user_data.setter
918 918 def user_data(self, val):
919 919 if not isinstance(val, dict):
920 920 raise Exception('user_data must be dict, got %s' % type(val))
921 921 try:
922 922 self._user_data = json.dumps(val)
923 923 except Exception:
924 924 log.error(traceback.format_exc())
925 925
926 926 @classmethod
927 927 def get_by_username(cls, username, case_insensitive=False,
928 928 cache=False, identity_cache=False):
929 929 session = Session()
930 930
931 931 if case_insensitive:
932 932 q = cls.query().filter(
933 933 func.lower(cls.username) == func.lower(username))
934 934 else:
935 935 q = cls.query().filter(cls.username == username)
936 936
937 937 if cache:
938 938 if identity_cache:
939 939 val = cls.identity_cache(session, 'username', username)
940 940 if val:
941 941 return val
942 942 else:
943 943 cache_key = "get_user_by_name_%s" % _hash_key(username)
944 944 q = q.options(
945 945 FromCache("sql_cache_short", cache_key))
946 946
947 947 return q.scalar()
948 948
949 949 @classmethod
950 950 def get_by_auth_token(cls, auth_token, cache=False):
951 951 q = UserApiKeys.query()\
952 952 .filter(UserApiKeys.api_key == auth_token)\
953 953 .filter(or_(UserApiKeys.expires == -1,
954 954 UserApiKeys.expires >= time.time()))
955 955 if cache:
956 956 q = q.options(
957 957 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
958 958
959 959 match = q.first()
960 960 if match:
961 961 return match.user
962 962
963 963 @classmethod
964 964 def get_by_email(cls, email, case_insensitive=False, cache=False):
965 965
966 966 if case_insensitive:
967 967 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
968 968
969 969 else:
970 970 q = cls.query().filter(cls.email == email)
971 971
972 972 email_key = _hash_key(email)
973 973 if cache:
974 974 q = q.options(
975 975 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
976 976
977 977 ret = q.scalar()
978 978 if ret is None:
979 979 q = UserEmailMap.query()
980 980 # try fetching in alternate email map
981 981 if case_insensitive:
982 982 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
983 983 else:
984 984 q = q.filter(UserEmailMap.email == email)
985 985 q = q.options(joinedload(UserEmailMap.user))
986 986 if cache:
987 987 q = q.options(
988 988 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
989 989 ret = getattr(q.scalar(), 'user', None)
990 990
991 991 return ret
992 992
993 993 @classmethod
994 994 def get_from_cs_author(cls, author):
995 995 """
996 996 Tries to get User objects out of commit author string
997 997
998 998 :param author:
999 999 """
1000 1000 from rhodecode.lib.helpers import email, author_name
1001 1001 # Valid email in the attribute passed, see if they're in the system
1002 1002 _email = email(author)
1003 1003 if _email:
1004 1004 user = cls.get_by_email(_email, case_insensitive=True)
1005 1005 if user:
1006 1006 return user
1007 1007 # Maybe we can match by username?
1008 1008 _author = author_name(author)
1009 1009 user = cls.get_by_username(_author, case_insensitive=True)
1010 1010 if user:
1011 1011 return user
1012 1012
1013 1013 def update_userdata(self, **kwargs):
1014 1014 usr = self
1015 1015 old = usr.user_data
1016 1016 old.update(**kwargs)
1017 1017 usr.user_data = old
1018 1018 Session().add(usr)
1019 1019 log.debug('updated userdata with %s', kwargs)
1020 1020
1021 1021 def update_lastlogin(self):
1022 1022 """Update user lastlogin"""
1023 1023 self.last_login = datetime.datetime.now()
1024 1024 Session().add(self)
1025 1025 log.debug('updated user %s lastlogin', self.username)
1026 1026
1027 1027 def update_password(self, new_password):
1028 1028 from rhodecode.lib.auth import get_crypt_password
1029 1029
1030 1030 self.password = get_crypt_password(new_password)
1031 1031 Session().add(self)
1032 1032
1033 1033 @classmethod
1034 1034 def get_first_super_admin(cls):
1035 1035 user = User.query()\
1036 1036 .filter(User.admin == true()) \
1037 1037 .order_by(User.user_id.asc()) \
1038 1038 .first()
1039 1039
1040 1040 if user is None:
1041 1041 raise Exception('FATAL: Missing administrative account!')
1042 1042 return user
1043 1043
1044 1044 @classmethod
1045 1045 def get_all_super_admins(cls, only_active=False):
1046 1046 """
1047 1047 Returns all admin accounts sorted by username
1048 1048 """
1049 1049 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
1050 1050 if only_active:
1051 1051 qry = qry.filter(User.active == true())
1052 1052 return qry.all()
1053 1053
1054 1054 @classmethod
1055 1055 def get_all_user_ids(cls, only_active=True):
1056 1056 """
1057 1057 Returns all users IDs
1058 1058 """
1059 1059 qry = Session().query(User.user_id)
1060 1060
1061 1061 if only_active:
1062 1062 qry = qry.filter(User.active == true())
1063 1063 return [x.user_id for x in qry]
1064 1064
1065 1065 @classmethod
1066 1066 def get_default_user(cls, cache=False, refresh=False):
1067 1067 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
1068 1068 if user is None:
1069 1069 raise Exception('FATAL: Missing default account!')
1070 1070 if refresh:
1071 1071 # The default user might be based on outdated state which
1072 1072 # has been loaded from the cache.
1073 1073 # A call to refresh() ensures that the
1074 1074 # latest state from the database is used.
1075 1075 Session().refresh(user)
1076 1076 return user
1077 1077
1078 1078 @classmethod
1079 1079 def get_default_user_id(cls):
1080 1080 import rhodecode
1081 1081 return rhodecode.CONFIG['default_user_id']
1082 1082
1083 1083 def _get_default_perms(self, user, suffix=''):
1084 1084 from rhodecode.model.permission import PermissionModel
1085 1085 return PermissionModel().get_default_perms(user.user_perms, suffix)
1086 1086
1087 1087 def get_default_perms(self, suffix=''):
1088 1088 return self._get_default_perms(self, suffix)
1089 1089
1090 1090 def get_api_data(self, include_secrets=False, details='full'):
1091 1091 """
1092 1092 Common function for generating user related data for API
1093 1093
1094 1094 :param include_secrets: By default secrets in the API data will be replaced
1095 1095 by a placeholder value to prevent exposing this data by accident. In case
1096 1096 this data shall be exposed, set this flag to ``True``.
1097 1097
1098 1098 :param details: details can be 'basic|full' basic gives only a subset of
1099 1099 the available user information that includes user_id, name and emails.
1100 1100 """
1101 1101 user = self
1102 1102 user_data = self.user_data
1103 1103 data = {
1104 1104 'user_id': user.user_id,
1105 1105 'username': user.username,
1106 1106 'firstname': user.name,
1107 1107 'lastname': user.lastname,
1108 1108 'description': user.description,
1109 1109 'email': user.email,
1110 1110 'emails': user.emails,
1111 1111 }
1112 1112 if details == 'basic':
1113 1113 return data
1114 1114
1115 1115 auth_token_length = 40
1116 1116 auth_token_replacement = '*' * auth_token_length
1117 1117
1118 1118 extras = {
1119 1119 'auth_tokens': [auth_token_replacement],
1120 1120 'active': user.active,
1121 1121 'admin': user.admin,
1122 1122 'extern_type': user.extern_type,
1123 1123 'extern_name': user.extern_name,
1124 1124 'last_login': user.last_login,
1125 1125 'last_activity': user.last_activity,
1126 1126 'ip_addresses': user.ip_addresses,
1127 1127 'language': user_data.get('language')
1128 1128 }
1129 1129 data.update(extras)
1130 1130
1131 1131 if include_secrets:
1132 1132 data['auth_tokens'] = user.auth_tokens
1133 1133 return data
1134 1134
1135 1135 def __json__(self):
1136 1136 data = {
1137 1137 'full_name': self.full_name,
1138 1138 'full_name_or_username': self.full_name_or_username,
1139 1139 'short_contact': self.short_contact,
1140 1140 'full_contact': self.full_contact,
1141 1141 }
1142 1142 data.update(self.get_api_data())
1143 1143 return data
1144 1144
1145 1145
1146 1146 class UserApiKeys(Base, BaseModel):
1147 1147 __tablename__ = 'user_api_keys'
1148 1148 __table_args__ = (
1149 1149 Index('uak_api_key_idx', 'api_key'),
1150 1150 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1151 1151 base_table_args
1152 1152 )
1153 1153 __mapper_args__ = {}
1154 1154
1155 1155 # ApiKey role
1156 1156 ROLE_ALL = 'token_role_all'
1157 1157 ROLE_VCS = 'token_role_vcs'
1158 1158 ROLE_API = 'token_role_api'
1159 1159 ROLE_HTTP = 'token_role_http'
1160 1160 ROLE_FEED = 'token_role_feed'
1161 1161 ROLE_ARTIFACT_DOWNLOAD = 'role_artifact_download'
1162 1162 # The last one is ignored in the list as we only
1163 1163 # use it for one action, and cannot be created by users
1164 1164 ROLE_PASSWORD_RESET = 'token_password_reset'
1165 1165
1166 1166 ROLES = [ROLE_ALL, ROLE_VCS, ROLE_API, ROLE_HTTP, ROLE_FEED, ROLE_ARTIFACT_DOWNLOAD]
1167 1167
1168 1168 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1169 1169 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1170 1170 api_key = Column("api_key", String(255), nullable=False, unique=True)
1171 1171 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1172 1172 expires = Column('expires', Float(53), nullable=False)
1173 1173 role = Column('role', String(255), nullable=True)
1174 1174 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1175 1175
1176 1176 # scope columns
1177 1177 repo_id = Column(
1178 1178 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1179 1179 nullable=True, unique=None, default=None)
1180 1180 repo = relationship('Repository', lazy='joined')
1181 1181
1182 1182 repo_group_id = Column(
1183 1183 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1184 1184 nullable=True, unique=None, default=None)
1185 1185 repo_group = relationship('RepoGroup', lazy='joined')
1186 1186
1187 1187 user = relationship('User', lazy='joined')
1188 1188
1189 1189 def __unicode__(self):
1190 1190 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1191 1191
1192 1192 def __json__(self):
1193 1193 data = {
1194 1194 'auth_token': self.api_key,
1195 1195 'role': self.role,
1196 1196 'scope': self.scope_humanized,
1197 1197 'expired': self.expired
1198 1198 }
1199 1199 return data
1200 1200
1201 1201 def get_api_data(self, include_secrets=False):
1202 1202 data = self.__json__()
1203 1203 if include_secrets:
1204 1204 return data
1205 1205 else:
1206 1206 data['auth_token'] = self.token_obfuscated
1207 1207 return data
1208 1208
1209 1209 @hybrid_property
1210 1210 def description_safe(self):
1211 1211 from rhodecode.lib import helpers as h
1212 1212 return h.escape(self.description)
1213 1213
1214 1214 @property
1215 1215 def expired(self):
1216 1216 if self.expires == -1:
1217 1217 return False
1218 1218 return time.time() > self.expires
1219 1219
1220 1220 @classmethod
1221 1221 def _get_role_name(cls, role):
1222 1222 return {
1223 1223 cls.ROLE_ALL: _('all'),
1224 1224 cls.ROLE_HTTP: _('http/web interface'),
1225 1225 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1226 1226 cls.ROLE_API: _('api calls'),
1227 1227 cls.ROLE_FEED: _('feed access'),
1228 1228 cls.ROLE_ARTIFACT_DOWNLOAD: _('artifacts downloads'),
1229 1229 }.get(role, role)
1230 1230
1231 1231 @classmethod
1232 1232 def _get_role_description(cls, role):
1233 1233 return {
1234 1234 cls.ROLE_ALL: _('Token for all actions.'),
1235 1235 cls.ROLE_HTTP: _('Token to access RhodeCode pages via web interface without '
1236 1236 'login using `api_access_controllers_whitelist` functionality.'),
1237 1237 cls.ROLE_VCS: _('Token to interact over git/hg/svn protocols. '
1238 1238 'Requires auth_token authentication plugin to be active. <br/>'
1239 1239 'Such Token should be used then instead of a password to '
1240 1240 'interact with a repository, and additionally can be '
1241 1241 'limited to single repository using repo scope.'),
1242 1242 cls.ROLE_API: _('Token limited to api calls.'),
1243 1243 cls.ROLE_FEED: _('Token to read RSS/ATOM feed.'),
1244 1244 cls.ROLE_ARTIFACT_DOWNLOAD: _('Token for artifacts downloads.'),
1245 1245 }.get(role, role)
1246 1246
1247 1247 @property
1248 1248 def role_humanized(self):
1249 1249 return self._get_role_name(self.role)
1250 1250
1251 1251 def _get_scope(self):
1252 1252 if self.repo:
1253 1253 return 'Repository: {}'.format(self.repo.repo_name)
1254 1254 if self.repo_group:
1255 1255 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1256 1256 return 'Global'
1257 1257
1258 1258 @property
1259 1259 def scope_humanized(self):
1260 1260 return self._get_scope()
1261 1261
1262 1262 @property
1263 1263 def token_obfuscated(self):
1264 1264 if self.api_key:
1265 1265 return self.api_key[:4] + "****"
1266 1266
1267 1267
1268 1268 class UserEmailMap(Base, BaseModel):
1269 1269 __tablename__ = 'user_email_map'
1270 1270 __table_args__ = (
1271 1271 Index('uem_email_idx', 'email'),
1272 1272 UniqueConstraint('email'),
1273 1273 base_table_args
1274 1274 )
1275 1275 __mapper_args__ = {}
1276 1276
1277 1277 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1278 1278 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1279 1279 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1280 1280 user = relationship('User', lazy='joined')
1281 1281
1282 1282 @validates('_email')
1283 1283 def validate_email(self, key, email):
1284 1284 # check if this email is not main one
1285 1285 main_email = Session().query(User).filter(User.email == email).scalar()
1286 1286 if main_email is not None:
1287 1287 raise AttributeError('email %s is present is user table' % email)
1288 1288 return email
1289 1289
1290 1290 @hybrid_property
1291 1291 def email(self):
1292 1292 return self._email
1293 1293
1294 1294 @email.setter
1295 1295 def email(self, val):
1296 1296 self._email = val.lower() if val else None
1297 1297
1298 1298
1299 1299 class UserIpMap(Base, BaseModel):
1300 1300 __tablename__ = 'user_ip_map'
1301 1301 __table_args__ = (
1302 1302 UniqueConstraint('user_id', 'ip_addr'),
1303 1303 base_table_args
1304 1304 )
1305 1305 __mapper_args__ = {}
1306 1306
1307 1307 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1308 1308 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1309 1309 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1310 1310 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1311 1311 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1312 1312 user = relationship('User', lazy='joined')
1313 1313
1314 1314 @hybrid_property
1315 1315 def description_safe(self):
1316 1316 from rhodecode.lib import helpers as h
1317 1317 return h.escape(self.description)
1318 1318
1319 1319 @classmethod
1320 1320 def _get_ip_range(cls, ip_addr):
1321 1321 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1322 1322 return [str(net.network_address), str(net.broadcast_address)]
1323 1323
1324 1324 def __json__(self):
1325 1325 return {
1326 1326 'ip_addr': self.ip_addr,
1327 1327 'ip_range': self._get_ip_range(self.ip_addr),
1328 1328 }
1329 1329
1330 1330 def __unicode__(self):
1331 1331 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1332 1332 self.user_id, self.ip_addr)
1333 1333
1334 1334
1335 1335 class UserSshKeys(Base, BaseModel):
1336 1336 __tablename__ = 'user_ssh_keys'
1337 1337 __table_args__ = (
1338 1338 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1339 1339
1340 1340 UniqueConstraint('ssh_key_fingerprint'),
1341 1341
1342 1342 base_table_args
1343 1343 )
1344 1344 __mapper_args__ = {}
1345 1345
1346 1346 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1347 1347 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1348 1348 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1349 1349
1350 1350 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1351 1351
1352 1352 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1353 1353 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1354 1354 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1355 1355
1356 1356 user = relationship('User', lazy='joined')
1357 1357
1358 1358 def __json__(self):
1359 1359 data = {
1360 1360 'ssh_fingerprint': self.ssh_key_fingerprint,
1361 1361 'description': self.description,
1362 1362 'created_on': self.created_on
1363 1363 }
1364 1364 return data
1365 1365
1366 1366 def get_api_data(self):
1367 1367 data = self.__json__()
1368 1368 return data
1369 1369
1370 1370
1371 1371 class UserLog(Base, BaseModel):
1372 1372 __tablename__ = 'user_logs'
1373 1373 __table_args__ = (
1374 1374 base_table_args,
1375 1375 )
1376 1376
1377 1377 VERSION_1 = 'v1'
1378 1378 VERSION_2 = 'v2'
1379 1379 VERSIONS = [VERSION_1, VERSION_2]
1380 1380
1381 1381 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1382 1382 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1383 1383 username = Column("username", String(255), nullable=True, unique=None, default=None)
1384 1384 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1385 1385 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1386 1386 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1387 1387 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1388 1388 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1389 1389
1390 1390 version = Column("version", String(255), nullable=True, default=VERSION_1)
1391 1391 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1392 1392 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1393 1393
1394 1394 def __unicode__(self):
1395 1395 return u"<%s('id:%s:%s')>" % (
1396 1396 self.__class__.__name__, self.repository_name, self.action)
1397 1397
1398 1398 def __json__(self):
1399 1399 return {
1400 1400 'user_id': self.user_id,
1401 1401 'username': self.username,
1402 1402 'repository_id': self.repository_id,
1403 1403 'repository_name': self.repository_name,
1404 1404 'user_ip': self.user_ip,
1405 1405 'action_date': self.action_date,
1406 1406 'action': self.action,
1407 1407 }
1408 1408
1409 1409 @hybrid_property
1410 1410 def entry_id(self):
1411 1411 return self.user_log_id
1412 1412
1413 1413 @property
1414 1414 def action_as_day(self):
1415 1415 return datetime.date(*self.action_date.timetuple()[:3])
1416 1416
1417 1417 user = relationship('User')
1418 1418 repository = relationship('Repository', cascade='')
1419 1419
1420 1420
1421 1421 class UserGroup(Base, BaseModel):
1422 1422 __tablename__ = 'users_groups'
1423 1423 __table_args__ = (
1424 1424 base_table_args,
1425 1425 )
1426 1426
1427 1427 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1428 1428 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1429 1429 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1430 1430 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1431 1431 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1432 1432 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1433 1433 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1434 1434 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1435 1435
1436 1436 members = relationship('UserGroupMember', cascade="all, delete-orphan", lazy="joined")
1437 1437 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1438 1438 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1439 1439 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1440 1440 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1441 1441 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1442 1442
1443 1443 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1444 1444 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1445 1445
1446 1446 @classmethod
1447 1447 def _load_group_data(cls, column):
1448 1448 if not column:
1449 1449 return {}
1450 1450
1451 1451 try:
1452 1452 return json.loads(column) or {}
1453 1453 except TypeError:
1454 1454 return {}
1455 1455
1456 1456 @hybrid_property
1457 1457 def description_safe(self):
1458 1458 from rhodecode.lib import helpers as h
1459 1459 return h.escape(self.user_group_description)
1460 1460
1461 1461 @hybrid_property
1462 1462 def group_data(self):
1463 1463 return self._load_group_data(self._group_data)
1464 1464
1465 1465 @group_data.expression
1466 1466 def group_data(self, **kwargs):
1467 1467 return self._group_data
1468 1468
1469 1469 @group_data.setter
1470 1470 def group_data(self, val):
1471 1471 try:
1472 1472 self._group_data = json.dumps(val)
1473 1473 except Exception:
1474 1474 log.error(traceback.format_exc())
1475 1475
1476 1476 @classmethod
1477 1477 def _load_sync(cls, group_data):
1478 1478 if group_data:
1479 1479 return group_data.get('extern_type')
1480 1480
1481 1481 @property
1482 1482 def sync(self):
1483 1483 return self._load_sync(self.group_data)
1484 1484
1485 1485 def __unicode__(self):
1486 1486 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1487 1487 self.users_group_id,
1488 1488 self.users_group_name)
1489 1489
1490 1490 @classmethod
1491 1491 def get_by_group_name(cls, group_name, cache=False,
1492 1492 case_insensitive=False):
1493 1493 if case_insensitive:
1494 1494 q = cls.query().filter(func.lower(cls.users_group_name) ==
1495 1495 func.lower(group_name))
1496 1496
1497 1497 else:
1498 1498 q = cls.query().filter(cls.users_group_name == group_name)
1499 1499 if cache:
1500 1500 q = q.options(
1501 1501 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1502 1502 return q.scalar()
1503 1503
1504 1504 @classmethod
1505 1505 def get(cls, user_group_id, cache=False):
1506 1506 if not user_group_id:
1507 1507 return
1508 1508
1509 1509 user_group = cls.query()
1510 1510 if cache:
1511 1511 user_group = user_group.options(
1512 1512 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1513 1513 return user_group.get(user_group_id)
1514 1514
1515 1515 def permissions(self, with_admins=True, with_owner=True,
1516 1516 expand_from_user_groups=False):
1517 1517 """
1518 1518 Permissions for user groups
1519 1519 """
1520 1520 _admin_perm = 'usergroup.admin'
1521 1521
1522 1522 owner_row = []
1523 1523 if with_owner:
1524 1524 usr = AttributeDict(self.user.get_dict())
1525 1525 usr.owner_row = True
1526 1526 usr.permission = _admin_perm
1527 1527 owner_row.append(usr)
1528 1528
1529 1529 super_admin_ids = []
1530 1530 super_admin_rows = []
1531 1531 if with_admins:
1532 1532 for usr in User.get_all_super_admins():
1533 1533 super_admin_ids.append(usr.user_id)
1534 1534 # if this admin is also owner, don't double the record
1535 1535 if usr.user_id == owner_row[0].user_id:
1536 1536 owner_row[0].admin_row = True
1537 1537 else:
1538 1538 usr = AttributeDict(usr.get_dict())
1539 1539 usr.admin_row = True
1540 1540 usr.permission = _admin_perm
1541 1541 super_admin_rows.append(usr)
1542 1542
1543 1543 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1544 1544 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1545 1545 joinedload(UserUserGroupToPerm.user),
1546 1546 joinedload(UserUserGroupToPerm.permission),)
1547 1547
1548 1548 # get owners and admins and permissions. We do a trick of re-writing
1549 1549 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1550 1550 # has a global reference and changing one object propagates to all
1551 1551 # others. This means if admin is also an owner admin_row that change
1552 1552 # would propagate to both objects
1553 1553 perm_rows = []
1554 1554 for _usr in q.all():
1555 1555 usr = AttributeDict(_usr.user.get_dict())
1556 1556 # if this user is also owner/admin, mark as duplicate record
1557 1557 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1558 1558 usr.duplicate_perm = True
1559 1559 usr.permission = _usr.permission.permission_name
1560 1560 perm_rows.append(usr)
1561 1561
1562 1562 # filter the perm rows by 'default' first and then sort them by
1563 1563 # admin,write,read,none permissions sorted again alphabetically in
1564 1564 # each group
1565 1565 perm_rows = sorted(perm_rows, key=display_user_sort)
1566 1566
1567 1567 user_groups_rows = []
1568 1568 if expand_from_user_groups:
1569 1569 for ug in self.permission_user_groups(with_members=True):
1570 1570 for user_data in ug.members:
1571 1571 user_groups_rows.append(user_data)
1572 1572
1573 1573 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1574 1574
1575 1575 def permission_user_groups(self, with_members=False):
1576 1576 q = UserGroupUserGroupToPerm.query()\
1577 1577 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1578 1578 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1579 1579 joinedload(UserGroupUserGroupToPerm.target_user_group),
1580 1580 joinedload(UserGroupUserGroupToPerm.permission),)
1581 1581
1582 1582 perm_rows = []
1583 1583 for _user_group in q.all():
1584 1584 entry = AttributeDict(_user_group.user_group.get_dict())
1585 1585 entry.permission = _user_group.permission.permission_name
1586 1586 if with_members:
1587 1587 entry.members = [x.user.get_dict()
1588 1588 for x in _user_group.user_group.members]
1589 1589 perm_rows.append(entry)
1590 1590
1591 1591 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1592 1592 return perm_rows
1593 1593
1594 1594 def _get_default_perms(self, user_group, suffix=''):
1595 1595 from rhodecode.model.permission import PermissionModel
1596 1596 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1597 1597
1598 1598 def get_default_perms(self, suffix=''):
1599 1599 return self._get_default_perms(self, suffix)
1600 1600
1601 1601 def get_api_data(self, with_group_members=True, include_secrets=False):
1602 1602 """
1603 1603 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1604 1604 basically forwarded.
1605 1605
1606 1606 """
1607 1607 user_group = self
1608 1608 data = {
1609 1609 'users_group_id': user_group.users_group_id,
1610 1610 'group_name': user_group.users_group_name,
1611 1611 'group_description': user_group.user_group_description,
1612 1612 'active': user_group.users_group_active,
1613 1613 'owner': user_group.user.username,
1614 1614 'sync': user_group.sync,
1615 1615 'owner_email': user_group.user.email,
1616 1616 }
1617 1617
1618 1618 if with_group_members:
1619 1619 users = []
1620 1620 for user in user_group.members:
1621 1621 user = user.user
1622 1622 users.append(user.get_api_data(include_secrets=include_secrets))
1623 1623 data['users'] = users
1624 1624
1625 1625 return data
1626 1626
1627 1627
1628 1628 class UserGroupMember(Base, BaseModel):
1629 1629 __tablename__ = 'users_groups_members'
1630 1630 __table_args__ = (
1631 1631 base_table_args,
1632 1632 )
1633 1633
1634 1634 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1635 1635 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1636 1636 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1637 1637
1638 1638 user = relationship('User', lazy='joined')
1639 1639 users_group = relationship('UserGroup')
1640 1640
1641 1641 def __init__(self, gr_id='', u_id=''):
1642 1642 self.users_group_id = gr_id
1643 1643 self.user_id = u_id
1644 1644
1645 1645
1646 1646 class RepositoryField(Base, BaseModel):
1647 1647 __tablename__ = 'repositories_fields'
1648 1648 __table_args__ = (
1649 1649 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1650 1650 base_table_args,
1651 1651 )
1652 1652
1653 1653 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1654 1654
1655 1655 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1656 1656 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1657 1657 field_key = Column("field_key", String(250))
1658 1658 field_label = Column("field_label", String(1024), nullable=False)
1659 1659 field_value = Column("field_value", String(10000), nullable=False)
1660 1660 field_desc = Column("field_desc", String(1024), nullable=False)
1661 1661 field_type = Column("field_type", String(255), nullable=False, unique=None)
1662 1662 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1663 1663
1664 1664 repository = relationship('Repository')
1665 1665
1666 1666 @property
1667 1667 def field_key_prefixed(self):
1668 1668 return 'ex_%s' % self.field_key
1669 1669
1670 1670 @classmethod
1671 1671 def un_prefix_key(cls, key):
1672 1672 if key.startswith(cls.PREFIX):
1673 1673 return key[len(cls.PREFIX):]
1674 1674 return key
1675 1675
1676 1676 @classmethod
1677 1677 def get_by_key_name(cls, key, repo):
1678 1678 row = cls.query()\
1679 1679 .filter(cls.repository == repo)\
1680 1680 .filter(cls.field_key == key).scalar()
1681 1681 return row
1682 1682
1683 1683
1684 1684 class Repository(Base, BaseModel):
1685 1685 __tablename__ = 'repositories'
1686 1686 __table_args__ = (
1687 1687 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1688 1688 base_table_args,
1689 1689 )
1690 1690 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1691 1691 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1692 1692 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1693 1693
1694 1694 STATE_CREATED = 'repo_state_created'
1695 1695 STATE_PENDING = 'repo_state_pending'
1696 1696 STATE_ERROR = 'repo_state_error'
1697 1697
1698 1698 LOCK_AUTOMATIC = 'lock_auto'
1699 1699 LOCK_API = 'lock_api'
1700 1700 LOCK_WEB = 'lock_web'
1701 1701 LOCK_PULL = 'lock_pull'
1702 1702
1703 1703 NAME_SEP = URL_SEP
1704 1704
1705 1705 repo_id = Column(
1706 1706 "repo_id", Integer(), nullable=False, unique=True, default=None,
1707 1707 primary_key=True)
1708 1708 _repo_name = Column(
1709 1709 "repo_name", Text(), nullable=False, default=None)
1710 1710 repo_name_hash = Column(
1711 1711 "repo_name_hash", String(255), nullable=False, unique=True)
1712 1712 repo_state = Column("repo_state", String(255), nullable=True)
1713 1713
1714 1714 clone_uri = Column(
1715 1715 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1716 1716 default=None)
1717 1717 push_uri = Column(
1718 1718 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1719 1719 default=None)
1720 1720 repo_type = Column(
1721 1721 "repo_type", String(255), nullable=False, unique=False, default=None)
1722 1722 user_id = Column(
1723 1723 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1724 1724 unique=False, default=None)
1725 1725 private = Column(
1726 1726 "private", Boolean(), nullable=True, unique=None, default=None)
1727 1727 archived = Column(
1728 1728 "archived", Boolean(), nullable=True, unique=None, default=None)
1729 1729 enable_statistics = Column(
1730 1730 "statistics", Boolean(), nullable=True, unique=None, default=True)
1731 1731 enable_downloads = Column(
1732 1732 "downloads", Boolean(), nullable=True, unique=None, default=True)
1733 1733 description = Column(
1734 1734 "description", String(10000), nullable=True, unique=None, default=None)
1735 1735 created_on = Column(
1736 1736 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1737 1737 default=datetime.datetime.now)
1738 1738 updated_on = Column(
1739 1739 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1740 1740 default=datetime.datetime.now)
1741 1741 _landing_revision = Column(
1742 1742 "landing_revision", String(255), nullable=False, unique=False,
1743 1743 default=None)
1744 1744 enable_locking = Column(
1745 1745 "enable_locking", Boolean(), nullable=False, unique=None,
1746 1746 default=False)
1747 1747 _locked = Column(
1748 1748 "locked", String(255), nullable=True, unique=False, default=None)
1749 1749 _changeset_cache = Column(
1750 1750 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1751 1751
1752 1752 fork_id = Column(
1753 1753 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1754 1754 nullable=True, unique=False, default=None)
1755 1755 group_id = Column(
1756 1756 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1757 1757 unique=False, default=None)
1758 1758
1759 1759 user = relationship('User', lazy='joined')
1760 1760 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1761 1761 group = relationship('RepoGroup', lazy='joined')
1762 1762 repo_to_perm = relationship(
1763 1763 'UserRepoToPerm', cascade='all',
1764 1764 order_by='UserRepoToPerm.repo_to_perm_id')
1765 1765 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1766 1766 stats = relationship('Statistics', cascade='all', uselist=False)
1767 1767
1768 1768 followers = relationship(
1769 1769 'UserFollowing',
1770 1770 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1771 1771 cascade='all')
1772 1772 extra_fields = relationship(
1773 1773 'RepositoryField', cascade="all, delete-orphan")
1774 1774 logs = relationship('UserLog')
1775 1775 comments = relationship(
1776 1776 'ChangesetComment', cascade="all, delete-orphan")
1777 1777 pull_requests_source = relationship(
1778 1778 'PullRequest',
1779 1779 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1780 1780 cascade="all, delete-orphan")
1781 1781 pull_requests_target = relationship(
1782 1782 'PullRequest',
1783 1783 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1784 1784 cascade="all, delete-orphan")
1785 1785 ui = relationship('RepoRhodeCodeUi', cascade="all")
1786 1786 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1787 1787 integrations = relationship('Integration', cascade="all, delete-orphan")
1788 1788
1789 1789 scoped_tokens = relationship('UserApiKeys', cascade="all")
1790 1790
1791 1791 # no cascade, set NULL
1792 1792 artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_id==Repository.repo_id')
1793 1793
1794 1794 def __unicode__(self):
1795 1795 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1796 1796 safe_unicode(self.repo_name))
1797 1797
1798 1798 @hybrid_property
1799 1799 def description_safe(self):
1800 1800 from rhodecode.lib import helpers as h
1801 1801 return h.escape(self.description)
1802 1802
1803 1803 @hybrid_property
1804 1804 def landing_rev(self):
1805 1805 # always should return [rev_type, rev], e.g ['branch', 'master']
1806 1806 if self._landing_revision:
1807 1807 _rev_info = self._landing_revision.split(':')
1808 1808 if len(_rev_info) < 2:
1809 1809 _rev_info.insert(0, 'rev')
1810 1810 return [_rev_info[0], _rev_info[1]]
1811 1811 return [None, None]
1812 1812
1813 1813 @property
1814 1814 def landing_ref_type(self):
1815 1815 return self.landing_rev[0]
1816 1816
1817 1817 @property
1818 1818 def landing_ref_name(self):
1819 1819 return self.landing_rev[1]
1820 1820
1821 1821 @landing_rev.setter
1822 1822 def landing_rev(self, val):
1823 1823 if ':' not in val:
1824 1824 raise ValueError('value must be delimited with `:` and consist '
1825 1825 'of <rev_type>:<rev>, got %s instead' % val)
1826 1826 self._landing_revision = val
1827 1827
1828 1828 @hybrid_property
1829 1829 def locked(self):
1830 1830 if self._locked:
1831 1831 user_id, timelocked, reason = self._locked.split(':')
1832 1832 lock_values = int(user_id), timelocked, reason
1833 1833 else:
1834 1834 lock_values = [None, None, None]
1835 1835 return lock_values
1836 1836
1837 1837 @locked.setter
1838 1838 def locked(self, val):
1839 1839 if val and isinstance(val, (list, tuple)):
1840 1840 self._locked = ':'.join(map(str, val))
1841 1841 else:
1842 1842 self._locked = None
1843 1843
1844 1844 @classmethod
1845 1845 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
1846 1846 from rhodecode.lib.vcs.backends.base import EmptyCommit
1847 1847 dummy = EmptyCommit().__json__()
1848 1848 if not changeset_cache_raw:
1849 1849 dummy['source_repo_id'] = repo_id
1850 1850 return json.loads(json.dumps(dummy))
1851 1851
1852 1852 try:
1853 1853 return json.loads(changeset_cache_raw)
1854 1854 except TypeError:
1855 1855 return dummy
1856 1856 except Exception:
1857 1857 log.error(traceback.format_exc())
1858 1858 return dummy
1859 1859
1860 1860 @hybrid_property
1861 1861 def changeset_cache(self):
1862 1862 return self._load_changeset_cache(self.repo_id, self._changeset_cache)
1863 1863
1864 1864 @changeset_cache.setter
1865 1865 def changeset_cache(self, val):
1866 1866 try:
1867 1867 self._changeset_cache = json.dumps(val)
1868 1868 except Exception:
1869 1869 log.error(traceback.format_exc())
1870 1870
1871 1871 @hybrid_property
1872 1872 def repo_name(self):
1873 1873 return self._repo_name
1874 1874
1875 1875 @repo_name.setter
1876 1876 def repo_name(self, value):
1877 1877 self._repo_name = value
1878 1878 self.repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1879 1879
1880 1880 @classmethod
1881 1881 def normalize_repo_name(cls, repo_name):
1882 1882 """
1883 1883 Normalizes os specific repo_name to the format internally stored inside
1884 1884 database using URL_SEP
1885 1885
1886 1886 :param cls:
1887 1887 :param repo_name:
1888 1888 """
1889 1889 return cls.NAME_SEP.join(repo_name.split(os.sep))
1890 1890
1891 1891 @classmethod
1892 1892 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1893 1893 session = Session()
1894 1894 q = session.query(cls).filter(cls.repo_name == repo_name)
1895 1895
1896 1896 if cache:
1897 1897 if identity_cache:
1898 1898 val = cls.identity_cache(session, 'repo_name', repo_name)
1899 1899 if val:
1900 1900 return val
1901 1901 else:
1902 1902 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1903 1903 q = q.options(
1904 1904 FromCache("sql_cache_short", cache_key))
1905 1905
1906 1906 return q.scalar()
1907 1907
1908 1908 @classmethod
1909 1909 def get_by_id_or_repo_name(cls, repoid):
1910 if isinstance(repoid, (int, long)):
1910 if isinstance(repoid, int):
1911 1911 try:
1912 1912 repo = cls.get(repoid)
1913 1913 except ValueError:
1914 1914 repo = None
1915 1915 else:
1916 1916 repo = cls.get_by_repo_name(repoid)
1917 1917 return repo
1918 1918
1919 1919 @classmethod
1920 1920 def get_by_full_path(cls, repo_full_path):
1921 1921 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1922 1922 repo_name = cls.normalize_repo_name(repo_name)
1923 1923 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1924 1924
1925 1925 @classmethod
1926 1926 def get_repo_forks(cls, repo_id):
1927 1927 return cls.query().filter(Repository.fork_id == repo_id)
1928 1928
1929 1929 @classmethod
1930 1930 def base_path(cls):
1931 1931 """
1932 1932 Returns base path when all repos are stored
1933 1933
1934 1934 :param cls:
1935 1935 """
1936 1936 q = Session().query(RhodeCodeUi)\
1937 1937 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1938 1938 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1939 1939 return q.one().ui_value
1940 1940
1941 1941 @classmethod
1942 1942 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1943 1943 case_insensitive=True, archived=False):
1944 1944 q = Repository.query()
1945 1945
1946 1946 if not archived:
1947 1947 q = q.filter(Repository.archived.isnot(true()))
1948 1948
1949 1949 if not isinstance(user_id, Optional):
1950 1950 q = q.filter(Repository.user_id == user_id)
1951 1951
1952 1952 if not isinstance(group_id, Optional):
1953 1953 q = q.filter(Repository.group_id == group_id)
1954 1954
1955 1955 if case_insensitive:
1956 1956 q = q.order_by(func.lower(Repository.repo_name))
1957 1957 else:
1958 1958 q = q.order_by(Repository.repo_name)
1959 1959
1960 1960 return q.all()
1961 1961
1962 1962 @property
1963 1963 def repo_uid(self):
1964 1964 return '_{}'.format(self.repo_id)
1965 1965
1966 1966 @property
1967 1967 def forks(self):
1968 1968 """
1969 1969 Return forks of this repo
1970 1970 """
1971 1971 return Repository.get_repo_forks(self.repo_id)
1972 1972
1973 1973 @property
1974 1974 def parent(self):
1975 1975 """
1976 1976 Returns fork parent
1977 1977 """
1978 1978 return self.fork
1979 1979
1980 1980 @property
1981 1981 def just_name(self):
1982 1982 return self.repo_name.split(self.NAME_SEP)[-1]
1983 1983
1984 1984 @property
1985 1985 def groups_with_parents(self):
1986 1986 groups = []
1987 1987 if self.group is None:
1988 1988 return groups
1989 1989
1990 1990 cur_gr = self.group
1991 1991 groups.insert(0, cur_gr)
1992 1992 while 1:
1993 1993 gr = getattr(cur_gr, 'parent_group', None)
1994 1994 cur_gr = cur_gr.parent_group
1995 1995 if gr is None:
1996 1996 break
1997 1997 groups.insert(0, gr)
1998 1998
1999 1999 return groups
2000 2000
2001 2001 @property
2002 2002 def groups_and_repo(self):
2003 2003 return self.groups_with_parents, self
2004 2004
2005 2005 @LazyProperty
2006 2006 def repo_path(self):
2007 2007 """
2008 2008 Returns base full path for that repository means where it actually
2009 2009 exists on a filesystem
2010 2010 """
2011 2011 q = Session().query(RhodeCodeUi).filter(
2012 2012 RhodeCodeUi.ui_key == self.NAME_SEP)
2013 2013 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
2014 2014 return q.one().ui_value
2015 2015
2016 2016 @property
2017 2017 def repo_full_path(self):
2018 2018 p = [self.repo_path]
2019 2019 # we need to split the name by / since this is how we store the
2020 2020 # names in the database, but that eventually needs to be converted
2021 2021 # into a valid system path
2022 2022 p += self.repo_name.split(self.NAME_SEP)
2023 2023 return os.path.join(*map(safe_unicode, p))
2024 2024
2025 2025 @property
2026 2026 def cache_keys(self):
2027 2027 """
2028 2028 Returns associated cache keys for that repo
2029 2029 """
2030 2030 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2031 2031 repo_id=self.repo_id)
2032 2032 return CacheKey.query()\
2033 2033 .filter(CacheKey.cache_args == invalidation_namespace)\
2034 2034 .order_by(CacheKey.cache_key)\
2035 2035 .all()
2036 2036
2037 2037 @property
2038 2038 def cached_diffs_relative_dir(self):
2039 2039 """
2040 2040 Return a relative to the repository store path of cached diffs
2041 2041 used for safe display for users, who shouldn't know the absolute store
2042 2042 path
2043 2043 """
2044 2044 return os.path.join(
2045 2045 os.path.dirname(self.repo_name),
2046 2046 self.cached_diffs_dir.split(os.path.sep)[-1])
2047 2047
2048 2048 @property
2049 2049 def cached_diffs_dir(self):
2050 2050 path = self.repo_full_path
2051 2051 return os.path.join(
2052 2052 os.path.dirname(path),
2053 2053 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
2054 2054
2055 2055 def cached_diffs(self):
2056 2056 diff_cache_dir = self.cached_diffs_dir
2057 2057 if os.path.isdir(diff_cache_dir):
2058 2058 return os.listdir(diff_cache_dir)
2059 2059 return []
2060 2060
2061 2061 def shadow_repos(self):
2062 2062 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
2063 2063 return [
2064 2064 x for x in os.listdir(os.path.dirname(self.repo_full_path))
2065 2065 if x.startswith(shadow_repos_pattern)]
2066 2066
2067 2067 def get_new_name(self, repo_name):
2068 2068 """
2069 2069 returns new full repository name based on assigned group and new new
2070 2070
2071 2071 :param group_name:
2072 2072 """
2073 2073 path_prefix = self.group.full_path_splitted if self.group else []
2074 2074 return self.NAME_SEP.join(path_prefix + [repo_name])
2075 2075
2076 2076 @property
2077 2077 def _config(self):
2078 2078 """
2079 2079 Returns db based config object.
2080 2080 """
2081 2081 from rhodecode.lib.utils import make_db_config
2082 2082 return make_db_config(clear_session=False, repo=self)
2083 2083
2084 2084 def permissions(self, with_admins=True, with_owner=True,
2085 2085 expand_from_user_groups=False):
2086 2086 """
2087 2087 Permissions for repositories
2088 2088 """
2089 2089 _admin_perm = 'repository.admin'
2090 2090
2091 2091 owner_row = []
2092 2092 if with_owner:
2093 2093 usr = AttributeDict(self.user.get_dict())
2094 2094 usr.owner_row = True
2095 2095 usr.permission = _admin_perm
2096 2096 usr.permission_id = None
2097 2097 owner_row.append(usr)
2098 2098
2099 2099 super_admin_ids = []
2100 2100 super_admin_rows = []
2101 2101 if with_admins:
2102 2102 for usr in User.get_all_super_admins():
2103 2103 super_admin_ids.append(usr.user_id)
2104 2104 # if this admin is also owner, don't double the record
2105 2105 if usr.user_id == owner_row[0].user_id:
2106 2106 owner_row[0].admin_row = True
2107 2107 else:
2108 2108 usr = AttributeDict(usr.get_dict())
2109 2109 usr.admin_row = True
2110 2110 usr.permission = _admin_perm
2111 2111 usr.permission_id = None
2112 2112 super_admin_rows.append(usr)
2113 2113
2114 2114 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
2115 2115 q = q.options(joinedload(UserRepoToPerm.repository),
2116 2116 joinedload(UserRepoToPerm.user),
2117 2117 joinedload(UserRepoToPerm.permission),)
2118 2118
2119 2119 # get owners and admins and permissions. We do a trick of re-writing
2120 2120 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2121 2121 # has a global reference and changing one object propagates to all
2122 2122 # others. This means if admin is also an owner admin_row that change
2123 2123 # would propagate to both objects
2124 2124 perm_rows = []
2125 2125 for _usr in q.all():
2126 2126 usr = AttributeDict(_usr.user.get_dict())
2127 2127 # if this user is also owner/admin, mark as duplicate record
2128 2128 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2129 2129 usr.duplicate_perm = True
2130 2130 # also check if this permission is maybe used by branch_permissions
2131 2131 if _usr.branch_perm_entry:
2132 2132 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2133 2133
2134 2134 usr.permission = _usr.permission.permission_name
2135 2135 usr.permission_id = _usr.repo_to_perm_id
2136 2136 perm_rows.append(usr)
2137 2137
2138 2138 # filter the perm rows by 'default' first and then sort them by
2139 2139 # admin,write,read,none permissions sorted again alphabetically in
2140 2140 # each group
2141 2141 perm_rows = sorted(perm_rows, key=display_user_sort)
2142 2142
2143 2143 user_groups_rows = []
2144 2144 if expand_from_user_groups:
2145 2145 for ug in self.permission_user_groups(with_members=True):
2146 2146 for user_data in ug.members:
2147 2147 user_groups_rows.append(user_data)
2148 2148
2149 2149 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2150 2150
2151 2151 def permission_user_groups(self, with_members=True):
2152 2152 q = UserGroupRepoToPerm.query()\
2153 2153 .filter(UserGroupRepoToPerm.repository == self)
2154 2154 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2155 2155 joinedload(UserGroupRepoToPerm.users_group),
2156 2156 joinedload(UserGroupRepoToPerm.permission),)
2157 2157
2158 2158 perm_rows = []
2159 2159 for _user_group in q.all():
2160 2160 entry = AttributeDict(_user_group.users_group.get_dict())
2161 2161 entry.permission = _user_group.permission.permission_name
2162 2162 if with_members:
2163 2163 entry.members = [x.user.get_dict()
2164 2164 for x in _user_group.users_group.members]
2165 2165 perm_rows.append(entry)
2166 2166
2167 2167 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2168 2168 return perm_rows
2169 2169
2170 2170 def get_api_data(self, include_secrets=False):
2171 2171 """
2172 2172 Common function for generating repo api data
2173 2173
2174 2174 :param include_secrets: See :meth:`User.get_api_data`.
2175 2175
2176 2176 """
2177 2177 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2178 2178 # move this methods on models level.
2179 2179 from rhodecode.model.settings import SettingsModel
2180 2180 from rhodecode.model.repo import RepoModel
2181 2181
2182 2182 repo = self
2183 2183 _user_id, _time, _reason = self.locked
2184 2184
2185 2185 data = {
2186 2186 'repo_id': repo.repo_id,
2187 2187 'repo_name': repo.repo_name,
2188 2188 'repo_type': repo.repo_type,
2189 2189 'clone_uri': repo.clone_uri or '',
2190 2190 'push_uri': repo.push_uri or '',
2191 2191 'url': RepoModel().get_url(self),
2192 2192 'private': repo.private,
2193 2193 'created_on': repo.created_on,
2194 2194 'description': repo.description_safe,
2195 2195 'landing_rev': repo.landing_rev,
2196 2196 'owner': repo.user.username,
2197 2197 'fork_of': repo.fork.repo_name if repo.fork else None,
2198 2198 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2199 2199 'enable_statistics': repo.enable_statistics,
2200 2200 'enable_locking': repo.enable_locking,
2201 2201 'enable_downloads': repo.enable_downloads,
2202 2202 'last_changeset': repo.changeset_cache,
2203 2203 'locked_by': User.get(_user_id).get_api_data(
2204 2204 include_secrets=include_secrets) if _user_id else None,
2205 2205 'locked_date': time_to_datetime(_time) if _time else None,
2206 2206 'lock_reason': _reason if _reason else None,
2207 2207 }
2208 2208
2209 2209 # TODO: mikhail: should be per-repo settings here
2210 2210 rc_config = SettingsModel().get_all_settings()
2211 2211 repository_fields = str2bool(
2212 2212 rc_config.get('rhodecode_repository_fields'))
2213 2213 if repository_fields:
2214 2214 for f in self.extra_fields:
2215 2215 data[f.field_key_prefixed] = f.field_value
2216 2216
2217 2217 return data
2218 2218
2219 2219 @classmethod
2220 2220 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2221 2221 if not lock_time:
2222 2222 lock_time = time.time()
2223 2223 if not lock_reason:
2224 2224 lock_reason = cls.LOCK_AUTOMATIC
2225 2225 repo.locked = [user_id, lock_time, lock_reason]
2226 2226 Session().add(repo)
2227 2227 Session().commit()
2228 2228
2229 2229 @classmethod
2230 2230 def unlock(cls, repo):
2231 2231 repo.locked = None
2232 2232 Session().add(repo)
2233 2233 Session().commit()
2234 2234
2235 2235 @classmethod
2236 2236 def getlock(cls, repo):
2237 2237 return repo.locked
2238 2238
2239 2239 def is_user_lock(self, user_id):
2240 2240 if self.lock[0]:
2241 2241 lock_user_id = safe_int(self.lock[0])
2242 2242 user_id = safe_int(user_id)
2243 2243 # both are ints, and they are equal
2244 2244 return all([lock_user_id, user_id]) and lock_user_id == user_id
2245 2245
2246 2246 return False
2247 2247
2248 2248 def get_locking_state(self, action, user_id, only_when_enabled=True):
2249 2249 """
2250 2250 Checks locking on this repository, if locking is enabled and lock is
2251 2251 present returns a tuple of make_lock, locked, locked_by.
2252 2252 make_lock can have 3 states None (do nothing) True, make lock
2253 2253 False release lock, This value is later propagated to hooks, which
2254 2254 do the locking. Think about this as signals passed to hooks what to do.
2255 2255
2256 2256 """
2257 2257 # TODO: johbo: This is part of the business logic and should be moved
2258 2258 # into the RepositoryModel.
2259 2259
2260 2260 if action not in ('push', 'pull'):
2261 2261 raise ValueError("Invalid action value: %s" % repr(action))
2262 2262
2263 2263 # defines if locked error should be thrown to user
2264 2264 currently_locked = False
2265 2265 # defines if new lock should be made, tri-state
2266 2266 make_lock = None
2267 2267 repo = self
2268 2268 user = User.get(user_id)
2269 2269
2270 2270 lock_info = repo.locked
2271 2271
2272 2272 if repo and (repo.enable_locking or not only_when_enabled):
2273 2273 if action == 'push':
2274 2274 # check if it's already locked !, if it is compare users
2275 2275 locked_by_user_id = lock_info[0]
2276 2276 if user.user_id == locked_by_user_id:
2277 2277 log.debug(
2278 2278 'Got `push` action from user %s, now unlocking', user)
2279 2279 # unlock if we have push from user who locked
2280 2280 make_lock = False
2281 2281 else:
2282 2282 # we're not the same user who locked, ban with
2283 2283 # code defined in settings (default is 423 HTTP Locked) !
2284 2284 log.debug('Repo %s is currently locked by %s', repo, user)
2285 2285 currently_locked = True
2286 2286 elif action == 'pull':
2287 2287 # [0] user [1] date
2288 2288 if lock_info[0] and lock_info[1]:
2289 2289 log.debug('Repo %s is currently locked by %s', repo, user)
2290 2290 currently_locked = True
2291 2291 else:
2292 2292 log.debug('Setting lock on repo %s by %s', repo, user)
2293 2293 make_lock = True
2294 2294
2295 2295 else:
2296 2296 log.debug('Repository %s do not have locking enabled', repo)
2297 2297
2298 2298 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2299 2299 make_lock, currently_locked, lock_info)
2300 2300
2301 2301 from rhodecode.lib.auth import HasRepoPermissionAny
2302 2302 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2303 2303 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2304 2304 # if we don't have at least write permission we cannot make a lock
2305 2305 log.debug('lock state reset back to FALSE due to lack '
2306 2306 'of at least read permission')
2307 2307 make_lock = False
2308 2308
2309 2309 return make_lock, currently_locked, lock_info
2310 2310
2311 2311 @property
2312 2312 def last_commit_cache_update_diff(self):
2313 2313 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2314 2314
2315 2315 @classmethod
2316 2316 def _load_commit_change(cls, last_commit_cache):
2317 2317 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2318 2318 empty_date = datetime.datetime.fromtimestamp(0)
2319 2319 date_latest = last_commit_cache.get('date', empty_date)
2320 2320 try:
2321 2321 return parse_datetime(date_latest)
2322 2322 except Exception:
2323 2323 return empty_date
2324 2324
2325 2325 @property
2326 2326 def last_commit_change(self):
2327 2327 return self._load_commit_change(self.changeset_cache)
2328 2328
2329 2329 @property
2330 2330 def last_db_change(self):
2331 2331 return self.updated_on
2332 2332
2333 2333 @property
2334 2334 def clone_uri_hidden(self):
2335 2335 clone_uri = self.clone_uri
2336 2336 if clone_uri:
2337 2337 import urlobject
2338 2338 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2339 2339 if url_obj.password:
2340 2340 clone_uri = url_obj.with_password('*****')
2341 2341 return clone_uri
2342 2342
2343 2343 @property
2344 2344 def push_uri_hidden(self):
2345 2345 push_uri = self.push_uri
2346 2346 if push_uri:
2347 2347 import urlobject
2348 2348 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2349 2349 if url_obj.password:
2350 2350 push_uri = url_obj.with_password('*****')
2351 2351 return push_uri
2352 2352
2353 2353 def clone_url(self, **override):
2354 2354 from rhodecode.model.settings import SettingsModel
2355 2355
2356 2356 uri_tmpl = None
2357 2357 if 'with_id' in override:
2358 2358 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2359 2359 del override['with_id']
2360 2360
2361 2361 if 'uri_tmpl' in override:
2362 2362 uri_tmpl = override['uri_tmpl']
2363 2363 del override['uri_tmpl']
2364 2364
2365 2365 ssh = False
2366 2366 if 'ssh' in override:
2367 2367 ssh = True
2368 2368 del override['ssh']
2369 2369
2370 2370 # we didn't override our tmpl from **overrides
2371 2371 request = get_current_request()
2372 2372 if not uri_tmpl:
2373 2373 if hasattr(request, 'call_context') and hasattr(request.call_context, 'rc_config'):
2374 2374 rc_config = request.call_context.rc_config
2375 2375 else:
2376 2376 rc_config = SettingsModel().get_all_settings(cache=True)
2377 2377
2378 2378 if ssh:
2379 2379 uri_tmpl = rc_config.get(
2380 2380 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2381 2381
2382 2382 else:
2383 2383 uri_tmpl = rc_config.get(
2384 2384 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2385 2385
2386 2386 return get_clone_url(request=request,
2387 2387 uri_tmpl=uri_tmpl,
2388 2388 repo_name=self.repo_name,
2389 2389 repo_id=self.repo_id,
2390 2390 repo_type=self.repo_type,
2391 2391 **override)
2392 2392
2393 2393 def set_state(self, state):
2394 2394 self.repo_state = state
2395 2395 Session().add(self)
2396 2396 #==========================================================================
2397 2397 # SCM PROPERTIES
2398 2398 #==========================================================================
2399 2399
2400 2400 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None, maybe_unreachable=False, reference_obj=None):
2401 2401 return get_commit_safe(
2402 2402 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load,
2403 2403 maybe_unreachable=maybe_unreachable, reference_obj=reference_obj)
2404 2404
2405 2405 def get_changeset(self, rev=None, pre_load=None):
2406 2406 warnings.warn("Use get_commit", DeprecationWarning)
2407 2407 commit_id = None
2408 2408 commit_idx = None
2409 2409 if isinstance(rev, str):
2410 2410 commit_id = rev
2411 2411 else:
2412 2412 commit_idx = rev
2413 2413 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2414 2414 pre_load=pre_load)
2415 2415
2416 2416 def get_landing_commit(self):
2417 2417 """
2418 2418 Returns landing commit, or if that doesn't exist returns the tip
2419 2419 """
2420 2420 _rev_type, _rev = self.landing_rev
2421 2421 commit = self.get_commit(_rev)
2422 2422 if isinstance(commit, EmptyCommit):
2423 2423 return self.get_commit()
2424 2424 return commit
2425 2425
2426 2426 def flush_commit_cache(self):
2427 2427 self.update_commit_cache(cs_cache={'raw_id':'0'})
2428 2428 self.update_commit_cache()
2429 2429
2430 2430 def update_commit_cache(self, cs_cache=None, config=None):
2431 2431 """
2432 2432 Update cache of last commit for repository
2433 2433 cache_keys should be::
2434 2434
2435 2435 source_repo_id
2436 2436 short_id
2437 2437 raw_id
2438 2438 revision
2439 2439 parents
2440 2440 message
2441 2441 date
2442 2442 author
2443 2443 updated_on
2444 2444
2445 2445 """
2446 2446 from rhodecode.lib.vcs.backends.base import BaseChangeset
2447 2447 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2448 2448 empty_date = datetime.datetime.fromtimestamp(0)
2449 2449
2450 2450 if cs_cache is None:
2451 2451 # use no-cache version here
2452 2452 try:
2453 2453 scm_repo = self.scm_instance(cache=False, config=config)
2454 2454 except VCSError:
2455 2455 scm_repo = None
2456 2456 empty = scm_repo is None or scm_repo.is_empty()
2457 2457
2458 2458 if not empty:
2459 2459 cs_cache = scm_repo.get_commit(
2460 2460 pre_load=["author", "date", "message", "parents", "branch"])
2461 2461 else:
2462 2462 cs_cache = EmptyCommit()
2463 2463
2464 2464 if isinstance(cs_cache, BaseChangeset):
2465 2465 cs_cache = cs_cache.__json__()
2466 2466
2467 2467 def is_outdated(new_cs_cache):
2468 2468 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2469 2469 new_cs_cache['revision'] != self.changeset_cache['revision']):
2470 2470 return True
2471 2471 return False
2472 2472
2473 2473 # check if we have maybe already latest cached revision
2474 2474 if is_outdated(cs_cache) or not self.changeset_cache:
2475 2475 _current_datetime = datetime.datetime.utcnow()
2476 2476 last_change = cs_cache.get('date') or _current_datetime
2477 2477 # we check if last update is newer than the new value
2478 2478 # if yes, we use the current timestamp instead. Imagine you get
2479 2479 # old commit pushed 1y ago, we'd set last update 1y to ago.
2480 2480 last_change_timestamp = datetime_to_time(last_change)
2481 2481 current_timestamp = datetime_to_time(last_change)
2482 2482 if last_change_timestamp > current_timestamp and not empty:
2483 2483 cs_cache['date'] = _current_datetime
2484 2484
2485 2485 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2486 2486 cs_cache['updated_on'] = time.time()
2487 2487 self.changeset_cache = cs_cache
2488 2488 self.updated_on = last_change
2489 2489 Session().add(self)
2490 2490 Session().commit()
2491 2491
2492 2492 else:
2493 2493 if empty:
2494 2494 cs_cache = EmptyCommit().__json__()
2495 2495 else:
2496 2496 cs_cache = self.changeset_cache
2497 2497
2498 2498 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2499 2499
2500 2500 cs_cache['updated_on'] = time.time()
2501 2501 self.changeset_cache = cs_cache
2502 2502 self.updated_on = _date_latest
2503 2503 Session().add(self)
2504 2504 Session().commit()
2505 2505
2506 2506 log.debug('updated repo `%s` with new commit cache %s, and last update_date: %s',
2507 2507 self.repo_name, cs_cache, _date_latest)
2508 2508
2509 2509 @property
2510 2510 def tip(self):
2511 2511 return self.get_commit('tip')
2512 2512
2513 2513 @property
2514 2514 def author(self):
2515 2515 return self.tip.author
2516 2516
2517 2517 @property
2518 2518 def last_change(self):
2519 2519 return self.scm_instance().last_change
2520 2520
2521 2521 def get_comments(self, revisions=None):
2522 2522 """
2523 2523 Returns comments for this repository grouped by revisions
2524 2524
2525 2525 :param revisions: filter query by revisions only
2526 2526 """
2527 2527 cmts = ChangesetComment.query()\
2528 2528 .filter(ChangesetComment.repo == self)
2529 2529 if revisions:
2530 2530 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2531 2531 grouped = collections.defaultdict(list)
2532 2532 for cmt in cmts.all():
2533 2533 grouped[cmt.revision].append(cmt)
2534 2534 return grouped
2535 2535
2536 2536 def statuses(self, revisions=None):
2537 2537 """
2538 2538 Returns statuses for this repository
2539 2539
2540 2540 :param revisions: list of revisions to get statuses for
2541 2541 """
2542 2542 statuses = ChangesetStatus.query()\
2543 2543 .filter(ChangesetStatus.repo == self)\
2544 2544 .filter(ChangesetStatus.version == 0)
2545 2545
2546 2546 if revisions:
2547 2547 # Try doing the filtering in chunks to avoid hitting limits
2548 2548 size = 500
2549 2549 status_results = []
2550 2550 for chunk in range(0, len(revisions), size):
2551 2551 status_results += statuses.filter(
2552 2552 ChangesetStatus.revision.in_(
2553 2553 revisions[chunk: chunk+size])
2554 2554 ).all()
2555 2555 else:
2556 2556 status_results = statuses.all()
2557 2557
2558 2558 grouped = {}
2559 2559
2560 2560 # maybe we have open new pullrequest without a status?
2561 2561 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2562 2562 status_lbl = ChangesetStatus.get_status_lbl(stat)
2563 2563 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2564 2564 for rev in pr.revisions:
2565 2565 pr_id = pr.pull_request_id
2566 2566 pr_repo = pr.target_repo.repo_name
2567 2567 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2568 2568
2569 2569 for stat in status_results:
2570 2570 pr_id = pr_repo = None
2571 2571 if stat.pull_request:
2572 2572 pr_id = stat.pull_request.pull_request_id
2573 2573 pr_repo = stat.pull_request.target_repo.repo_name
2574 2574 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2575 2575 pr_id, pr_repo]
2576 2576 return grouped
2577 2577
2578 2578 # ==========================================================================
2579 2579 # SCM CACHE INSTANCE
2580 2580 # ==========================================================================
2581 2581
2582 2582 def scm_instance(self, **kwargs):
2583 2583 import rhodecode
2584 2584
2585 2585 # Passing a config will not hit the cache currently only used
2586 2586 # for repo2dbmapper
2587 2587 config = kwargs.pop('config', None)
2588 2588 cache = kwargs.pop('cache', None)
2589 2589 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2590 2590 if vcs_full_cache is not None:
2591 2591 # allows override global config
2592 2592 full_cache = vcs_full_cache
2593 2593 else:
2594 2594 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2595 2595 # if cache is NOT defined use default global, else we have a full
2596 2596 # control over cache behaviour
2597 2597 if cache is None and full_cache and not config:
2598 2598 log.debug('Initializing pure cached instance for %s', self.repo_path)
2599 2599 return self._get_instance_cached()
2600 2600
2601 2601 # cache here is sent to the "vcs server"
2602 2602 return self._get_instance(cache=bool(cache), config=config)
2603 2603
2604 2604 def _get_instance_cached(self):
2605 2605 from rhodecode.lib import rc_cache
2606 2606
2607 2607 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2608 2608 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2609 2609 repo_id=self.repo_id)
2610 2610 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2611 2611
2612 2612 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2613 2613 def get_instance_cached(repo_id, context_id, _cache_state_uid):
2614 2614 return self._get_instance(repo_state_uid=_cache_state_uid)
2615 2615
2616 2616 # we must use thread scoped cache here,
2617 2617 # because each thread of gevent needs it's own not shared connection and cache
2618 2618 # we also alter `args` so the cache key is individual for every green thread.
2619 2619 inv_context_manager = rc_cache.InvalidationContext(
2620 2620 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2621 2621 thread_scoped=True)
2622 2622 with inv_context_manager as invalidation_context:
2623 2623 cache_state_uid = invalidation_context.cache_data['cache_state_uid']
2624 2624 args = (self.repo_id, inv_context_manager.cache_key, cache_state_uid)
2625 2625
2626 2626 # re-compute and store cache if we get invalidate signal
2627 2627 if invalidation_context.should_invalidate():
2628 2628 instance = get_instance_cached.refresh(*args)
2629 2629 else:
2630 2630 instance = get_instance_cached(*args)
2631 2631
2632 2632 log.debug('Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2633 2633 return instance
2634 2634
2635 2635 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2636 2636 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2637 2637 self.repo_type, self.repo_path, cache)
2638 2638 config = config or self._config
2639 2639 custom_wire = {
2640 2640 'cache': cache, # controls the vcs.remote cache
2641 2641 'repo_state_uid': repo_state_uid
2642 2642 }
2643 2643 repo = get_vcs_instance(
2644 2644 repo_path=safe_str(self.repo_full_path),
2645 2645 config=config,
2646 2646 with_wire=custom_wire,
2647 2647 create=False,
2648 2648 _vcs_alias=self.repo_type)
2649 2649 if repo is not None:
2650 2650 repo.count() # cache rebuild
2651 2651 return repo
2652 2652
2653 2653 def get_shadow_repository_path(self, workspace_id):
2654 2654 from rhodecode.lib.vcs.backends.base import BaseRepository
2655 2655 shadow_repo_path = BaseRepository._get_shadow_repository_path(
2656 2656 self.repo_full_path, self.repo_id, workspace_id)
2657 2657 return shadow_repo_path
2658 2658
2659 2659 def __json__(self):
2660 2660 return {'landing_rev': self.landing_rev}
2661 2661
2662 2662 def get_dict(self):
2663 2663
2664 2664 # Since we transformed `repo_name` to a hybrid property, we need to
2665 2665 # keep compatibility with the code which uses `repo_name` field.
2666 2666
2667 2667 result = super(Repository, self).get_dict()
2668 2668 result['repo_name'] = result.pop('_repo_name', None)
2669 2669 return result
2670 2670
2671 2671
2672 2672 class RepoGroup(Base, BaseModel):
2673 2673 __tablename__ = 'groups'
2674 2674 __table_args__ = (
2675 2675 UniqueConstraint('group_name', 'group_parent_id'),
2676 2676 base_table_args,
2677 2677 )
2678 2678 __mapper_args__ = {
2679 2679 #TODO: this is now depracated ?!
2680 2680 # 'order_by': 'group_name'
2681 2681 }
2682 2682
2683 2683 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2684 2684
2685 2685 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2686 2686 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2687 2687 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2688 2688 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2689 2689 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2690 2690 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2691 2691 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2692 2692 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2693 2693 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2694 2694 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2695 2695 _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) # JSON data
2696 2696
2697 2697 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2698 2698 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2699 2699 parent_group = relationship('RepoGroup', remote_side=group_id)
2700 2700 user = relationship('User')
2701 2701 integrations = relationship('Integration', cascade="all, delete-orphan")
2702 2702
2703 2703 # no cascade, set NULL
2704 2704 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_group_id==RepoGroup.group_id')
2705 2705
2706 2706 def __init__(self, group_name='', parent_group=None):
2707 2707 self.group_name = group_name
2708 2708 self.parent_group = parent_group
2709 2709
2710 2710 def __unicode__(self):
2711 2711 return u"<%s('id:%s:%s')>" % (
2712 2712 self.__class__.__name__, self.group_id, self.group_name)
2713 2713
2714 2714 @hybrid_property
2715 2715 def group_name(self):
2716 2716 return self._group_name
2717 2717
2718 2718 @group_name.setter
2719 2719 def group_name(self, value):
2720 2720 self._group_name = value
2721 2721 self.group_name_hash = self.hash_repo_group_name(value)
2722 2722
2723 2723 @classmethod
2724 2724 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
2725 2725 from rhodecode.lib.vcs.backends.base import EmptyCommit
2726 2726 dummy = EmptyCommit().__json__()
2727 2727 if not changeset_cache_raw:
2728 2728 dummy['source_repo_id'] = repo_id
2729 2729 return json.loads(json.dumps(dummy))
2730 2730
2731 2731 try:
2732 2732 return json.loads(changeset_cache_raw)
2733 2733 except TypeError:
2734 2734 return dummy
2735 2735 except Exception:
2736 2736 log.error(traceback.format_exc())
2737 2737 return dummy
2738 2738
2739 2739 @hybrid_property
2740 2740 def changeset_cache(self):
2741 2741 return self._load_changeset_cache('', self._changeset_cache)
2742 2742
2743 2743 @changeset_cache.setter
2744 2744 def changeset_cache(self, val):
2745 2745 try:
2746 2746 self._changeset_cache = json.dumps(val)
2747 2747 except Exception:
2748 2748 log.error(traceback.format_exc())
2749 2749
2750 2750 @validates('group_parent_id')
2751 2751 def validate_group_parent_id(self, key, val):
2752 2752 """
2753 2753 Check cycle references for a parent group to self
2754 2754 """
2755 2755 if self.group_id and val:
2756 2756 assert val != self.group_id
2757 2757
2758 2758 return val
2759 2759
2760 2760 @hybrid_property
2761 2761 def description_safe(self):
2762 2762 from rhodecode.lib import helpers as h
2763 2763 return h.escape(self.group_description)
2764 2764
2765 2765 @classmethod
2766 2766 def hash_repo_group_name(cls, repo_group_name):
2767 2767 val = remove_formatting(repo_group_name)
2768 2768 val = safe_str(val).lower()
2769 2769 chars = []
2770 2770 for c in val:
2771 2771 if c not in string.ascii_letters:
2772 2772 c = str(ord(c))
2773 2773 chars.append(c)
2774 2774
2775 2775 return ''.join(chars)
2776 2776
2777 2777 @classmethod
2778 2778 def _generate_choice(cls, repo_group):
2779 2779 from webhelpers2.html import literal as _literal
2780 2780 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2781 2781 return repo_group.group_id, _name(repo_group.full_path_splitted)
2782 2782
2783 2783 @classmethod
2784 2784 def groups_choices(cls, groups=None, show_empty_group=True):
2785 2785 if not groups:
2786 2786 groups = cls.query().all()
2787 2787
2788 2788 repo_groups = []
2789 2789 if show_empty_group:
2790 2790 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2791 2791
2792 2792 repo_groups.extend([cls._generate_choice(x) for x in groups])
2793 2793
2794 2794 repo_groups = sorted(
2795 2795 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2796 2796 return repo_groups
2797 2797
2798 2798 @classmethod
2799 2799 def url_sep(cls):
2800 2800 return URL_SEP
2801 2801
2802 2802 @classmethod
2803 2803 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2804 2804 if case_insensitive:
2805 2805 gr = cls.query().filter(func.lower(cls.group_name)
2806 2806 == func.lower(group_name))
2807 2807 else:
2808 2808 gr = cls.query().filter(cls.group_name == group_name)
2809 2809 if cache:
2810 2810 name_key = _hash_key(group_name)
2811 2811 gr = gr.options(
2812 2812 FromCache("sql_cache_short", "get_group_%s" % name_key))
2813 2813 return gr.scalar()
2814 2814
2815 2815 @classmethod
2816 2816 def get_user_personal_repo_group(cls, user_id):
2817 2817 user = User.get(user_id)
2818 2818 if user.username == User.DEFAULT_USER:
2819 2819 return None
2820 2820
2821 2821 return cls.query()\
2822 2822 .filter(cls.personal == true()) \
2823 2823 .filter(cls.user == user) \
2824 2824 .order_by(cls.group_id.asc()) \
2825 2825 .first()
2826 2826
2827 2827 @classmethod
2828 2828 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2829 2829 case_insensitive=True):
2830 2830 q = RepoGroup.query()
2831 2831
2832 2832 if not isinstance(user_id, Optional):
2833 2833 q = q.filter(RepoGroup.user_id == user_id)
2834 2834
2835 2835 if not isinstance(group_id, Optional):
2836 2836 q = q.filter(RepoGroup.group_parent_id == group_id)
2837 2837
2838 2838 if case_insensitive:
2839 2839 q = q.order_by(func.lower(RepoGroup.group_name))
2840 2840 else:
2841 2841 q = q.order_by(RepoGroup.group_name)
2842 2842 return q.all()
2843 2843
2844 2844 @property
2845 2845 def parents(self, parents_recursion_limit=10):
2846 2846 groups = []
2847 2847 if self.parent_group is None:
2848 2848 return groups
2849 2849 cur_gr = self.parent_group
2850 2850 groups.insert(0, cur_gr)
2851 2851 cnt = 0
2852 2852 while 1:
2853 2853 cnt += 1
2854 2854 gr = getattr(cur_gr, 'parent_group', None)
2855 2855 cur_gr = cur_gr.parent_group
2856 2856 if gr is None:
2857 2857 break
2858 2858 if cnt == parents_recursion_limit:
2859 2859 # this will prevent accidental infinit loops
2860 2860 log.error('more than %s parents found for group %s, stopping '
2861 2861 'recursive parent fetching', parents_recursion_limit, self)
2862 2862 break
2863 2863
2864 2864 groups.insert(0, gr)
2865 2865 return groups
2866 2866
2867 2867 @property
2868 2868 def last_commit_cache_update_diff(self):
2869 2869 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2870 2870
2871 2871 @classmethod
2872 2872 def _load_commit_change(cls, last_commit_cache):
2873 2873 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2874 2874 empty_date = datetime.datetime.fromtimestamp(0)
2875 2875 date_latest = last_commit_cache.get('date', empty_date)
2876 2876 try:
2877 2877 return parse_datetime(date_latest)
2878 2878 except Exception:
2879 2879 return empty_date
2880 2880
2881 2881 @property
2882 2882 def last_commit_change(self):
2883 2883 return self._load_commit_change(self.changeset_cache)
2884 2884
2885 2885 @property
2886 2886 def last_db_change(self):
2887 2887 return self.updated_on
2888 2888
2889 2889 @property
2890 2890 def children(self):
2891 2891 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2892 2892
2893 2893 @property
2894 2894 def name(self):
2895 2895 return self.group_name.split(RepoGroup.url_sep())[-1]
2896 2896
2897 2897 @property
2898 2898 def full_path(self):
2899 2899 return self.group_name
2900 2900
2901 2901 @property
2902 2902 def full_path_splitted(self):
2903 2903 return self.group_name.split(RepoGroup.url_sep())
2904 2904
2905 2905 @property
2906 2906 def repositories(self):
2907 2907 return Repository.query()\
2908 2908 .filter(Repository.group == self)\
2909 2909 .order_by(Repository.repo_name)
2910 2910
2911 2911 @property
2912 2912 def repositories_recursive_count(self):
2913 2913 cnt = self.repositories.count()
2914 2914
2915 2915 def children_count(group):
2916 2916 cnt = 0
2917 2917 for child in group.children:
2918 2918 cnt += child.repositories.count()
2919 2919 cnt += children_count(child)
2920 2920 return cnt
2921 2921
2922 2922 return cnt + children_count(self)
2923 2923
2924 2924 def _recursive_objects(self, include_repos=True, include_groups=True):
2925 2925 all_ = []
2926 2926
2927 2927 def _get_members(root_gr):
2928 2928 if include_repos:
2929 2929 for r in root_gr.repositories:
2930 2930 all_.append(r)
2931 2931 childs = root_gr.children.all()
2932 2932 if childs:
2933 2933 for gr in childs:
2934 2934 if include_groups:
2935 2935 all_.append(gr)
2936 2936 _get_members(gr)
2937 2937
2938 2938 root_group = []
2939 2939 if include_groups:
2940 2940 root_group = [self]
2941 2941
2942 2942 _get_members(self)
2943 2943 return root_group + all_
2944 2944
2945 2945 def recursive_groups_and_repos(self):
2946 2946 """
2947 2947 Recursive return all groups, with repositories in those groups
2948 2948 """
2949 2949 return self._recursive_objects()
2950 2950
2951 2951 def recursive_groups(self):
2952 2952 """
2953 2953 Returns all children groups for this group including children of children
2954 2954 """
2955 2955 return self._recursive_objects(include_repos=False)
2956 2956
2957 2957 def recursive_repos(self):
2958 2958 """
2959 2959 Returns all children repositories for this group
2960 2960 """
2961 2961 return self._recursive_objects(include_groups=False)
2962 2962
2963 2963 def get_new_name(self, group_name):
2964 2964 """
2965 2965 returns new full group name based on parent and new name
2966 2966
2967 2967 :param group_name:
2968 2968 """
2969 2969 path_prefix = (self.parent_group.full_path_splitted if
2970 2970 self.parent_group else [])
2971 2971 return RepoGroup.url_sep().join(path_prefix + [group_name])
2972 2972
2973 2973 def update_commit_cache(self, config=None):
2974 2974 """
2975 2975 Update cache of last commit for newest repository inside this repository group.
2976 2976 cache_keys should be::
2977 2977
2978 2978 source_repo_id
2979 2979 short_id
2980 2980 raw_id
2981 2981 revision
2982 2982 parents
2983 2983 message
2984 2984 date
2985 2985 author
2986 2986
2987 2987 """
2988 2988 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2989 2989 empty_date = datetime.datetime.fromtimestamp(0)
2990 2990
2991 2991 def repo_groups_and_repos(root_gr):
2992 2992 for _repo in root_gr.repositories:
2993 2993 yield _repo
2994 2994 for child_group in root_gr.children.all():
2995 2995 yield child_group
2996 2996
2997 2997 latest_repo_cs_cache = {}
2998 2998 for obj in repo_groups_and_repos(self):
2999 2999 repo_cs_cache = obj.changeset_cache
3000 3000 date_latest = latest_repo_cs_cache.get('date', empty_date)
3001 3001 date_current = repo_cs_cache.get('date', empty_date)
3002 3002 current_timestamp = datetime_to_time(parse_datetime(date_latest))
3003 3003 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
3004 3004 latest_repo_cs_cache = repo_cs_cache
3005 3005 if hasattr(obj, 'repo_id'):
3006 3006 latest_repo_cs_cache['source_repo_id'] = obj.repo_id
3007 3007 else:
3008 3008 latest_repo_cs_cache['source_repo_id'] = repo_cs_cache.get('source_repo_id')
3009 3009
3010 3010 _date_latest = parse_datetime(latest_repo_cs_cache.get('date') or empty_date)
3011 3011
3012 3012 latest_repo_cs_cache['updated_on'] = time.time()
3013 3013 self.changeset_cache = latest_repo_cs_cache
3014 3014 self.updated_on = _date_latest
3015 3015 Session().add(self)
3016 3016 Session().commit()
3017 3017
3018 3018 log.debug('updated repo group `%s` with new commit cache %s, and last update_date: %s',
3019 3019 self.group_name, latest_repo_cs_cache, _date_latest)
3020 3020
3021 3021 def permissions(self, with_admins=True, with_owner=True,
3022 3022 expand_from_user_groups=False):
3023 3023 """
3024 3024 Permissions for repository groups
3025 3025 """
3026 3026 _admin_perm = 'group.admin'
3027 3027
3028 3028 owner_row = []
3029 3029 if with_owner:
3030 3030 usr = AttributeDict(self.user.get_dict())
3031 3031 usr.owner_row = True
3032 3032 usr.permission = _admin_perm
3033 3033 owner_row.append(usr)
3034 3034
3035 3035 super_admin_ids = []
3036 3036 super_admin_rows = []
3037 3037 if with_admins:
3038 3038 for usr in User.get_all_super_admins():
3039 3039 super_admin_ids.append(usr.user_id)
3040 3040 # if this admin is also owner, don't double the record
3041 3041 if usr.user_id == owner_row[0].user_id:
3042 3042 owner_row[0].admin_row = True
3043 3043 else:
3044 3044 usr = AttributeDict(usr.get_dict())
3045 3045 usr.admin_row = True
3046 3046 usr.permission = _admin_perm
3047 3047 super_admin_rows.append(usr)
3048 3048
3049 3049 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
3050 3050 q = q.options(joinedload(UserRepoGroupToPerm.group),
3051 3051 joinedload(UserRepoGroupToPerm.user),
3052 3052 joinedload(UserRepoGroupToPerm.permission),)
3053 3053
3054 3054 # get owners and admins and permissions. We do a trick of re-writing
3055 3055 # objects from sqlalchemy to named-tuples due to sqlalchemy session
3056 3056 # has a global reference and changing one object propagates to all
3057 3057 # others. This means if admin is also an owner admin_row that change
3058 3058 # would propagate to both objects
3059 3059 perm_rows = []
3060 3060 for _usr in q.all():
3061 3061 usr = AttributeDict(_usr.user.get_dict())
3062 3062 # if this user is also owner/admin, mark as duplicate record
3063 3063 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
3064 3064 usr.duplicate_perm = True
3065 3065 usr.permission = _usr.permission.permission_name
3066 3066 perm_rows.append(usr)
3067 3067
3068 3068 # filter the perm rows by 'default' first and then sort them by
3069 3069 # admin,write,read,none permissions sorted again alphabetically in
3070 3070 # each group
3071 3071 perm_rows = sorted(perm_rows, key=display_user_sort)
3072 3072
3073 3073 user_groups_rows = []
3074 3074 if expand_from_user_groups:
3075 3075 for ug in self.permission_user_groups(with_members=True):
3076 3076 for user_data in ug.members:
3077 3077 user_groups_rows.append(user_data)
3078 3078
3079 3079 return super_admin_rows + owner_row + perm_rows + user_groups_rows
3080 3080
3081 3081 def permission_user_groups(self, with_members=False):
3082 3082 q = UserGroupRepoGroupToPerm.query()\
3083 3083 .filter(UserGroupRepoGroupToPerm.group == self)
3084 3084 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
3085 3085 joinedload(UserGroupRepoGroupToPerm.users_group),
3086 3086 joinedload(UserGroupRepoGroupToPerm.permission),)
3087 3087
3088 3088 perm_rows = []
3089 3089 for _user_group in q.all():
3090 3090 entry = AttributeDict(_user_group.users_group.get_dict())
3091 3091 entry.permission = _user_group.permission.permission_name
3092 3092 if with_members:
3093 3093 entry.members = [x.user.get_dict()
3094 3094 for x in _user_group.users_group.members]
3095 3095 perm_rows.append(entry)
3096 3096
3097 3097 perm_rows = sorted(perm_rows, key=display_user_group_sort)
3098 3098 return perm_rows
3099 3099
3100 3100 def get_api_data(self):
3101 3101 """
3102 3102 Common function for generating api data
3103 3103
3104 3104 """
3105 3105 group = self
3106 3106 data = {
3107 3107 'group_id': group.group_id,
3108 3108 'group_name': group.group_name,
3109 3109 'group_description': group.description_safe,
3110 3110 'parent_group': group.parent_group.group_name if group.parent_group else None,
3111 3111 'repositories': [x.repo_name for x in group.repositories],
3112 3112 'owner': group.user.username,
3113 3113 }
3114 3114 return data
3115 3115
3116 3116 def get_dict(self):
3117 3117 # Since we transformed `group_name` to a hybrid property, we need to
3118 3118 # keep compatibility with the code which uses `group_name` field.
3119 3119 result = super(RepoGroup, self).get_dict()
3120 3120 result['group_name'] = result.pop('_group_name', None)
3121 3121 return result
3122 3122
3123 3123
3124 3124 class Permission(Base, BaseModel):
3125 3125 __tablename__ = 'permissions'
3126 3126 __table_args__ = (
3127 3127 Index('p_perm_name_idx', 'permission_name'),
3128 3128 base_table_args,
3129 3129 )
3130 3130
3131 3131 PERMS = [
3132 3132 ('hg.admin', _('RhodeCode Super Administrator')),
3133 3133
3134 3134 ('repository.none', _('Repository no access')),
3135 3135 ('repository.read', _('Repository read access')),
3136 3136 ('repository.write', _('Repository write access')),
3137 3137 ('repository.admin', _('Repository admin access')),
3138 3138
3139 3139 ('group.none', _('Repository group no access')),
3140 3140 ('group.read', _('Repository group read access')),
3141 3141 ('group.write', _('Repository group write access')),
3142 3142 ('group.admin', _('Repository group admin access')),
3143 3143
3144 3144 ('usergroup.none', _('User group no access')),
3145 3145 ('usergroup.read', _('User group read access')),
3146 3146 ('usergroup.write', _('User group write access')),
3147 3147 ('usergroup.admin', _('User group admin access')),
3148 3148
3149 3149 ('branch.none', _('Branch no permissions')),
3150 3150 ('branch.merge', _('Branch access by web merge')),
3151 3151 ('branch.push', _('Branch access by push')),
3152 3152 ('branch.push_force', _('Branch access by push with force')),
3153 3153
3154 3154 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
3155 3155 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
3156 3156
3157 3157 ('hg.usergroup.create.false', _('User Group creation disabled')),
3158 3158 ('hg.usergroup.create.true', _('User Group creation enabled')),
3159 3159
3160 3160 ('hg.create.none', _('Repository creation disabled')),
3161 3161 ('hg.create.repository', _('Repository creation enabled')),
3162 3162 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3163 3163 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3164 3164
3165 3165 ('hg.fork.none', _('Repository forking disabled')),
3166 3166 ('hg.fork.repository', _('Repository forking enabled')),
3167 3167
3168 3168 ('hg.register.none', _('Registration disabled')),
3169 3169 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3170 3170 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3171 3171
3172 3172 ('hg.password_reset.enabled', _('Password reset enabled')),
3173 3173 ('hg.password_reset.hidden', _('Password reset hidden')),
3174 3174 ('hg.password_reset.disabled', _('Password reset disabled')),
3175 3175
3176 3176 ('hg.extern_activate.manual', _('Manual activation of external account')),
3177 3177 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3178 3178
3179 3179 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3180 3180 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3181 3181 ]
3182 3182
3183 3183 # definition of system default permissions for DEFAULT user, created on
3184 3184 # system setup
3185 3185 DEFAULT_USER_PERMISSIONS = [
3186 3186 # object perms
3187 3187 'repository.read',
3188 3188 'group.read',
3189 3189 'usergroup.read',
3190 3190 # branch, for backward compat we need same value as before so forced pushed
3191 3191 'branch.push_force',
3192 3192 # global
3193 3193 'hg.create.repository',
3194 3194 'hg.repogroup.create.false',
3195 3195 'hg.usergroup.create.false',
3196 3196 'hg.create.write_on_repogroup.true',
3197 3197 'hg.fork.repository',
3198 3198 'hg.register.manual_activate',
3199 3199 'hg.password_reset.enabled',
3200 3200 'hg.extern_activate.auto',
3201 3201 'hg.inherit_default_perms.true',
3202 3202 ]
3203 3203
3204 3204 # defines which permissions are more important higher the more important
3205 3205 # Weight defines which permissions are more important.
3206 3206 # The higher number the more important.
3207 3207 PERM_WEIGHTS = {
3208 3208 'repository.none': 0,
3209 3209 'repository.read': 1,
3210 3210 'repository.write': 3,
3211 3211 'repository.admin': 4,
3212 3212
3213 3213 'group.none': 0,
3214 3214 'group.read': 1,
3215 3215 'group.write': 3,
3216 3216 'group.admin': 4,
3217 3217
3218 3218 'usergroup.none': 0,
3219 3219 'usergroup.read': 1,
3220 3220 'usergroup.write': 3,
3221 3221 'usergroup.admin': 4,
3222 3222
3223 3223 'branch.none': 0,
3224 3224 'branch.merge': 1,
3225 3225 'branch.push': 3,
3226 3226 'branch.push_force': 4,
3227 3227
3228 3228 'hg.repogroup.create.false': 0,
3229 3229 'hg.repogroup.create.true': 1,
3230 3230
3231 3231 'hg.usergroup.create.false': 0,
3232 3232 'hg.usergroup.create.true': 1,
3233 3233
3234 3234 'hg.fork.none': 0,
3235 3235 'hg.fork.repository': 1,
3236 3236 'hg.create.none': 0,
3237 3237 'hg.create.repository': 1
3238 3238 }
3239 3239
3240 3240 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3241 3241 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3242 3242 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3243 3243
3244 3244 def __unicode__(self):
3245 3245 return u"<%s('%s:%s')>" % (
3246 3246 self.__class__.__name__, self.permission_id, self.permission_name
3247 3247 )
3248 3248
3249 3249 @classmethod
3250 3250 def get_by_key(cls, key):
3251 3251 return cls.query().filter(cls.permission_name == key).scalar()
3252 3252
3253 3253 @classmethod
3254 3254 def get_default_repo_perms(cls, user_id, repo_id=None):
3255 3255 q = Session().query(UserRepoToPerm, Repository, Permission)\
3256 3256 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3257 3257 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3258 3258 .filter(UserRepoToPerm.user_id == user_id)
3259 3259 if repo_id:
3260 3260 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3261 3261 return q.all()
3262 3262
3263 3263 @classmethod
3264 3264 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3265 3265 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3266 3266 .join(
3267 3267 Permission,
3268 3268 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3269 3269 .join(
3270 3270 UserRepoToPerm,
3271 3271 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3272 3272 .filter(UserRepoToPerm.user_id == user_id)
3273 3273
3274 3274 if repo_id:
3275 3275 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3276 3276 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3277 3277
3278 3278 @classmethod
3279 3279 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3280 3280 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3281 3281 .join(
3282 3282 Permission,
3283 3283 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3284 3284 .join(
3285 3285 Repository,
3286 3286 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3287 3287 .join(
3288 3288 UserGroup,
3289 3289 UserGroupRepoToPerm.users_group_id ==
3290 3290 UserGroup.users_group_id)\
3291 3291 .join(
3292 3292 UserGroupMember,
3293 3293 UserGroupRepoToPerm.users_group_id ==
3294 3294 UserGroupMember.users_group_id)\
3295 3295 .filter(
3296 3296 UserGroupMember.user_id == user_id,
3297 3297 UserGroup.users_group_active == true())
3298 3298 if repo_id:
3299 3299 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3300 3300 return q.all()
3301 3301
3302 3302 @classmethod
3303 3303 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3304 3304 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3305 3305 .join(
3306 3306 Permission,
3307 3307 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3308 3308 .join(
3309 3309 UserGroupRepoToPerm,
3310 3310 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3311 3311 .join(
3312 3312 UserGroup,
3313 3313 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3314 3314 .join(
3315 3315 UserGroupMember,
3316 3316 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3317 3317 .filter(
3318 3318 UserGroupMember.user_id == user_id,
3319 3319 UserGroup.users_group_active == true())
3320 3320
3321 3321 if repo_id:
3322 3322 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3323 3323 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3324 3324
3325 3325 @classmethod
3326 3326 def get_default_group_perms(cls, user_id, repo_group_id=None):
3327 3327 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3328 3328 .join(
3329 3329 Permission,
3330 3330 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3331 3331 .join(
3332 3332 RepoGroup,
3333 3333 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3334 3334 .filter(UserRepoGroupToPerm.user_id == user_id)
3335 3335 if repo_group_id:
3336 3336 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3337 3337 return q.all()
3338 3338
3339 3339 @classmethod
3340 3340 def get_default_group_perms_from_user_group(
3341 3341 cls, user_id, repo_group_id=None):
3342 3342 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3343 3343 .join(
3344 3344 Permission,
3345 3345 UserGroupRepoGroupToPerm.permission_id ==
3346 3346 Permission.permission_id)\
3347 3347 .join(
3348 3348 RepoGroup,
3349 3349 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3350 3350 .join(
3351 3351 UserGroup,
3352 3352 UserGroupRepoGroupToPerm.users_group_id ==
3353 3353 UserGroup.users_group_id)\
3354 3354 .join(
3355 3355 UserGroupMember,
3356 3356 UserGroupRepoGroupToPerm.users_group_id ==
3357 3357 UserGroupMember.users_group_id)\
3358 3358 .filter(
3359 3359 UserGroupMember.user_id == user_id,
3360 3360 UserGroup.users_group_active == true())
3361 3361 if repo_group_id:
3362 3362 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3363 3363 return q.all()
3364 3364
3365 3365 @classmethod
3366 3366 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3367 3367 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3368 3368 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3369 3369 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3370 3370 .filter(UserUserGroupToPerm.user_id == user_id)
3371 3371 if user_group_id:
3372 3372 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3373 3373 return q.all()
3374 3374
3375 3375 @classmethod
3376 3376 def get_default_user_group_perms_from_user_group(
3377 3377 cls, user_id, user_group_id=None):
3378 3378 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3379 3379 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3380 3380 .join(
3381 3381 Permission,
3382 3382 UserGroupUserGroupToPerm.permission_id ==
3383 3383 Permission.permission_id)\
3384 3384 .join(
3385 3385 TargetUserGroup,
3386 3386 UserGroupUserGroupToPerm.target_user_group_id ==
3387 3387 TargetUserGroup.users_group_id)\
3388 3388 .join(
3389 3389 UserGroup,
3390 3390 UserGroupUserGroupToPerm.user_group_id ==
3391 3391 UserGroup.users_group_id)\
3392 3392 .join(
3393 3393 UserGroupMember,
3394 3394 UserGroupUserGroupToPerm.user_group_id ==
3395 3395 UserGroupMember.users_group_id)\
3396 3396 .filter(
3397 3397 UserGroupMember.user_id == user_id,
3398 3398 UserGroup.users_group_active == true())
3399 3399 if user_group_id:
3400 3400 q = q.filter(
3401 3401 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3402 3402
3403 3403 return q.all()
3404 3404
3405 3405
3406 3406 class UserRepoToPerm(Base, BaseModel):
3407 3407 __tablename__ = 'repo_to_perm'
3408 3408 __table_args__ = (
3409 3409 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3410 3410 base_table_args
3411 3411 )
3412 3412
3413 3413 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3414 3414 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3415 3415 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3416 3416 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3417 3417
3418 3418 user = relationship('User')
3419 3419 repository = relationship('Repository')
3420 3420 permission = relationship('Permission')
3421 3421
3422 3422 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete-orphan", lazy='joined')
3423 3423
3424 3424 @classmethod
3425 3425 def create(cls, user, repository, permission):
3426 3426 n = cls()
3427 3427 n.user = user
3428 3428 n.repository = repository
3429 3429 n.permission = permission
3430 3430 Session().add(n)
3431 3431 return n
3432 3432
3433 3433 def __unicode__(self):
3434 3434 return u'<%s => %s >' % (self.user, self.repository)
3435 3435
3436 3436
3437 3437 class UserUserGroupToPerm(Base, BaseModel):
3438 3438 __tablename__ = 'user_user_group_to_perm'
3439 3439 __table_args__ = (
3440 3440 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3441 3441 base_table_args
3442 3442 )
3443 3443
3444 3444 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3445 3445 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3446 3446 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3447 3447 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3448 3448
3449 3449 user = relationship('User')
3450 3450 user_group = relationship('UserGroup')
3451 3451 permission = relationship('Permission')
3452 3452
3453 3453 @classmethod
3454 3454 def create(cls, user, user_group, permission):
3455 3455 n = cls()
3456 3456 n.user = user
3457 3457 n.user_group = user_group
3458 3458 n.permission = permission
3459 3459 Session().add(n)
3460 3460 return n
3461 3461
3462 3462 def __unicode__(self):
3463 3463 return u'<%s => %s >' % (self.user, self.user_group)
3464 3464
3465 3465
3466 3466 class UserToPerm(Base, BaseModel):
3467 3467 __tablename__ = 'user_to_perm'
3468 3468 __table_args__ = (
3469 3469 UniqueConstraint('user_id', 'permission_id'),
3470 3470 base_table_args
3471 3471 )
3472 3472
3473 3473 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3474 3474 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3475 3475 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3476 3476
3477 3477 user = relationship('User')
3478 3478 permission = relationship('Permission', lazy='joined')
3479 3479
3480 3480 def __unicode__(self):
3481 3481 return u'<%s => %s >' % (self.user, self.permission)
3482 3482
3483 3483
3484 3484 class UserGroupRepoToPerm(Base, BaseModel):
3485 3485 __tablename__ = 'users_group_repo_to_perm'
3486 3486 __table_args__ = (
3487 3487 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3488 3488 base_table_args
3489 3489 )
3490 3490
3491 3491 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3492 3492 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3493 3493 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3494 3494 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3495 3495
3496 3496 users_group = relationship('UserGroup')
3497 3497 permission = relationship('Permission')
3498 3498 repository = relationship('Repository')
3499 3499 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3500 3500
3501 3501 @classmethod
3502 3502 def create(cls, users_group, repository, permission):
3503 3503 n = cls()
3504 3504 n.users_group = users_group
3505 3505 n.repository = repository
3506 3506 n.permission = permission
3507 3507 Session().add(n)
3508 3508 return n
3509 3509
3510 3510 def __unicode__(self):
3511 3511 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3512 3512
3513 3513
3514 3514 class UserGroupUserGroupToPerm(Base, BaseModel):
3515 3515 __tablename__ = 'user_group_user_group_to_perm'
3516 3516 __table_args__ = (
3517 3517 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3518 3518 CheckConstraint('target_user_group_id != user_group_id'),
3519 3519 base_table_args
3520 3520 )
3521 3521
3522 3522 user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3523 3523 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3524 3524 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3525 3525 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3526 3526
3527 3527 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3528 3528 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3529 3529 permission = relationship('Permission')
3530 3530
3531 3531 @classmethod
3532 3532 def create(cls, target_user_group, user_group, permission):
3533 3533 n = cls()
3534 3534 n.target_user_group = target_user_group
3535 3535 n.user_group = user_group
3536 3536 n.permission = permission
3537 3537 Session().add(n)
3538 3538 return n
3539 3539
3540 3540 def __unicode__(self):
3541 3541 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3542 3542
3543 3543
3544 3544 class UserGroupToPerm(Base, BaseModel):
3545 3545 __tablename__ = 'users_group_to_perm'
3546 3546 __table_args__ = (
3547 3547 UniqueConstraint('users_group_id', 'permission_id',),
3548 3548 base_table_args
3549 3549 )
3550 3550
3551 3551 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3552 3552 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3553 3553 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3554 3554
3555 3555 users_group = relationship('UserGroup')
3556 3556 permission = relationship('Permission')
3557 3557
3558 3558
3559 3559 class UserRepoGroupToPerm(Base, BaseModel):
3560 3560 __tablename__ = 'user_repo_group_to_perm'
3561 3561 __table_args__ = (
3562 3562 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3563 3563 base_table_args
3564 3564 )
3565 3565
3566 3566 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3567 3567 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3568 3568 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3569 3569 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3570 3570
3571 3571 user = relationship('User')
3572 3572 group = relationship('RepoGroup')
3573 3573 permission = relationship('Permission')
3574 3574
3575 3575 @classmethod
3576 3576 def create(cls, user, repository_group, permission):
3577 3577 n = cls()
3578 3578 n.user = user
3579 3579 n.group = repository_group
3580 3580 n.permission = permission
3581 3581 Session().add(n)
3582 3582 return n
3583 3583
3584 3584
3585 3585 class UserGroupRepoGroupToPerm(Base, BaseModel):
3586 3586 __tablename__ = 'users_group_repo_group_to_perm'
3587 3587 __table_args__ = (
3588 3588 UniqueConstraint('users_group_id', 'group_id'),
3589 3589 base_table_args
3590 3590 )
3591 3591
3592 3592 users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3593 3593 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3594 3594 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3595 3595 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3596 3596
3597 3597 users_group = relationship('UserGroup')
3598 3598 permission = relationship('Permission')
3599 3599 group = relationship('RepoGroup')
3600 3600
3601 3601 @classmethod
3602 3602 def create(cls, user_group, repository_group, permission):
3603 3603 n = cls()
3604 3604 n.users_group = user_group
3605 3605 n.group = repository_group
3606 3606 n.permission = permission
3607 3607 Session().add(n)
3608 3608 return n
3609 3609
3610 3610 def __unicode__(self):
3611 3611 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3612 3612
3613 3613
3614 3614 class Statistics(Base, BaseModel):
3615 3615 __tablename__ = 'statistics'
3616 3616 __table_args__ = (
3617 3617 base_table_args
3618 3618 )
3619 3619
3620 3620 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3621 3621 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3622 3622 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3623 3623 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3624 3624 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3625 3625 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3626 3626
3627 3627 repository = relationship('Repository', single_parent=True)
3628 3628
3629 3629
3630 3630 class UserFollowing(Base, BaseModel):
3631 3631 __tablename__ = 'user_followings'
3632 3632 __table_args__ = (
3633 3633 UniqueConstraint('user_id', 'follows_repository_id'),
3634 3634 UniqueConstraint('user_id', 'follows_user_id'),
3635 3635 base_table_args
3636 3636 )
3637 3637
3638 3638 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3639 3639 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3640 3640 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3641 3641 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3642 3642 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3643 3643
3644 3644 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3645 3645
3646 3646 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3647 3647 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3648 3648
3649 3649 @classmethod
3650 3650 def get_repo_followers(cls, repo_id):
3651 3651 return cls.query().filter(cls.follows_repo_id == repo_id)
3652 3652
3653 3653
3654 3654 class CacheKey(Base, BaseModel):
3655 3655 __tablename__ = 'cache_invalidation'
3656 3656 __table_args__ = (
3657 3657 UniqueConstraint('cache_key'),
3658 3658 Index('key_idx', 'cache_key'),
3659 3659 Index('cache_args_idx', 'cache_args'),
3660 3660 base_table_args,
3661 3661 )
3662 3662
3663 3663 CACHE_TYPE_FEED = 'FEED'
3664 3664
3665 3665 # namespaces used to register process/thread aware caches
3666 3666 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3667 3667
3668 3668 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3669 3669 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3670 3670 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3671 3671 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3672 3672 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3673 3673
3674 3674 def __init__(self, cache_key, cache_args='', cache_state_uid=None):
3675 3675 self.cache_key = cache_key
3676 3676 self.cache_args = cache_args
3677 3677 self.cache_active = False
3678 3678 # first key should be same for all entries, since all workers should share it
3679 3679 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid()
3680 3680
3681 3681 def __unicode__(self):
3682 3682 return u"<%s('%s:%s[%s]')>" % (
3683 3683 self.__class__.__name__,
3684 3684 self.cache_id, self.cache_key, self.cache_active)
3685 3685
3686 3686 def _cache_key_partition(self):
3687 3687 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3688 3688 return prefix, repo_name, suffix
3689 3689
3690 3690 def get_prefix(self):
3691 3691 """
3692 3692 Try to extract prefix from existing cache key. The key could consist
3693 3693 of prefix, repo_name, suffix
3694 3694 """
3695 3695 # this returns prefix, repo_name, suffix
3696 3696 return self._cache_key_partition()[0]
3697 3697
3698 3698 def get_suffix(self):
3699 3699 """
3700 3700 get suffix that might have been used in _get_cache_key to
3701 3701 generate self.cache_key. Only used for informational purposes
3702 3702 in repo_edit.mako.
3703 3703 """
3704 3704 # prefix, repo_name, suffix
3705 3705 return self._cache_key_partition()[2]
3706 3706
3707 3707 @classmethod
3708 3708 def generate_new_state_uid(cls, based_on=None):
3709 3709 if based_on:
3710 3710 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3711 3711 else:
3712 3712 return str(uuid.uuid4())
3713 3713
3714 3714 @classmethod
3715 3715 def delete_all_cache(cls):
3716 3716 """
3717 3717 Delete all cache keys from database.
3718 3718 Should only be run when all instances are down and all entries
3719 3719 thus stale.
3720 3720 """
3721 3721 cls.query().delete()
3722 3722 Session().commit()
3723 3723
3724 3724 @classmethod
3725 3725 def set_invalidate(cls, cache_uid, delete=False):
3726 3726 """
3727 3727 Mark all caches of a repo as invalid in the database.
3728 3728 """
3729 3729
3730 3730 try:
3731 3731 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3732 3732 if delete:
3733 3733 qry.delete()
3734 3734 log.debug('cache objects deleted for cache args %s',
3735 3735 safe_str(cache_uid))
3736 3736 else:
3737 3737 qry.update({"cache_active": False,
3738 3738 "cache_state_uid": cls.generate_new_state_uid()})
3739 3739 log.debug('cache objects marked as invalid for cache args %s',
3740 3740 safe_str(cache_uid))
3741 3741
3742 3742 Session().commit()
3743 3743 except Exception:
3744 3744 log.exception(
3745 3745 'Cache key invalidation failed for cache args %s',
3746 3746 safe_str(cache_uid))
3747 3747 Session().rollback()
3748 3748
3749 3749 @classmethod
3750 3750 def get_active_cache(cls, cache_key):
3751 3751 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3752 3752 if inv_obj:
3753 3753 return inv_obj
3754 3754 return None
3755 3755
3756 3756 @classmethod
3757 3757 def get_namespace_map(cls, namespace):
3758 3758 return {
3759 3759 x.cache_key: x
3760 3760 for x in cls.query().filter(cls.cache_args == namespace)}
3761 3761
3762 3762
3763 3763 class ChangesetComment(Base, BaseModel):
3764 3764 __tablename__ = 'changeset_comments'
3765 3765 __table_args__ = (
3766 3766 Index('cc_revision_idx', 'revision'),
3767 3767 base_table_args,
3768 3768 )
3769 3769
3770 3770 COMMENT_OUTDATED = u'comment_outdated'
3771 3771 COMMENT_TYPE_NOTE = u'note'
3772 3772 COMMENT_TYPE_TODO = u'todo'
3773 3773 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3774 3774
3775 3775 OP_IMMUTABLE = u'immutable'
3776 3776 OP_CHANGEABLE = u'changeable'
3777 3777
3778 3778 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3779 3779 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3780 3780 revision = Column('revision', String(40), nullable=True)
3781 3781 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3782 3782 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3783 3783 line_no = Column('line_no', Unicode(10), nullable=True)
3784 3784 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3785 3785 f_path = Column('f_path', Unicode(1000), nullable=True)
3786 3786 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3787 3787 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3788 3788 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3789 3789 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3790 3790 renderer = Column('renderer', Unicode(64), nullable=True)
3791 3791 display_state = Column('display_state', Unicode(128), nullable=True)
3792 3792 immutable_state = Column('immutable_state', Unicode(128), nullable=True, default=OP_CHANGEABLE)
3793 3793 draft = Column('draft', Boolean(), nullable=True, default=False)
3794 3794
3795 3795 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3796 3796 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3797 3797
3798 3798 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3799 3799 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3800 3800
3801 3801 author = relationship('User', lazy='select')
3802 3802 repo = relationship('Repository')
3803 3803 status_change = relationship('ChangesetStatus', cascade="all, delete-orphan", lazy='select')
3804 3804 pull_request = relationship('PullRequest', lazy='select')
3805 3805 pull_request_version = relationship('PullRequestVersion', lazy='select')
3806 3806 history = relationship('ChangesetCommentHistory', cascade='all, delete-orphan', lazy='select', order_by='ChangesetCommentHistory.version')
3807 3807
3808 3808 @classmethod
3809 3809 def get_users(cls, revision=None, pull_request_id=None):
3810 3810 """
3811 3811 Returns user associated with this ChangesetComment. ie those
3812 3812 who actually commented
3813 3813
3814 3814 :param cls:
3815 3815 :param revision:
3816 3816 """
3817 3817 q = Session().query(User)\
3818 3818 .join(ChangesetComment.author)
3819 3819 if revision:
3820 3820 q = q.filter(cls.revision == revision)
3821 3821 elif pull_request_id:
3822 3822 q = q.filter(cls.pull_request_id == pull_request_id)
3823 3823 return q.all()
3824 3824
3825 3825 @classmethod
3826 3826 def get_index_from_version(cls, pr_version, versions=None, num_versions=None):
3827 3827
3828 3828 if versions is not None:
3829 3829 num_versions = [x.pull_request_version_id for x in versions]
3830 3830
3831 3831 num_versions = num_versions or []
3832 3832 try:
3833 3833 return num_versions.index(pr_version) + 1
3834 3834 except (IndexError, ValueError):
3835 3835 return
3836 3836
3837 3837 @property
3838 3838 def outdated(self):
3839 3839 return self.display_state == self.COMMENT_OUTDATED
3840 3840
3841 3841 @property
3842 3842 def outdated_js(self):
3843 3843 return json.dumps(self.display_state == self.COMMENT_OUTDATED)
3844 3844
3845 3845 @property
3846 3846 def immutable(self):
3847 3847 return self.immutable_state == self.OP_IMMUTABLE
3848 3848
3849 3849 def outdated_at_version(self, version):
3850 3850 """
3851 3851 Checks if comment is outdated for given pull request version
3852 3852 """
3853 3853 def version_check():
3854 3854 return self.pull_request_version_id and self.pull_request_version_id != version
3855 3855
3856 3856 if self.is_inline:
3857 3857 return self.outdated and version_check()
3858 3858 else:
3859 3859 # general comments don't have .outdated set, also latest don't have a version
3860 3860 return version_check()
3861 3861
3862 3862 def outdated_at_version_js(self, version):
3863 3863 """
3864 3864 Checks if comment is outdated for given pull request version
3865 3865 """
3866 3866 return json.dumps(self.outdated_at_version(version))
3867 3867
3868 3868 def older_than_version(self, version):
3869 3869 """
3870 3870 Checks if comment is made from previous version than given
3871 3871 """
3872 3872 if version is None:
3873 3873 return self.pull_request_version != version
3874 3874
3875 3875 return self.pull_request_version < version
3876 3876
3877 3877 def older_than_version_js(self, version):
3878 3878 """
3879 3879 Checks if comment is made from previous version than given
3880 3880 """
3881 3881 return json.dumps(self.older_than_version(version))
3882 3882
3883 3883 @property
3884 3884 def commit_id(self):
3885 3885 """New style naming to stop using .revision"""
3886 3886 return self.revision
3887 3887
3888 3888 @property
3889 3889 def resolved(self):
3890 3890 return self.resolved_by[0] if self.resolved_by else None
3891 3891
3892 3892 @property
3893 3893 def is_todo(self):
3894 3894 return self.comment_type == self.COMMENT_TYPE_TODO
3895 3895
3896 3896 @property
3897 3897 def is_inline(self):
3898 3898 if self.line_no and self.f_path:
3899 3899 return True
3900 3900 return False
3901 3901
3902 3902 @property
3903 3903 def last_version(self):
3904 3904 version = 0
3905 3905 if self.history:
3906 3906 version = self.history[-1].version
3907 3907 return version
3908 3908
3909 3909 def get_index_version(self, versions):
3910 3910 return self.get_index_from_version(
3911 3911 self.pull_request_version_id, versions)
3912 3912
3913 3913 @property
3914 3914 def review_status(self):
3915 3915 if self.status_change:
3916 3916 return self.status_change[0].status
3917 3917
3918 3918 @property
3919 3919 def review_status_lbl(self):
3920 3920 if self.status_change:
3921 3921 return self.status_change[0].status_lbl
3922 3922
3923 3923 def __repr__(self):
3924 3924 if self.comment_id:
3925 3925 return '<DB:Comment #%s>' % self.comment_id
3926 3926 else:
3927 3927 return '<DB:Comment at %#x>' % id(self)
3928 3928
3929 3929 def get_api_data(self):
3930 3930 comment = self
3931 3931
3932 3932 data = {
3933 3933 'comment_id': comment.comment_id,
3934 3934 'comment_type': comment.comment_type,
3935 3935 'comment_text': comment.text,
3936 3936 'comment_status': comment.status_change,
3937 3937 'comment_f_path': comment.f_path,
3938 3938 'comment_lineno': comment.line_no,
3939 3939 'comment_author': comment.author,
3940 3940 'comment_created_on': comment.created_on,
3941 3941 'comment_resolved_by': self.resolved,
3942 3942 'comment_commit_id': comment.revision,
3943 3943 'comment_pull_request_id': comment.pull_request_id,
3944 3944 'comment_last_version': self.last_version
3945 3945 }
3946 3946 return data
3947 3947
3948 3948 def __json__(self):
3949 3949 data = dict()
3950 3950 data.update(self.get_api_data())
3951 3951 return data
3952 3952
3953 3953
3954 3954 class ChangesetCommentHistory(Base, BaseModel):
3955 3955 __tablename__ = 'changeset_comments_history'
3956 3956 __table_args__ = (
3957 3957 Index('cch_comment_id_idx', 'comment_id'),
3958 3958 base_table_args,
3959 3959 )
3960 3960
3961 3961 comment_history_id = Column('comment_history_id', Integer(), nullable=False, primary_key=True)
3962 3962 comment_id = Column('comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=False)
3963 3963 version = Column("version", Integer(), nullable=False, default=0)
3964 3964 created_by_user_id = Column('created_by_user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3965 3965 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3966 3966 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3967 3967 deleted = Column('deleted', Boolean(), default=False)
3968 3968
3969 3969 author = relationship('User', lazy='joined')
3970 3970 comment = relationship('ChangesetComment', cascade="all, delete")
3971 3971
3972 3972 @classmethod
3973 3973 def get_version(cls, comment_id):
3974 3974 q = Session().query(ChangesetCommentHistory).filter(
3975 3975 ChangesetCommentHistory.comment_id == comment_id).order_by(ChangesetCommentHistory.version.desc())
3976 3976 if q.count() == 0:
3977 3977 return 1
3978 3978 elif q.count() >= q[0].version:
3979 3979 return q.count() + 1
3980 3980 else:
3981 3981 return q[0].version + 1
3982 3982
3983 3983
3984 3984 class ChangesetStatus(Base, BaseModel):
3985 3985 __tablename__ = 'changeset_statuses'
3986 3986 __table_args__ = (
3987 3987 Index('cs_revision_idx', 'revision'),
3988 3988 Index('cs_version_idx', 'version'),
3989 3989 UniqueConstraint('repo_id', 'revision', 'version'),
3990 3990 base_table_args
3991 3991 )
3992 3992
3993 3993 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3994 3994 STATUS_APPROVED = 'approved'
3995 3995 STATUS_REJECTED = 'rejected'
3996 3996 STATUS_UNDER_REVIEW = 'under_review'
3997 3997 CheckConstraint,
3998 3998 STATUSES = [
3999 3999 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
4000 4000 (STATUS_APPROVED, _("Approved")),
4001 4001 (STATUS_REJECTED, _("Rejected")),
4002 4002 (STATUS_UNDER_REVIEW, _("Under Review")),
4003 4003 ]
4004 4004
4005 4005 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
4006 4006 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
4007 4007 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
4008 4008 revision = Column('revision', String(40), nullable=False)
4009 4009 status = Column('status', String(128), nullable=False, default=DEFAULT)
4010 4010 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
4011 4011 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
4012 4012 version = Column('version', Integer(), nullable=False, default=0)
4013 4013 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
4014 4014
4015 4015 author = relationship('User', lazy='select')
4016 4016 repo = relationship('Repository', lazy='select')
4017 4017 comment = relationship('ChangesetComment', lazy='select')
4018 4018 pull_request = relationship('PullRequest', lazy='select')
4019 4019
4020 4020 def __unicode__(self):
4021 4021 return u"<%s('%s[v%s]:%s')>" % (
4022 4022 self.__class__.__name__,
4023 4023 self.status, self.version, self.author
4024 4024 )
4025 4025
4026 4026 @classmethod
4027 4027 def get_status_lbl(cls, value):
4028 4028 return dict(cls.STATUSES).get(value)
4029 4029
4030 4030 @property
4031 4031 def status_lbl(self):
4032 4032 return ChangesetStatus.get_status_lbl(self.status)
4033 4033
4034 4034 def get_api_data(self):
4035 4035 status = self
4036 4036 data = {
4037 4037 'status_id': status.changeset_status_id,
4038 4038 'status': status.status,
4039 4039 }
4040 4040 return data
4041 4041
4042 4042 def __json__(self):
4043 4043 data = dict()
4044 4044 data.update(self.get_api_data())
4045 4045 return data
4046 4046
4047 4047
4048 4048 class _SetState(object):
4049 4049 """
4050 4050 Context processor allowing changing state for sensitive operation such as
4051 4051 pull request update or merge
4052 4052 """
4053 4053
4054 4054 def __init__(self, pull_request, pr_state, back_state=None):
4055 4055 self._pr = pull_request
4056 4056 self._org_state = back_state or pull_request.pull_request_state
4057 4057 self._pr_state = pr_state
4058 4058 self._current_state = None
4059 4059
4060 4060 def __enter__(self):
4061 4061 log.debug('StateLock: entering set state context of pr %s, setting state to: `%s`',
4062 4062 self._pr, self._pr_state)
4063 4063 self.set_pr_state(self._pr_state)
4064 4064 return self
4065 4065
4066 4066 def __exit__(self, exc_type, exc_val, exc_tb):
4067 4067 if exc_val is not None or exc_type is not None:
4068 4068 log.error(traceback.format_exc(exc_tb))
4069 4069 return None
4070 4070
4071 4071 self.set_pr_state(self._org_state)
4072 4072 log.debug('StateLock: exiting set state context of pr %s, setting state to: `%s`',
4073 4073 self._pr, self._org_state)
4074 4074
4075 4075 @property
4076 4076 def state(self):
4077 4077 return self._current_state
4078 4078
4079 4079 def set_pr_state(self, pr_state):
4080 4080 try:
4081 4081 self._pr.pull_request_state = pr_state
4082 4082 Session().add(self._pr)
4083 4083 Session().commit()
4084 4084 self._current_state = pr_state
4085 4085 except Exception:
4086 4086 log.exception('Failed to set PullRequest %s state to %s', self._pr, pr_state)
4087 4087 raise
4088 4088
4089 4089
4090 4090 class _PullRequestBase(BaseModel):
4091 4091 """
4092 4092 Common attributes of pull request and version entries.
4093 4093 """
4094 4094
4095 4095 # .status values
4096 4096 STATUS_NEW = u'new'
4097 4097 STATUS_OPEN = u'open'
4098 4098 STATUS_CLOSED = u'closed'
4099 4099
4100 4100 # available states
4101 4101 STATE_CREATING = u'creating'
4102 4102 STATE_UPDATING = u'updating'
4103 4103 STATE_MERGING = u'merging'
4104 4104 STATE_CREATED = u'created'
4105 4105
4106 4106 title = Column('title', Unicode(255), nullable=True)
4107 4107 description = Column(
4108 4108 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
4109 4109 nullable=True)
4110 4110 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
4111 4111
4112 4112 # new/open/closed status of pull request (not approve/reject/etc)
4113 4113 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
4114 4114 created_on = Column(
4115 4115 'created_on', DateTime(timezone=False), nullable=False,
4116 4116 default=datetime.datetime.now)
4117 4117 updated_on = Column(
4118 4118 'updated_on', DateTime(timezone=False), nullable=False,
4119 4119 default=datetime.datetime.now)
4120 4120
4121 4121 pull_request_state = Column("pull_request_state", String(255), nullable=True)
4122 4122
4123 4123 @declared_attr
4124 4124 def user_id(cls):
4125 4125 return Column(
4126 4126 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
4127 4127 unique=None)
4128 4128
4129 4129 # 500 revisions max
4130 4130 _revisions = Column(
4131 4131 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
4132 4132
4133 4133 common_ancestor_id = Column('common_ancestor_id', Unicode(255), nullable=True)
4134 4134
4135 4135 @declared_attr
4136 4136 def source_repo_id(cls):
4137 4137 # TODO: dan: rename column to source_repo_id
4138 4138 return Column(
4139 4139 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4140 4140 nullable=False)
4141 4141
4142 4142 _source_ref = Column('org_ref', Unicode(255), nullable=False)
4143 4143
4144 4144 @hybrid_property
4145 4145 def source_ref(self):
4146 4146 return self._source_ref
4147 4147
4148 4148 @source_ref.setter
4149 4149 def source_ref(self, val):
4150 4150 parts = (val or '').split(':')
4151 4151 if len(parts) != 3:
4152 4152 raise ValueError(
4153 4153 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4154 4154 self._source_ref = safe_unicode(val)
4155 4155
4156 4156 _target_ref = Column('other_ref', Unicode(255), nullable=False)
4157 4157
4158 4158 @hybrid_property
4159 4159 def target_ref(self):
4160 4160 return self._target_ref
4161 4161
4162 4162 @target_ref.setter
4163 4163 def target_ref(self, val):
4164 4164 parts = (val or '').split(':')
4165 4165 if len(parts) != 3:
4166 4166 raise ValueError(
4167 4167 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4168 4168 self._target_ref = safe_unicode(val)
4169 4169
4170 4170 @declared_attr
4171 4171 def target_repo_id(cls):
4172 4172 # TODO: dan: rename column to target_repo_id
4173 4173 return Column(
4174 4174 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4175 4175 nullable=False)
4176 4176
4177 4177 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
4178 4178
4179 4179 # TODO: dan: rename column to last_merge_source_rev
4180 4180 _last_merge_source_rev = Column(
4181 4181 'last_merge_org_rev', String(40), nullable=True)
4182 4182 # TODO: dan: rename column to last_merge_target_rev
4183 4183 _last_merge_target_rev = Column(
4184 4184 'last_merge_other_rev', String(40), nullable=True)
4185 4185 _last_merge_status = Column('merge_status', Integer(), nullable=True)
4186 4186 last_merge_metadata = Column(
4187 4187 'last_merge_metadata', MutationObj.as_mutable(
4188 4188 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4189 4189
4190 4190 merge_rev = Column('merge_rev', String(40), nullable=True)
4191 4191
4192 4192 reviewer_data = Column(
4193 4193 'reviewer_data_json', MutationObj.as_mutable(
4194 4194 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4195 4195
4196 4196 @property
4197 4197 def reviewer_data_json(self):
4198 4198 return json.dumps(self.reviewer_data)
4199 4199
4200 4200 @property
4201 4201 def last_merge_metadata_parsed(self):
4202 4202 metadata = {}
4203 4203 if not self.last_merge_metadata:
4204 4204 return metadata
4205 4205
4206 4206 if hasattr(self.last_merge_metadata, 'de_coerce'):
4207 4207 for k, v in self.last_merge_metadata.de_coerce().items():
4208 4208 if k in ['target_ref', 'source_ref']:
4209 4209 metadata[k] = Reference(v['type'], v['name'], v['commit_id'])
4210 4210 else:
4211 4211 if hasattr(v, 'de_coerce'):
4212 4212 metadata[k] = v.de_coerce()
4213 4213 else:
4214 4214 metadata[k] = v
4215 4215 return metadata
4216 4216
4217 4217 @property
4218 4218 def work_in_progress(self):
4219 4219 """checks if pull request is work in progress by checking the title"""
4220 4220 title = self.title.upper()
4221 4221 if re.match(r'^(\[WIP\]\s*|WIP:\s*|WIP\s+)', title):
4222 4222 return True
4223 4223 return False
4224 4224
4225 4225 @property
4226 4226 def title_safe(self):
4227 4227 return self.title\
4228 4228 .replace('{', '{{')\
4229 4229 .replace('}', '}}')
4230 4230
4231 4231 @hybrid_property
4232 4232 def description_safe(self):
4233 4233 from rhodecode.lib import helpers as h
4234 4234 return h.escape(self.description)
4235 4235
4236 4236 @hybrid_property
4237 4237 def revisions(self):
4238 4238 return self._revisions.split(':') if self._revisions else []
4239 4239
4240 4240 @revisions.setter
4241 4241 def revisions(self, val):
4242 4242 self._revisions = u':'.join(val)
4243 4243
4244 4244 @hybrid_property
4245 4245 def last_merge_status(self):
4246 4246 return safe_int(self._last_merge_status)
4247 4247
4248 4248 @last_merge_status.setter
4249 4249 def last_merge_status(self, val):
4250 4250 self._last_merge_status = val
4251 4251
4252 4252 @declared_attr
4253 4253 def author(cls):
4254 4254 return relationship('User', lazy='joined')
4255 4255
4256 4256 @declared_attr
4257 4257 def source_repo(cls):
4258 4258 return relationship(
4259 4259 'Repository',
4260 4260 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
4261 4261
4262 4262 @property
4263 4263 def source_ref_parts(self):
4264 4264 return self.unicode_to_reference(self.source_ref)
4265 4265
4266 4266 @declared_attr
4267 4267 def target_repo(cls):
4268 4268 return relationship(
4269 4269 'Repository',
4270 4270 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
4271 4271
4272 4272 @property
4273 4273 def target_ref_parts(self):
4274 4274 return self.unicode_to_reference(self.target_ref)
4275 4275
4276 4276 @property
4277 4277 def shadow_merge_ref(self):
4278 4278 return self.unicode_to_reference(self._shadow_merge_ref)
4279 4279
4280 4280 @shadow_merge_ref.setter
4281 4281 def shadow_merge_ref(self, ref):
4282 4282 self._shadow_merge_ref = self.reference_to_unicode(ref)
4283 4283
4284 4284 @staticmethod
4285 4285 def unicode_to_reference(raw):
4286 4286 return unicode_to_reference(raw)
4287 4287
4288 4288 @staticmethod
4289 4289 def reference_to_unicode(ref):
4290 4290 return reference_to_unicode(ref)
4291 4291
4292 4292 def get_api_data(self, with_merge_state=True):
4293 4293 from rhodecode.model.pull_request import PullRequestModel
4294 4294
4295 4295 pull_request = self
4296 4296 if with_merge_state:
4297 4297 merge_response, merge_status, msg = \
4298 4298 PullRequestModel().merge_status(pull_request)
4299 4299 merge_state = {
4300 4300 'status': merge_status,
4301 4301 'message': safe_unicode(msg),
4302 4302 }
4303 4303 else:
4304 4304 merge_state = {'status': 'not_available',
4305 4305 'message': 'not_available'}
4306 4306
4307 4307 merge_data = {
4308 4308 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4309 4309 'reference': (
4310 4310 pull_request.shadow_merge_ref._asdict()
4311 4311 if pull_request.shadow_merge_ref else None),
4312 4312 }
4313 4313
4314 4314 data = {
4315 4315 'pull_request_id': pull_request.pull_request_id,
4316 4316 'url': PullRequestModel().get_url(pull_request),
4317 4317 'title': pull_request.title,
4318 4318 'description': pull_request.description,
4319 4319 'status': pull_request.status,
4320 4320 'state': pull_request.pull_request_state,
4321 4321 'created_on': pull_request.created_on,
4322 4322 'updated_on': pull_request.updated_on,
4323 4323 'commit_ids': pull_request.revisions,
4324 4324 'review_status': pull_request.calculated_review_status(),
4325 4325 'mergeable': merge_state,
4326 4326 'source': {
4327 4327 'clone_url': pull_request.source_repo.clone_url(),
4328 4328 'repository': pull_request.source_repo.repo_name,
4329 4329 'reference': {
4330 4330 'name': pull_request.source_ref_parts.name,
4331 4331 'type': pull_request.source_ref_parts.type,
4332 4332 'commit_id': pull_request.source_ref_parts.commit_id,
4333 4333 },
4334 4334 },
4335 4335 'target': {
4336 4336 'clone_url': pull_request.target_repo.clone_url(),
4337 4337 'repository': pull_request.target_repo.repo_name,
4338 4338 'reference': {
4339 4339 'name': pull_request.target_ref_parts.name,
4340 4340 'type': pull_request.target_ref_parts.type,
4341 4341 'commit_id': pull_request.target_ref_parts.commit_id,
4342 4342 },
4343 4343 },
4344 4344 'merge': merge_data,
4345 4345 'author': pull_request.author.get_api_data(include_secrets=False,
4346 4346 details='basic'),
4347 4347 'reviewers': [
4348 4348 {
4349 4349 'user': reviewer.get_api_data(include_secrets=False,
4350 4350 details='basic'),
4351 4351 'reasons': reasons,
4352 4352 'review_status': st[0][1].status if st else 'not_reviewed',
4353 4353 }
4354 4354 for obj, reviewer, reasons, mandatory, st in
4355 4355 pull_request.reviewers_statuses()
4356 4356 ]
4357 4357 }
4358 4358
4359 4359 return data
4360 4360
4361 4361 def set_state(self, pull_request_state, final_state=None):
4362 4362 """
4363 4363 # goes from initial state to updating to initial state.
4364 4364 # initial state can be changed by specifying back_state=
4365 4365 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4366 4366 pull_request.merge()
4367 4367
4368 4368 :param pull_request_state:
4369 4369 :param final_state:
4370 4370
4371 4371 """
4372 4372
4373 4373 return _SetState(self, pull_request_state, back_state=final_state)
4374 4374
4375 4375
4376 4376 class PullRequest(Base, _PullRequestBase):
4377 4377 __tablename__ = 'pull_requests'
4378 4378 __table_args__ = (
4379 4379 base_table_args,
4380 4380 )
4381 4381 LATEST_VER = 'latest'
4382 4382
4383 4383 pull_request_id = Column(
4384 4384 'pull_request_id', Integer(), nullable=False, primary_key=True)
4385 4385
4386 4386 def __repr__(self):
4387 4387 if self.pull_request_id:
4388 4388 return '<DB:PullRequest #%s>' % self.pull_request_id
4389 4389 else:
4390 4390 return '<DB:PullRequest at %#x>' % id(self)
4391 4391
4392 4392 reviewers = relationship('PullRequestReviewers', cascade="all, delete-orphan")
4393 4393 statuses = relationship('ChangesetStatus', cascade="all, delete-orphan")
4394 4394 comments = relationship('ChangesetComment', cascade="all, delete-orphan")
4395 4395 versions = relationship('PullRequestVersion', cascade="all, delete-orphan",
4396 4396 lazy='dynamic')
4397 4397
4398 4398 @classmethod
4399 4399 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4400 4400 internal_methods=None):
4401 4401
4402 4402 class PullRequestDisplay(object):
4403 4403 """
4404 4404 Special object wrapper for showing PullRequest data via Versions
4405 4405 It mimics PR object as close as possible. This is read only object
4406 4406 just for display
4407 4407 """
4408 4408
4409 4409 def __init__(self, attrs, internal=None):
4410 4410 self.attrs = attrs
4411 4411 # internal have priority over the given ones via attrs
4412 4412 self.internal = internal or ['versions']
4413 4413
4414 4414 def __getattr__(self, item):
4415 4415 if item in self.internal:
4416 4416 return getattr(self, item)
4417 4417 try:
4418 4418 return self.attrs[item]
4419 4419 except KeyError:
4420 4420 raise AttributeError(
4421 4421 '%s object has no attribute %s' % (self, item))
4422 4422
4423 4423 def __repr__(self):
4424 4424 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
4425 4425
4426 4426 def versions(self):
4427 4427 return pull_request_obj.versions.order_by(
4428 4428 PullRequestVersion.pull_request_version_id).all()
4429 4429
4430 4430 def is_closed(self):
4431 4431 return pull_request_obj.is_closed()
4432 4432
4433 4433 def is_state_changing(self):
4434 4434 return pull_request_obj.is_state_changing()
4435 4435
4436 4436 @property
4437 4437 def pull_request_version_id(self):
4438 4438 return getattr(pull_request_obj, 'pull_request_version_id', None)
4439 4439
4440 4440 @property
4441 4441 def pull_request_last_version(self):
4442 4442 return pull_request_obj.pull_request_last_version
4443 4443
4444 4444 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4445 4445
4446 4446 attrs.author = StrictAttributeDict(
4447 4447 pull_request_obj.author.get_api_data())
4448 4448 if pull_request_obj.target_repo:
4449 4449 attrs.target_repo = StrictAttributeDict(
4450 4450 pull_request_obj.target_repo.get_api_data())
4451 4451 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4452 4452
4453 4453 if pull_request_obj.source_repo:
4454 4454 attrs.source_repo = StrictAttributeDict(
4455 4455 pull_request_obj.source_repo.get_api_data())
4456 4456 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4457 4457
4458 4458 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4459 4459 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4460 4460 attrs.revisions = pull_request_obj.revisions
4461 4461 attrs.common_ancestor_id = pull_request_obj.common_ancestor_id
4462 4462 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4463 4463 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4464 4464 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4465 4465
4466 4466 return PullRequestDisplay(attrs, internal=internal_methods)
4467 4467
4468 4468 def is_closed(self):
4469 4469 return self.status == self.STATUS_CLOSED
4470 4470
4471 4471 def is_state_changing(self):
4472 4472 return self.pull_request_state != PullRequest.STATE_CREATED
4473 4473
4474 4474 def __json__(self):
4475 4475 return {
4476 4476 'revisions': self.revisions,
4477 4477 'versions': self.versions_count
4478 4478 }
4479 4479
4480 4480 def calculated_review_status(self):
4481 4481 from rhodecode.model.changeset_status import ChangesetStatusModel
4482 4482 return ChangesetStatusModel().calculated_review_status(self)
4483 4483
4484 4484 def reviewers_statuses(self, user=None):
4485 4485 from rhodecode.model.changeset_status import ChangesetStatusModel
4486 4486 return ChangesetStatusModel().reviewers_statuses(self, user=user)
4487 4487
4488 4488 def get_pull_request_reviewers(self, role=None):
4489 4489 qry = PullRequestReviewers.query()\
4490 4490 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)
4491 4491 if role:
4492 4492 qry = qry.filter(PullRequestReviewers.role == role)
4493 4493
4494 4494 return qry.all()
4495 4495
4496 4496 @property
4497 4497 def reviewers_count(self):
4498 4498 qry = PullRequestReviewers.query()\
4499 4499 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4500 4500 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_REVIEWER)
4501 4501 return qry.count()
4502 4502
4503 4503 @property
4504 4504 def observers_count(self):
4505 4505 qry = PullRequestReviewers.query()\
4506 4506 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4507 4507 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_OBSERVER)
4508 4508 return qry.count()
4509 4509
4510 4510 def observers(self):
4511 4511 qry = PullRequestReviewers.query()\
4512 4512 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4513 4513 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_OBSERVER)\
4514 4514 .all()
4515 4515
4516 4516 for entry in qry:
4517 4517 yield entry, entry.user
4518 4518
4519 4519 @property
4520 4520 def workspace_id(self):
4521 4521 from rhodecode.model.pull_request import PullRequestModel
4522 4522 return PullRequestModel()._workspace_id(self)
4523 4523
4524 4524 def get_shadow_repo(self):
4525 4525 workspace_id = self.workspace_id
4526 4526 shadow_repository_path = self.target_repo.get_shadow_repository_path(workspace_id)
4527 4527 if os.path.isdir(shadow_repository_path):
4528 4528 vcs_obj = self.target_repo.scm_instance()
4529 4529 return vcs_obj.get_shadow_instance(shadow_repository_path)
4530 4530
4531 4531 @property
4532 4532 def versions_count(self):
4533 4533 """
4534 4534 return number of versions this PR have, e.g a PR that once been
4535 4535 updated will have 2 versions
4536 4536 """
4537 4537 return self.versions.count() + 1
4538 4538
4539 4539 @property
4540 4540 def pull_request_last_version(self):
4541 4541 return self.versions_count
4542 4542
4543 4543
4544 4544 class PullRequestVersion(Base, _PullRequestBase):
4545 4545 __tablename__ = 'pull_request_versions'
4546 4546 __table_args__ = (
4547 4547 base_table_args,
4548 4548 )
4549 4549
4550 4550 pull_request_version_id = Column(
4551 4551 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
4552 4552 pull_request_id = Column(
4553 4553 'pull_request_id', Integer(),
4554 4554 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4555 4555 pull_request = relationship('PullRequest')
4556 4556
4557 4557 def __repr__(self):
4558 4558 if self.pull_request_version_id:
4559 4559 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
4560 4560 else:
4561 4561 return '<DB:PullRequestVersion at %#x>' % id(self)
4562 4562
4563 4563 @property
4564 4564 def reviewers(self):
4565 4565 return self.pull_request.reviewers
4566 4566 @property
4567 4567 def reviewers(self):
4568 4568 return self.pull_request.reviewers
4569 4569
4570 4570 @property
4571 4571 def versions(self):
4572 4572 return self.pull_request.versions
4573 4573
4574 4574 def is_closed(self):
4575 4575 # calculate from original
4576 4576 return self.pull_request.status == self.STATUS_CLOSED
4577 4577
4578 4578 def is_state_changing(self):
4579 4579 return self.pull_request.pull_request_state != PullRequest.STATE_CREATED
4580 4580
4581 4581 def calculated_review_status(self):
4582 4582 return self.pull_request.calculated_review_status()
4583 4583
4584 4584 def reviewers_statuses(self):
4585 4585 return self.pull_request.reviewers_statuses()
4586 4586
4587 4587 def observers(self):
4588 4588 return self.pull_request.observers()
4589 4589
4590 4590
4591 4591 class PullRequestReviewers(Base, BaseModel):
4592 4592 __tablename__ = 'pull_request_reviewers'
4593 4593 __table_args__ = (
4594 4594 base_table_args,
4595 4595 )
4596 4596 ROLE_REVIEWER = u'reviewer'
4597 4597 ROLE_OBSERVER = u'observer'
4598 4598 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
4599 4599
4600 4600 @hybrid_property
4601 4601 def reasons(self):
4602 4602 if not self._reasons:
4603 4603 return []
4604 4604 return self._reasons
4605 4605
4606 4606 @reasons.setter
4607 4607 def reasons(self, val):
4608 4608 val = val or []
4609 4609 if any(not isinstance(x, str) for x in val):
4610 4610 raise Exception('invalid reasons type, must be list of strings')
4611 4611 self._reasons = val
4612 4612
4613 4613 pull_requests_reviewers_id = Column(
4614 4614 'pull_requests_reviewers_id', Integer(), nullable=False,
4615 4615 primary_key=True)
4616 4616 pull_request_id = Column(
4617 4617 "pull_request_id", Integer(),
4618 4618 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4619 4619 user_id = Column(
4620 4620 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4621 4621 _reasons = Column(
4622 4622 'reason', MutationList.as_mutable(
4623 4623 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4624 4624
4625 4625 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4626 4626 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
4627 4627
4628 4628 user = relationship('User')
4629 4629 pull_request = relationship('PullRequest')
4630 4630
4631 4631 rule_data = Column(
4632 4632 'rule_data_json',
4633 4633 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4634 4634
4635 4635 def rule_user_group_data(self):
4636 4636 """
4637 4637 Returns the voting user group rule data for this reviewer
4638 4638 """
4639 4639
4640 4640 if self.rule_data and 'vote_rule' in self.rule_data:
4641 4641 user_group_data = {}
4642 4642 if 'rule_user_group_entry_id' in self.rule_data:
4643 4643 # means a group with voting rules !
4644 4644 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4645 4645 user_group_data['name'] = self.rule_data['rule_name']
4646 4646 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4647 4647
4648 4648 return user_group_data
4649 4649
4650 4650 @classmethod
4651 4651 def get_pull_request_reviewers(cls, pull_request_id, role=None):
4652 4652 qry = PullRequestReviewers.query()\
4653 4653 .filter(PullRequestReviewers.pull_request_id == pull_request_id)
4654 4654 if role:
4655 4655 qry = qry.filter(PullRequestReviewers.role == role)
4656 4656
4657 4657 return qry.all()
4658 4658
4659 4659 def __unicode__(self):
4660 4660 return u"<%s('id:%s')>" % (self.__class__.__name__,
4661 4661 self.pull_requests_reviewers_id)
4662 4662
4663 4663
4664 4664 class Notification(Base, BaseModel):
4665 4665 __tablename__ = 'notifications'
4666 4666 __table_args__ = (
4667 4667 Index('notification_type_idx', 'type'),
4668 4668 base_table_args,
4669 4669 )
4670 4670
4671 4671 TYPE_CHANGESET_COMMENT = u'cs_comment'
4672 4672 TYPE_MESSAGE = u'message'
4673 4673 TYPE_MENTION = u'mention'
4674 4674 TYPE_REGISTRATION = u'registration'
4675 4675 TYPE_PULL_REQUEST = u'pull_request'
4676 4676 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4677 4677 TYPE_PULL_REQUEST_UPDATE = u'pull_request_update'
4678 4678
4679 4679 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4680 4680 subject = Column('subject', Unicode(512), nullable=True)
4681 4681 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4682 4682 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4683 4683 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4684 4684 type_ = Column('type', Unicode(255))
4685 4685
4686 4686 created_by_user = relationship('User')
4687 4687 notifications_to_users = relationship('UserNotification', lazy='joined',
4688 4688 cascade="all, delete-orphan")
4689 4689
4690 4690 @property
4691 4691 def recipients(self):
4692 4692 return [x.user for x in UserNotification.query()\
4693 4693 .filter(UserNotification.notification == self)\
4694 4694 .order_by(UserNotification.user_id.asc()).all()]
4695 4695
4696 4696 @classmethod
4697 4697 def create(cls, created_by, subject, body, recipients, type_=None):
4698 4698 if type_ is None:
4699 4699 type_ = Notification.TYPE_MESSAGE
4700 4700
4701 4701 notification = cls()
4702 4702 notification.created_by_user = created_by
4703 4703 notification.subject = subject
4704 4704 notification.body = body
4705 4705 notification.type_ = type_
4706 4706 notification.created_on = datetime.datetime.now()
4707 4707
4708 4708 # For each recipient link the created notification to his account
4709 4709 for u in recipients:
4710 4710 assoc = UserNotification()
4711 4711 assoc.user_id = u.user_id
4712 4712 assoc.notification = notification
4713 4713
4714 4714 # if created_by is inside recipients mark his notification
4715 4715 # as read
4716 4716 if u.user_id == created_by.user_id:
4717 4717 assoc.read = True
4718 4718 Session().add(assoc)
4719 4719
4720 4720 Session().add(notification)
4721 4721
4722 4722 return notification
4723 4723
4724 4724
4725 4725 class UserNotification(Base, BaseModel):
4726 4726 __tablename__ = 'user_to_notification'
4727 4727 __table_args__ = (
4728 4728 UniqueConstraint('user_id', 'notification_id'),
4729 4729 base_table_args
4730 4730 )
4731 4731
4732 4732 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4733 4733 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4734 4734 read = Column('read', Boolean, default=False)
4735 4735 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4736 4736
4737 4737 user = relationship('User', lazy="joined")
4738 4738 notification = relationship('Notification', lazy="joined",
4739 4739 order_by=lambda: Notification.created_on.desc(),)
4740 4740
4741 4741 def mark_as_read(self):
4742 4742 self.read = True
4743 4743 Session().add(self)
4744 4744
4745 4745
4746 4746 class UserNotice(Base, BaseModel):
4747 4747 __tablename__ = 'user_notices'
4748 4748 __table_args__ = (
4749 4749 base_table_args
4750 4750 )
4751 4751
4752 4752 NOTIFICATION_TYPE_MESSAGE = 'message'
4753 4753 NOTIFICATION_TYPE_NOTICE = 'notice'
4754 4754
4755 4755 NOTIFICATION_LEVEL_INFO = 'info'
4756 4756 NOTIFICATION_LEVEL_WARNING = 'warning'
4757 4757 NOTIFICATION_LEVEL_ERROR = 'error'
4758 4758
4759 4759 user_notice_id = Column('gist_id', Integer(), primary_key=True)
4760 4760
4761 4761 notice_subject = Column('notice_subject', Unicode(512), nullable=True)
4762 4762 notice_body = Column('notice_body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4763 4763
4764 4764 notice_read = Column('notice_read', Boolean, default=False)
4765 4765
4766 4766 notification_level = Column('notification_level', String(1024), default=NOTIFICATION_LEVEL_INFO)
4767 4767 notification_type = Column('notification_type', String(1024), default=NOTIFICATION_TYPE_NOTICE)
4768 4768
4769 4769 notice_created_by = Column('notice_created_by', Integer(), ForeignKey('users.user_id'), nullable=True)
4770 4770 notice_created_on = Column('notice_created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4771 4771
4772 4772 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'))
4773 4773 user = relationship('User', lazy="joined", primaryjoin='User.user_id==UserNotice.user_id')
4774 4774
4775 4775 @classmethod
4776 4776 def create_for_user(cls, user, subject, body, notice_level=NOTIFICATION_LEVEL_INFO, allow_duplicate=False):
4777 4777
4778 4778 if notice_level not in [cls.NOTIFICATION_LEVEL_ERROR,
4779 4779 cls.NOTIFICATION_LEVEL_WARNING,
4780 4780 cls.NOTIFICATION_LEVEL_INFO]:
4781 4781 return
4782 4782
4783 4783 from rhodecode.model.user import UserModel
4784 4784 user = UserModel().get_user(user)
4785 4785
4786 4786 new_notice = UserNotice()
4787 4787 if not allow_duplicate:
4788 4788 existing_msg = UserNotice().query() \
4789 4789 .filter(UserNotice.user == user) \
4790 4790 .filter(UserNotice.notice_body == body) \
4791 4791 .filter(UserNotice.notice_read == false()) \
4792 4792 .scalar()
4793 4793 if existing_msg:
4794 4794 log.warning('Ignoring duplicate notice for user %s', user)
4795 4795 return
4796 4796
4797 4797 new_notice.user = user
4798 4798 new_notice.notice_subject = subject
4799 4799 new_notice.notice_body = body
4800 4800 new_notice.notification_level = notice_level
4801 4801 Session().add(new_notice)
4802 4802 Session().commit()
4803 4803
4804 4804
4805 4805 class Gist(Base, BaseModel):
4806 4806 __tablename__ = 'gists'
4807 4807 __table_args__ = (
4808 4808 Index('g_gist_access_id_idx', 'gist_access_id'),
4809 4809 Index('g_created_on_idx', 'created_on'),
4810 4810 base_table_args
4811 4811 )
4812 4812
4813 4813 GIST_PUBLIC = u'public'
4814 4814 GIST_PRIVATE = u'private'
4815 4815 DEFAULT_FILENAME = u'gistfile1.txt'
4816 4816
4817 4817 ACL_LEVEL_PUBLIC = u'acl_public'
4818 4818 ACL_LEVEL_PRIVATE = u'acl_private'
4819 4819
4820 4820 gist_id = Column('gist_id', Integer(), primary_key=True)
4821 4821 gist_access_id = Column('gist_access_id', Unicode(250))
4822 4822 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4823 4823 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4824 4824 gist_expires = Column('gist_expires', Float(53), nullable=False)
4825 4825 gist_type = Column('gist_type', Unicode(128), nullable=False)
4826 4826 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4827 4827 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4828 4828 acl_level = Column('acl_level', Unicode(128), nullable=True)
4829 4829
4830 4830 owner = relationship('User')
4831 4831
4832 4832 def __repr__(self):
4833 4833 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4834 4834
4835 4835 @hybrid_property
4836 4836 def description_safe(self):
4837 4837 from rhodecode.lib import helpers as h
4838 4838 return h.escape(self.gist_description)
4839 4839
4840 4840 @classmethod
4841 4841 def get_or_404(cls, id_):
4842 4842 from pyramid.httpexceptions import HTTPNotFound
4843 4843
4844 4844 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4845 4845 if not res:
4846 4846 log.debug('WARN: No DB entry with id %s', id_)
4847 4847 raise HTTPNotFound()
4848 4848 return res
4849 4849
4850 4850 @classmethod
4851 4851 def get_by_access_id(cls, gist_access_id):
4852 4852 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4853 4853
4854 4854 def gist_url(self):
4855 4855 from rhodecode.model.gist import GistModel
4856 4856 return GistModel().get_url(self)
4857 4857
4858 4858 @classmethod
4859 4859 def base_path(cls):
4860 4860 """
4861 4861 Returns base path when all gists are stored
4862 4862
4863 4863 :param cls:
4864 4864 """
4865 4865 from rhodecode.model.gist import GIST_STORE_LOC
4866 4866 q = Session().query(RhodeCodeUi)\
4867 4867 .filter(RhodeCodeUi.ui_key == URL_SEP)
4868 4868 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4869 4869 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4870 4870
4871 4871 def get_api_data(self):
4872 4872 """
4873 4873 Common function for generating gist related data for API
4874 4874 """
4875 4875 gist = self
4876 4876 data = {
4877 4877 'gist_id': gist.gist_id,
4878 4878 'type': gist.gist_type,
4879 4879 'access_id': gist.gist_access_id,
4880 4880 'description': gist.gist_description,
4881 4881 'url': gist.gist_url(),
4882 4882 'expires': gist.gist_expires,
4883 4883 'created_on': gist.created_on,
4884 4884 'modified_at': gist.modified_at,
4885 4885 'content': None,
4886 4886 'acl_level': gist.acl_level,
4887 4887 }
4888 4888 return data
4889 4889
4890 4890 def __json__(self):
4891 4891 data = dict(
4892 4892 )
4893 4893 data.update(self.get_api_data())
4894 4894 return data
4895 4895 # SCM functions
4896 4896
4897 4897 def scm_instance(self, **kwargs):
4898 4898 """
4899 4899 Get an instance of VCS Repository
4900 4900
4901 4901 :param kwargs:
4902 4902 """
4903 4903 from rhodecode.model.gist import GistModel
4904 4904 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4905 4905 return get_vcs_instance(
4906 4906 repo_path=safe_str(full_repo_path), create=False,
4907 4907 _vcs_alias=GistModel.vcs_backend)
4908 4908
4909 4909
4910 4910 class ExternalIdentity(Base, BaseModel):
4911 4911 __tablename__ = 'external_identities'
4912 4912 __table_args__ = (
4913 4913 Index('local_user_id_idx', 'local_user_id'),
4914 4914 Index('external_id_idx', 'external_id'),
4915 4915 base_table_args
4916 4916 )
4917 4917
4918 4918 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4919 4919 external_username = Column('external_username', Unicode(1024), default=u'')
4920 4920 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4921 4921 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4922 4922 access_token = Column('access_token', String(1024), default=u'')
4923 4923 alt_token = Column('alt_token', String(1024), default=u'')
4924 4924 token_secret = Column('token_secret', String(1024), default=u'')
4925 4925
4926 4926 @classmethod
4927 4927 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4928 4928 """
4929 4929 Returns ExternalIdentity instance based on search params
4930 4930
4931 4931 :param external_id:
4932 4932 :param provider_name:
4933 4933 :return: ExternalIdentity
4934 4934 """
4935 4935 query = cls.query()
4936 4936 query = query.filter(cls.external_id == external_id)
4937 4937 query = query.filter(cls.provider_name == provider_name)
4938 4938 if local_user_id:
4939 4939 query = query.filter(cls.local_user_id == local_user_id)
4940 4940 return query.first()
4941 4941
4942 4942 @classmethod
4943 4943 def user_by_external_id_and_provider(cls, external_id, provider_name):
4944 4944 """
4945 4945 Returns User instance based on search params
4946 4946
4947 4947 :param external_id:
4948 4948 :param provider_name:
4949 4949 :return: User
4950 4950 """
4951 4951 query = User.query()
4952 4952 query = query.filter(cls.external_id == external_id)
4953 4953 query = query.filter(cls.provider_name == provider_name)
4954 4954 query = query.filter(User.user_id == cls.local_user_id)
4955 4955 return query.first()
4956 4956
4957 4957 @classmethod
4958 4958 def by_local_user_id(cls, local_user_id):
4959 4959 """
4960 4960 Returns all tokens for user
4961 4961
4962 4962 :param local_user_id:
4963 4963 :return: ExternalIdentity
4964 4964 """
4965 4965 query = cls.query()
4966 4966 query = query.filter(cls.local_user_id == local_user_id)
4967 4967 return query
4968 4968
4969 4969 @classmethod
4970 4970 def load_provider_plugin(cls, plugin_id):
4971 4971 from rhodecode.authentication.base import loadplugin
4972 4972 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4973 4973 auth_plugin = loadplugin(_plugin_id)
4974 4974 return auth_plugin
4975 4975
4976 4976
4977 4977 class Integration(Base, BaseModel):
4978 4978 __tablename__ = 'integrations'
4979 4979 __table_args__ = (
4980 4980 base_table_args
4981 4981 )
4982 4982
4983 4983 integration_id = Column('integration_id', Integer(), primary_key=True)
4984 4984 integration_type = Column('integration_type', String(255))
4985 4985 enabled = Column('enabled', Boolean(), nullable=False)
4986 4986 name = Column('name', String(255), nullable=False)
4987 4987 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4988 4988 default=False)
4989 4989
4990 4990 settings = Column(
4991 4991 'settings_json', MutationObj.as_mutable(
4992 4992 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4993 4993 repo_id = Column(
4994 4994 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4995 4995 nullable=True, unique=None, default=None)
4996 4996 repo = relationship('Repository', lazy='joined')
4997 4997
4998 4998 repo_group_id = Column(
4999 4999 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
5000 5000 nullable=True, unique=None, default=None)
5001 5001 repo_group = relationship('RepoGroup', lazy='joined')
5002 5002
5003 5003 @property
5004 5004 def scope(self):
5005 5005 if self.repo:
5006 5006 return repr(self.repo)
5007 5007 if self.repo_group:
5008 5008 if self.child_repos_only:
5009 5009 return repr(self.repo_group) + ' (child repos only)'
5010 5010 else:
5011 5011 return repr(self.repo_group) + ' (recursive)'
5012 5012 if self.child_repos_only:
5013 5013 return 'root_repos'
5014 5014 return 'global'
5015 5015
5016 5016 def __repr__(self):
5017 5017 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
5018 5018
5019 5019
5020 5020 class RepoReviewRuleUser(Base, BaseModel):
5021 5021 __tablename__ = 'repo_review_rules_users'
5022 5022 __table_args__ = (
5023 5023 base_table_args
5024 5024 )
5025 5025 ROLE_REVIEWER = u'reviewer'
5026 5026 ROLE_OBSERVER = u'observer'
5027 5027 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
5028 5028
5029 5029 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
5030 5030 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
5031 5031 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
5032 5032 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
5033 5033 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
5034 5034 user = relationship('User')
5035 5035
5036 5036 def rule_data(self):
5037 5037 return {
5038 5038 'mandatory': self.mandatory,
5039 5039 'role': self.role,
5040 5040 }
5041 5041
5042 5042
5043 5043 class RepoReviewRuleUserGroup(Base, BaseModel):
5044 5044 __tablename__ = 'repo_review_rules_users_groups'
5045 5045 __table_args__ = (
5046 5046 base_table_args
5047 5047 )
5048 5048
5049 5049 VOTE_RULE_ALL = -1
5050 5050 ROLE_REVIEWER = u'reviewer'
5051 5051 ROLE_OBSERVER = u'observer'
5052 5052 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
5053 5053
5054 5054 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
5055 5055 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
5056 5056 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False)
5057 5057 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
5058 5058 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
5059 5059 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
5060 5060 users_group = relationship('UserGroup')
5061 5061
5062 5062 def rule_data(self):
5063 5063 return {
5064 5064 'mandatory': self.mandatory,
5065 5065 'role': self.role,
5066 5066 'vote_rule': self.vote_rule
5067 5067 }
5068 5068
5069 5069 @property
5070 5070 def vote_rule_label(self):
5071 5071 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
5072 5072 return 'all must vote'
5073 5073 else:
5074 5074 return 'min. vote {}'.format(self.vote_rule)
5075 5075
5076 5076
5077 5077 class RepoReviewRule(Base, BaseModel):
5078 5078 __tablename__ = 'repo_review_rules'
5079 5079 __table_args__ = (
5080 5080 base_table_args
5081 5081 )
5082 5082
5083 5083 repo_review_rule_id = Column(
5084 5084 'repo_review_rule_id', Integer(), primary_key=True)
5085 5085 repo_id = Column(
5086 5086 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
5087 5087 repo = relationship('Repository', backref='review_rules')
5088 5088
5089 5089 review_rule_name = Column('review_rule_name', String(255))
5090 5090 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
5091 5091 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
5092 5092 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
5093 5093
5094 5094 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
5095 5095
5096 5096 # Legacy fields, just for backward compat
5097 5097 _forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
5098 5098 _forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
5099 5099
5100 5100 pr_author = Column("pr_author", UnicodeText().with_variant(UnicodeText(255), 'mysql'), nullable=True)
5101 5101 commit_author = Column("commit_author", UnicodeText().with_variant(UnicodeText(255), 'mysql'), nullable=True)
5102 5102
5103 5103 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
5104 5104
5105 5105 rule_users = relationship('RepoReviewRuleUser')
5106 5106 rule_user_groups = relationship('RepoReviewRuleUserGroup')
5107 5107
5108 5108 def _validate_pattern(self, value):
5109 5109 re.compile('^' + glob2re(value) + '$')
5110 5110
5111 5111 @hybrid_property
5112 5112 def source_branch_pattern(self):
5113 5113 return self._branch_pattern or '*'
5114 5114
5115 5115 @source_branch_pattern.setter
5116 5116 def source_branch_pattern(self, value):
5117 5117 self._validate_pattern(value)
5118 5118 self._branch_pattern = value or '*'
5119 5119
5120 5120 @hybrid_property
5121 5121 def target_branch_pattern(self):
5122 5122 return self._target_branch_pattern or '*'
5123 5123
5124 5124 @target_branch_pattern.setter
5125 5125 def target_branch_pattern(self, value):
5126 5126 self._validate_pattern(value)
5127 5127 self._target_branch_pattern = value or '*'
5128 5128
5129 5129 @hybrid_property
5130 5130 def file_pattern(self):
5131 5131 return self._file_pattern or '*'
5132 5132
5133 5133 @file_pattern.setter
5134 5134 def file_pattern(self, value):
5135 5135 self._validate_pattern(value)
5136 5136 self._file_pattern = value or '*'
5137 5137
5138 5138 @hybrid_property
5139 5139 def forbid_pr_author_to_review(self):
5140 5140 return self.pr_author == 'forbid_pr_author'
5141 5141
5142 5142 @hybrid_property
5143 5143 def include_pr_author_to_review(self):
5144 5144 return self.pr_author == 'include_pr_author'
5145 5145
5146 5146 @hybrid_property
5147 5147 def forbid_commit_author_to_review(self):
5148 5148 return self.commit_author == 'forbid_commit_author'
5149 5149
5150 5150 @hybrid_property
5151 5151 def include_commit_author_to_review(self):
5152 5152 return self.commit_author == 'include_commit_author'
5153 5153
5154 5154 def matches(self, source_branch, target_branch, files_changed):
5155 5155 """
5156 5156 Check if this review rule matches a branch/files in a pull request
5157 5157
5158 5158 :param source_branch: source branch name for the commit
5159 5159 :param target_branch: target branch name for the commit
5160 5160 :param files_changed: list of file paths changed in the pull request
5161 5161 """
5162 5162
5163 5163 source_branch = source_branch or ''
5164 5164 target_branch = target_branch or ''
5165 5165 files_changed = files_changed or []
5166 5166
5167 5167 branch_matches = True
5168 5168 if source_branch or target_branch:
5169 5169 if self.source_branch_pattern == '*':
5170 5170 source_branch_match = True
5171 5171 else:
5172 5172 if self.source_branch_pattern.startswith('re:'):
5173 5173 source_pattern = self.source_branch_pattern[3:]
5174 5174 else:
5175 5175 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
5176 5176 source_branch_regex = re.compile(source_pattern)
5177 5177 source_branch_match = bool(source_branch_regex.search(source_branch))
5178 5178 if self.target_branch_pattern == '*':
5179 5179 target_branch_match = True
5180 5180 else:
5181 5181 if self.target_branch_pattern.startswith('re:'):
5182 5182 target_pattern = self.target_branch_pattern[3:]
5183 5183 else:
5184 5184 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
5185 5185 target_branch_regex = re.compile(target_pattern)
5186 5186 target_branch_match = bool(target_branch_regex.search(target_branch))
5187 5187
5188 5188 branch_matches = source_branch_match and target_branch_match
5189 5189
5190 5190 files_matches = True
5191 5191 if self.file_pattern != '*':
5192 5192 files_matches = False
5193 5193 if self.file_pattern.startswith('re:'):
5194 5194 file_pattern = self.file_pattern[3:]
5195 5195 else:
5196 5196 file_pattern = glob2re(self.file_pattern)
5197 5197 file_regex = re.compile(file_pattern)
5198 5198 for file_data in files_changed:
5199 5199 filename = file_data.get('filename')
5200 5200
5201 5201 if file_regex.search(filename):
5202 5202 files_matches = True
5203 5203 break
5204 5204
5205 5205 return branch_matches and files_matches
5206 5206
5207 5207 @property
5208 5208 def review_users(self):
5209 5209 """ Returns the users which this rule applies to """
5210 5210
5211 5211 users = collections.OrderedDict()
5212 5212
5213 5213 for rule_user in self.rule_users:
5214 5214 if rule_user.user.active:
5215 5215 if rule_user.user not in users:
5216 5216 users[rule_user.user.username] = {
5217 5217 'user': rule_user.user,
5218 5218 'source': 'user',
5219 5219 'source_data': {},
5220 5220 'data': rule_user.rule_data()
5221 5221 }
5222 5222
5223 5223 for rule_user_group in self.rule_user_groups:
5224 5224 source_data = {
5225 5225 'user_group_id': rule_user_group.users_group.users_group_id,
5226 5226 'name': rule_user_group.users_group.users_group_name,
5227 5227 'members': len(rule_user_group.users_group.members)
5228 5228 }
5229 5229 for member in rule_user_group.users_group.members:
5230 5230 if member.user.active:
5231 5231 key = member.user.username
5232 5232 if key in users:
5233 5233 # skip this member as we have him already
5234 5234 # this prevents from override the "first" matched
5235 5235 # users with duplicates in multiple groups
5236 5236 continue
5237 5237
5238 5238 users[key] = {
5239 5239 'user': member.user,
5240 5240 'source': 'user_group',
5241 5241 'source_data': source_data,
5242 5242 'data': rule_user_group.rule_data()
5243 5243 }
5244 5244
5245 5245 return users
5246 5246
5247 5247 def user_group_vote_rule(self, user_id):
5248 5248
5249 5249 rules = []
5250 5250 if not self.rule_user_groups:
5251 5251 return rules
5252 5252
5253 5253 for user_group in self.rule_user_groups:
5254 5254 user_group_members = [x.user_id for x in user_group.users_group.members]
5255 5255 if user_id in user_group_members:
5256 5256 rules.append(user_group)
5257 5257 return rules
5258 5258
5259 5259 def __repr__(self):
5260 5260 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
5261 5261 self.repo_review_rule_id, self.repo)
5262 5262
5263 5263
5264 5264 class ScheduleEntry(Base, BaseModel):
5265 5265 __tablename__ = 'schedule_entries'
5266 5266 __table_args__ = (
5267 5267 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
5268 5268 UniqueConstraint('task_uid', name='s_task_uid_idx'),
5269 5269 base_table_args,
5270 5270 )
5271 5271
5272 5272 schedule_types = ['crontab', 'timedelta', 'integer']
5273 5273 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
5274 5274
5275 5275 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
5276 5276 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
5277 5277 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
5278 5278
5279 5279 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
5280 5280 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
5281 5281
5282 5282 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
5283 5283 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
5284 5284
5285 5285 # task
5286 5286 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
5287 5287 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
5288 5288 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
5289 5289 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
5290 5290
5291 5291 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5292 5292 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
5293 5293
5294 5294 @hybrid_property
5295 5295 def schedule_type(self):
5296 5296 return self._schedule_type
5297 5297
5298 5298 @schedule_type.setter
5299 5299 def schedule_type(self, val):
5300 5300 if val not in self.schedule_types:
5301 5301 raise ValueError('Value must be on of `{}` and got `{}`'.format(
5302 5302 val, self.schedule_type))
5303 5303
5304 5304 self._schedule_type = val
5305 5305
5306 5306 @classmethod
5307 5307 def get_uid(cls, obj):
5308 5308 args = obj.task_args
5309 5309 kwargs = obj.task_kwargs
5310 5310 if isinstance(args, JsonRaw):
5311 5311 try:
5312 5312 args = json.loads(args)
5313 5313 except ValueError:
5314 5314 args = tuple()
5315 5315
5316 5316 if isinstance(kwargs, JsonRaw):
5317 5317 try:
5318 5318 kwargs = json.loads(kwargs)
5319 5319 except ValueError:
5320 5320 kwargs = dict()
5321 5321
5322 5322 dot_notation = obj.task_dot_notation
5323 5323 val = '.'.join(map(safe_str, [
5324 5324 sorted(dot_notation), args, sorted(kwargs.items())]))
5325 5325 return hashlib.sha1(val).hexdigest()
5326 5326
5327 5327 @classmethod
5328 5328 def get_by_schedule_name(cls, schedule_name):
5329 5329 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
5330 5330
5331 5331 @classmethod
5332 5332 def get_by_schedule_id(cls, schedule_id):
5333 5333 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
5334 5334
5335 5335 @property
5336 5336 def task(self):
5337 5337 return self.task_dot_notation
5338 5338
5339 5339 @property
5340 5340 def schedule(self):
5341 5341 from rhodecode.lib.celerylib.utils import raw_2_schedule
5342 5342 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
5343 5343 return schedule
5344 5344
5345 5345 @property
5346 5346 def args(self):
5347 5347 try:
5348 5348 return list(self.task_args or [])
5349 5349 except ValueError:
5350 5350 return list()
5351 5351
5352 5352 @property
5353 5353 def kwargs(self):
5354 5354 try:
5355 5355 return dict(self.task_kwargs or {})
5356 5356 except ValueError:
5357 5357 return dict()
5358 5358
5359 5359 def _as_raw(self, val, indent=None):
5360 5360 if hasattr(val, 'de_coerce'):
5361 5361 val = val.de_coerce()
5362 5362 if val:
5363 5363 val = json.dumps(val, indent=indent, sort_keys=True)
5364 5364
5365 5365 return val
5366 5366
5367 5367 @property
5368 5368 def schedule_definition_raw(self):
5369 5369 return self._as_raw(self.schedule_definition)
5370 5370
5371 5371 def args_raw(self, indent=None):
5372 5372 return self._as_raw(self.task_args, indent)
5373 5373
5374 5374 def kwargs_raw(self, indent=None):
5375 5375 return self._as_raw(self.task_kwargs, indent)
5376 5376
5377 5377 def __repr__(self):
5378 5378 return '<DB:ScheduleEntry({}:{})>'.format(
5379 5379 self.schedule_entry_id, self.schedule_name)
5380 5380
5381 5381
5382 5382 @event.listens_for(ScheduleEntry, 'before_update')
5383 5383 def update_task_uid(mapper, connection, target):
5384 5384 target.task_uid = ScheduleEntry.get_uid(target)
5385 5385
5386 5386
5387 5387 @event.listens_for(ScheduleEntry, 'before_insert')
5388 5388 def set_task_uid(mapper, connection, target):
5389 5389 target.task_uid = ScheduleEntry.get_uid(target)
5390 5390
5391 5391
5392 5392 class _BaseBranchPerms(BaseModel):
5393 5393 @classmethod
5394 5394 def compute_hash(cls, value):
5395 5395 return sha1_safe(value)
5396 5396
5397 5397 @hybrid_property
5398 5398 def branch_pattern(self):
5399 5399 return self._branch_pattern or '*'
5400 5400
5401 5401 @hybrid_property
5402 5402 def branch_hash(self):
5403 5403 return self._branch_hash
5404 5404
5405 5405 def _validate_glob(self, value):
5406 5406 re.compile('^' + glob2re(value) + '$')
5407 5407
5408 5408 @branch_pattern.setter
5409 5409 def branch_pattern(self, value):
5410 5410 self._validate_glob(value)
5411 5411 self._branch_pattern = value or '*'
5412 5412 # set the Hash when setting the branch pattern
5413 5413 self._branch_hash = self.compute_hash(self._branch_pattern)
5414 5414
5415 5415 def matches(self, branch):
5416 5416 """
5417 5417 Check if this the branch matches entry
5418 5418
5419 5419 :param branch: branch name for the commit
5420 5420 """
5421 5421
5422 5422 branch = branch or ''
5423 5423
5424 5424 branch_matches = True
5425 5425 if branch:
5426 5426 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
5427 5427 branch_matches = bool(branch_regex.search(branch))
5428 5428
5429 5429 return branch_matches
5430 5430
5431 5431
5432 5432 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
5433 5433 __tablename__ = 'user_to_repo_branch_permissions'
5434 5434 __table_args__ = (
5435 5435 base_table_args
5436 5436 )
5437 5437
5438 5438 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5439 5439
5440 5440 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5441 5441 repo = relationship('Repository', backref='user_branch_perms')
5442 5442
5443 5443 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5444 5444 permission = relationship('Permission')
5445 5445
5446 5446 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
5447 5447 user_repo_to_perm = relationship('UserRepoToPerm')
5448 5448
5449 5449 rule_order = Column('rule_order', Integer(), nullable=False)
5450 5450 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5451 5451 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5452 5452
5453 5453 def __unicode__(self):
5454 5454 return u'<UserBranchPermission(%s => %r)>' % (
5455 5455 self.user_repo_to_perm, self.branch_pattern)
5456 5456
5457 5457
5458 5458 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
5459 5459 __tablename__ = 'user_group_to_repo_branch_permissions'
5460 5460 __table_args__ = (
5461 5461 base_table_args
5462 5462 )
5463 5463
5464 5464 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5465 5465
5466 5466 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5467 5467 repo = relationship('Repository', backref='user_group_branch_perms')
5468 5468
5469 5469 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5470 5470 permission = relationship('Permission')
5471 5471
5472 5472 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('users_group_repo_to_perm.users_group_to_perm_id'), nullable=False, unique=None, default=None)
5473 5473 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
5474 5474
5475 5475 rule_order = Column('rule_order', Integer(), nullable=False)
5476 5476 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5477 5477 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5478 5478
5479 5479 def __unicode__(self):
5480 5480 return u'<UserBranchPermission(%s => %r)>' % (
5481 5481 self.user_group_repo_to_perm, self.branch_pattern)
5482 5482
5483 5483
5484 5484 class UserBookmark(Base, BaseModel):
5485 5485 __tablename__ = 'user_bookmarks'
5486 5486 __table_args__ = (
5487 5487 UniqueConstraint('user_id', 'bookmark_repo_id'),
5488 5488 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5489 5489 UniqueConstraint('user_id', 'bookmark_position'),
5490 5490 base_table_args
5491 5491 )
5492 5492
5493 5493 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5494 5494 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5495 5495 position = Column("bookmark_position", Integer(), nullable=False)
5496 5496 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5497 5497 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5498 5498 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5499 5499
5500 5500 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5501 5501 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5502 5502
5503 5503 user = relationship("User")
5504 5504
5505 5505 repository = relationship("Repository")
5506 5506 repository_group = relationship("RepoGroup")
5507 5507
5508 5508 @classmethod
5509 5509 def get_by_position_for_user(cls, position, user_id):
5510 5510 return cls.query() \
5511 5511 .filter(UserBookmark.user_id == user_id) \
5512 5512 .filter(UserBookmark.position == position).scalar()
5513 5513
5514 5514 @classmethod
5515 5515 def get_bookmarks_for_user(cls, user_id, cache=True):
5516 5516 bookmarks = cls.query() \
5517 5517 .filter(UserBookmark.user_id == user_id) \
5518 5518 .options(joinedload(UserBookmark.repository)) \
5519 5519 .options(joinedload(UserBookmark.repository_group)) \
5520 5520 .order_by(UserBookmark.position.asc())
5521 5521
5522 5522 if cache:
5523 5523 bookmarks = bookmarks.options(
5524 5524 FromCache("sql_cache_short", "get_user_{}_bookmarks".format(user_id))
5525 5525 )
5526 5526
5527 5527 return bookmarks.all()
5528 5528
5529 5529 def __unicode__(self):
5530 5530 return u'<UserBookmark(%s @ %r)>' % (self.position, self.redirect_url)
5531 5531
5532 5532
5533 5533 class FileStore(Base, BaseModel):
5534 5534 __tablename__ = 'file_store'
5535 5535 __table_args__ = (
5536 5536 base_table_args
5537 5537 )
5538 5538
5539 5539 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5540 5540 file_uid = Column('file_uid', String(1024), nullable=False)
5541 5541 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5542 5542 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5543 5543 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5544 5544
5545 5545 # sha256 hash
5546 5546 file_hash = Column('file_hash', String(512), nullable=False)
5547 5547 file_size = Column('file_size', BigInteger(), nullable=False)
5548 5548
5549 5549 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5550 5550 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5551 5551 accessed_count = Column('accessed_count', Integer(), default=0)
5552 5552
5553 5553 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5554 5554
5555 5555 # if repo/repo_group reference is set, check for permissions
5556 5556 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5557 5557
5558 5558 # hidden defines an attachment that should be hidden from showing in artifact listing
5559 5559 hidden = Column('hidden', Boolean(), nullable=False, default=False)
5560 5560
5561 5561 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5562 5562 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
5563 5563
5564 5564 file_metadata = relationship('FileStoreMetadata', lazy='joined')
5565 5565
5566 5566 # scope limited to user, which requester have access to
5567 5567 scope_user_id = Column(
5568 5568 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5569 5569 nullable=True, unique=None, default=None)
5570 5570 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
5571 5571
5572 5572 # scope limited to user group, which requester have access to
5573 5573 scope_user_group_id = Column(
5574 5574 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5575 5575 nullable=True, unique=None, default=None)
5576 5576 user_group = relationship('UserGroup', lazy='joined')
5577 5577
5578 5578 # scope limited to repo, which requester have access to
5579 5579 scope_repo_id = Column(
5580 5580 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5581 5581 nullable=True, unique=None, default=None)
5582 5582 repo = relationship('Repository', lazy='joined')
5583 5583
5584 5584 # scope limited to repo group, which requester have access to
5585 5585 scope_repo_group_id = Column(
5586 5586 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5587 5587 nullable=True, unique=None, default=None)
5588 5588 repo_group = relationship('RepoGroup', lazy='joined')
5589 5589
5590 5590 @classmethod
5591 5591 def get_by_store_uid(cls, file_store_uid, safe=False):
5592 5592 if safe:
5593 5593 return FileStore.query().filter(FileStore.file_uid == file_store_uid).first()
5594 5594 else:
5595 5595 return FileStore.query().filter(FileStore.file_uid == file_store_uid).scalar()
5596 5596
5597 5597 @classmethod
5598 5598 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5599 5599 file_description='', enabled=True, hidden=False, check_acl=True,
5600 5600 user_id=None, scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5601 5601
5602 5602 store_entry = FileStore()
5603 5603 store_entry.file_uid = file_uid
5604 5604 store_entry.file_display_name = file_display_name
5605 5605 store_entry.file_org_name = filename
5606 5606 store_entry.file_size = file_size
5607 5607 store_entry.file_hash = file_hash
5608 5608 store_entry.file_description = file_description
5609 5609
5610 5610 store_entry.check_acl = check_acl
5611 5611 store_entry.enabled = enabled
5612 5612 store_entry.hidden = hidden
5613 5613
5614 5614 store_entry.user_id = user_id
5615 5615 store_entry.scope_user_id = scope_user_id
5616 5616 store_entry.scope_repo_id = scope_repo_id
5617 5617 store_entry.scope_repo_group_id = scope_repo_group_id
5618 5618
5619 5619 return store_entry
5620 5620
5621 5621 @classmethod
5622 5622 def store_metadata(cls, file_store_id, args, commit=True):
5623 5623 file_store = FileStore.get(file_store_id)
5624 5624 if file_store is None:
5625 5625 return
5626 5626
5627 5627 for section, key, value, value_type in args:
5628 5628 has_key = FileStoreMetadata().query() \
5629 5629 .filter(FileStoreMetadata.file_store_id == file_store.file_store_id) \
5630 5630 .filter(FileStoreMetadata.file_store_meta_section == section) \
5631 5631 .filter(FileStoreMetadata.file_store_meta_key == key) \
5632 5632 .scalar()
5633 5633 if has_key:
5634 5634 msg = 'key `{}` already defined under section `{}` for this file.'\
5635 5635 .format(key, section)
5636 5636 raise ArtifactMetadataDuplicate(msg, err_section=section, err_key=key)
5637 5637
5638 5638 # NOTE(marcink): raises ArtifactMetadataBadValueType
5639 5639 FileStoreMetadata.valid_value_type(value_type)
5640 5640
5641 5641 meta_entry = FileStoreMetadata()
5642 5642 meta_entry.file_store = file_store
5643 5643 meta_entry.file_store_meta_section = section
5644 5644 meta_entry.file_store_meta_key = key
5645 5645 meta_entry.file_store_meta_value_type = value_type
5646 5646 meta_entry.file_store_meta_value = value
5647 5647
5648 5648 Session().add(meta_entry)
5649 5649
5650 5650 try:
5651 5651 if commit:
5652 5652 Session().commit()
5653 5653 except IntegrityError:
5654 5654 Session().rollback()
5655 5655 raise ArtifactMetadataDuplicate('Duplicate section/key found for this file.')
5656 5656
5657 5657 @classmethod
5658 5658 def bump_access_counter(cls, file_uid, commit=True):
5659 5659 FileStore().query()\
5660 5660 .filter(FileStore.file_uid == file_uid)\
5661 5661 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5662 5662 FileStore.accessed_on: datetime.datetime.now()})
5663 5663 if commit:
5664 5664 Session().commit()
5665 5665
5666 5666 def __json__(self):
5667 5667 data = {
5668 5668 'filename': self.file_display_name,
5669 5669 'filename_org': self.file_org_name,
5670 5670 'file_uid': self.file_uid,
5671 5671 'description': self.file_description,
5672 5672 'hidden': self.hidden,
5673 5673 'size': self.file_size,
5674 5674 'created_on': self.created_on,
5675 5675 'uploaded_by': self.upload_user.get_api_data(details='basic'),
5676 5676 'downloaded_times': self.accessed_count,
5677 5677 'sha256': self.file_hash,
5678 5678 'metadata': self.file_metadata,
5679 5679 }
5680 5680
5681 5681 return data
5682 5682
5683 5683 def __repr__(self):
5684 5684 return '<FileStore({})>'.format(self.file_store_id)
5685 5685
5686 5686
5687 5687 class FileStoreMetadata(Base, BaseModel):
5688 5688 __tablename__ = 'file_store_metadata'
5689 5689 __table_args__ = (
5690 5690 UniqueConstraint('file_store_id', 'file_store_meta_section_hash', 'file_store_meta_key_hash'),
5691 5691 Index('file_store_meta_section_idx', 'file_store_meta_section', mysql_length=255),
5692 5692 Index('file_store_meta_key_idx', 'file_store_meta_key', mysql_length=255),
5693 5693 base_table_args
5694 5694 )
5695 5695 SETTINGS_TYPES = {
5696 5696 'str': safe_str,
5697 5697 'int': safe_int,
5698 5698 'unicode': safe_unicode,
5699 5699 'bool': str2bool,
5700 5700 'list': functools.partial(aslist, sep=',')
5701 5701 }
5702 5702
5703 5703 file_store_meta_id = Column(
5704 5704 "file_store_meta_id", Integer(), nullable=False, unique=True, default=None,
5705 5705 primary_key=True)
5706 5706 _file_store_meta_section = Column(
5707 5707 "file_store_meta_section", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5708 5708 nullable=True, unique=None, default=None)
5709 5709 _file_store_meta_section_hash = Column(
5710 5710 "file_store_meta_section_hash", String(255),
5711 5711 nullable=True, unique=None, default=None)
5712 5712 _file_store_meta_key = Column(
5713 5713 "file_store_meta_key", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5714 5714 nullable=True, unique=None, default=None)
5715 5715 _file_store_meta_key_hash = Column(
5716 5716 "file_store_meta_key_hash", String(255), nullable=True, unique=None, default=None)
5717 5717 _file_store_meta_value = Column(
5718 5718 "file_store_meta_value", UnicodeText().with_variant(UnicodeText(20480), 'mysql'),
5719 5719 nullable=True, unique=None, default=None)
5720 5720 _file_store_meta_value_type = Column(
5721 5721 "file_store_meta_value_type", String(255), nullable=True, unique=None,
5722 5722 default='unicode')
5723 5723
5724 5724 file_store_id = Column(
5725 5725 'file_store_id', Integer(), ForeignKey('file_store.file_store_id'),
5726 5726 nullable=True, unique=None, default=None)
5727 5727
5728 5728 file_store = relationship('FileStore', lazy='joined')
5729 5729
5730 5730 @classmethod
5731 5731 def valid_value_type(cls, value):
5732 5732 if value.split('.')[0] not in cls.SETTINGS_TYPES:
5733 5733 raise ArtifactMetadataBadValueType(
5734 5734 'value_type must be one of %s got %s' % (cls.SETTINGS_TYPES.keys(), value))
5735 5735
5736 5736 @hybrid_property
5737 5737 def file_store_meta_section(self):
5738 5738 return self._file_store_meta_section
5739 5739
5740 5740 @file_store_meta_section.setter
5741 5741 def file_store_meta_section(self, value):
5742 5742 self._file_store_meta_section = value
5743 5743 self._file_store_meta_section_hash = _hash_key(value)
5744 5744
5745 5745 @hybrid_property
5746 5746 def file_store_meta_key(self):
5747 5747 return self._file_store_meta_key
5748 5748
5749 5749 @file_store_meta_key.setter
5750 5750 def file_store_meta_key(self, value):
5751 5751 self._file_store_meta_key = value
5752 5752 self._file_store_meta_key_hash = _hash_key(value)
5753 5753
5754 5754 @hybrid_property
5755 5755 def file_store_meta_value(self):
5756 5756 val = self._file_store_meta_value
5757 5757
5758 5758 if self._file_store_meta_value_type:
5759 5759 # e.g unicode.encrypted == unicode
5760 5760 _type = self._file_store_meta_value_type.split('.')[0]
5761 5761 # decode the encrypted value if it's encrypted field type
5762 5762 if '.encrypted' in self._file_store_meta_value_type:
5763 5763 cipher = EncryptedTextValue()
5764 5764 val = safe_unicode(cipher.process_result_value(val, None))
5765 5765 # do final type conversion
5766 5766 converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
5767 5767 val = converter(val)
5768 5768
5769 5769 return val
5770 5770
5771 5771 @file_store_meta_value.setter
5772 5772 def file_store_meta_value(self, val):
5773 5773 val = safe_unicode(val)
5774 5774 # encode the encrypted value
5775 5775 if '.encrypted' in self.file_store_meta_value_type:
5776 5776 cipher = EncryptedTextValue()
5777 5777 val = safe_unicode(cipher.process_bind_param(val, None))
5778 5778 self._file_store_meta_value = val
5779 5779
5780 5780 @hybrid_property
5781 5781 def file_store_meta_value_type(self):
5782 5782 return self._file_store_meta_value_type
5783 5783
5784 5784 @file_store_meta_value_type.setter
5785 5785 def file_store_meta_value_type(self, val):
5786 5786 # e.g unicode.encrypted
5787 5787 self.valid_value_type(val)
5788 5788 self._file_store_meta_value_type = val
5789 5789
5790 5790 def __json__(self):
5791 5791 data = {
5792 5792 'artifact': self.file_store.file_uid,
5793 5793 'section': self.file_store_meta_section,
5794 5794 'key': self.file_store_meta_key,
5795 5795 'value': self.file_store_meta_value,
5796 5796 }
5797 5797
5798 5798 return data
5799 5799
5800 5800 def __repr__(self):
5801 5801 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.file_store_meta_section,
5802 5802 self.file_store_meta_key, self.file_store_meta_value)
5803 5803
5804 5804
5805 5805 class DbMigrateVersion(Base, BaseModel):
5806 5806 __tablename__ = 'db_migrate_version'
5807 5807 __table_args__ = (
5808 5808 base_table_args,
5809 5809 )
5810 5810
5811 5811 repository_id = Column('repository_id', String(250), primary_key=True)
5812 5812 repository_path = Column('repository_path', Text)
5813 5813 version = Column('version', Integer)
5814 5814
5815 5815 @classmethod
5816 5816 def set_version(cls, version):
5817 5817 """
5818 5818 Helper for forcing a different version, usually for debugging purposes via ishell.
5819 5819 """
5820 5820 ver = DbMigrateVersion.query().first()
5821 5821 ver.version = version
5822 5822 Session().commit()
5823 5823
5824 5824
5825 5825 class DbSession(Base, BaseModel):
5826 5826 __tablename__ = 'db_session'
5827 5827 __table_args__ = (
5828 5828 base_table_args,
5829 5829 )
5830 5830
5831 5831 def __repr__(self):
5832 5832 return '<DB:DbSession({})>'.format(self.id)
5833 5833
5834 5834 id = Column('id', Integer())
5835 5835 namespace = Column('namespace', String(255), primary_key=True)
5836 5836 accessed = Column('accessed', DateTime, nullable=False)
5837 5837 created = Column('created', DateTime, nullable=False)
5838 5838 data = Column('data', PickleType, nullable=False)
@@ -1,918 +1,918 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2020 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import os
22 22 import re
23 23 import hashlib
24 24 import logging
25 25 import time
26 26 from collections import namedtuple
27 27 from functools import wraps
28 28 import bleach
29 29 from pyramid.threadlocal import get_current_request, get_current_registry
30 30
31 31 from rhodecode.lib import rc_cache
32 32 from rhodecode.lib.utils2 import (
33 33 Optional, AttributeDict, safe_str, remove_prefix, str2bool)
34 34 from rhodecode.lib.vcs.backends import base
35 35 from rhodecode.lib.statsd_client import StatsdClient
36 36 from rhodecode.model import BaseModel
37 37 from rhodecode.model.db import (
38 38 RepoRhodeCodeUi, RepoRhodeCodeSetting, RhodeCodeUi, RhodeCodeSetting)
39 39 from rhodecode.model.meta import Session
40 40
41 41
42 42 log = logging.getLogger(__name__)
43 43
44 44
45 45 UiSetting = namedtuple(
46 46 'UiSetting', ['section', 'key', 'value', 'active'])
47 47
48 48 SOCIAL_PLUGINS_LIST = ['github', 'bitbucket', 'twitter', 'google']
49 49
50 50
51 51 class SettingNotFound(Exception):
52 52 def __init__(self, setting_id):
53 53 msg = 'Setting `{}` is not found'.format(setting_id)
54 54 super(SettingNotFound, self).__init__(msg)
55 55
56 56
57 57 class SettingsModel(BaseModel):
58 58 BUILTIN_HOOKS = (
59 59 RhodeCodeUi.HOOK_REPO_SIZE, RhodeCodeUi.HOOK_PUSH,
60 60 RhodeCodeUi.HOOK_PRE_PUSH, RhodeCodeUi.HOOK_PRETX_PUSH,
61 61 RhodeCodeUi.HOOK_PULL, RhodeCodeUi.HOOK_PRE_PULL,
62 62 RhodeCodeUi.HOOK_PUSH_KEY,)
63 63 HOOKS_SECTION = 'hooks'
64 64
65 65 def __init__(self, sa=None, repo=None):
66 66 self.repo = repo
67 67 self.UiDbModel = RepoRhodeCodeUi if repo else RhodeCodeUi
68 68 self.SettingsDbModel = (
69 69 RepoRhodeCodeSetting if repo else RhodeCodeSetting)
70 70 super(SettingsModel, self).__init__(sa)
71 71
72 72 def get_ui_by_key(self, key):
73 73 q = self.UiDbModel.query()
74 74 q = q.filter(self.UiDbModel.ui_key == key)
75 75 q = self._filter_by_repo(RepoRhodeCodeUi, q)
76 76 return q.scalar()
77 77
78 78 def get_ui_by_section(self, section):
79 79 q = self.UiDbModel.query()
80 80 q = q.filter(self.UiDbModel.ui_section == section)
81 81 q = self._filter_by_repo(RepoRhodeCodeUi, q)
82 82 return q.all()
83 83
84 84 def get_ui_by_section_and_key(self, section, key):
85 85 q = self.UiDbModel.query()
86 86 q = q.filter(self.UiDbModel.ui_section == section)
87 87 q = q.filter(self.UiDbModel.ui_key == key)
88 88 q = self._filter_by_repo(RepoRhodeCodeUi, q)
89 89 return q.scalar()
90 90
91 91 def get_ui(self, section=None, key=None):
92 92 q = self.UiDbModel.query()
93 93 q = self._filter_by_repo(RepoRhodeCodeUi, q)
94 94
95 95 if section:
96 96 q = q.filter(self.UiDbModel.ui_section == section)
97 97 if key:
98 98 q = q.filter(self.UiDbModel.ui_key == key)
99 99
100 100 # TODO: mikhail: add caching
101 101 result = [
102 102 UiSetting(
103 103 section=safe_str(r.ui_section), key=safe_str(r.ui_key),
104 104 value=safe_str(r.ui_value), active=r.ui_active
105 105 )
106 106 for r in q.all()
107 107 ]
108 108 return result
109 109
110 110 def get_builtin_hooks(self):
111 111 q = self.UiDbModel.query()
112 112 q = q.filter(self.UiDbModel.ui_key.in_(self.BUILTIN_HOOKS))
113 113 return self._get_hooks(q)
114 114
115 115 def get_custom_hooks(self):
116 116 q = self.UiDbModel.query()
117 117 q = q.filter(~self.UiDbModel.ui_key.in_(self.BUILTIN_HOOKS))
118 118 return self._get_hooks(q)
119 119
120 120 def create_ui_section_value(self, section, val, key=None, active=True):
121 121 new_ui = self.UiDbModel()
122 122 new_ui.ui_section = section
123 123 new_ui.ui_value = val
124 124 new_ui.ui_active = active
125 125
126 126 repository_id = ''
127 127 if self.repo:
128 128 repo = self._get_repo(self.repo)
129 129 repository_id = repo.repo_id
130 130 new_ui.repository_id = repository_id
131 131
132 132 if not key:
133 133 # keys are unique so they need appended info
134 134 if self.repo:
135 135 key = hashlib.sha1(
136 136 '{}{}{}'.format(section, val, repository_id)).hexdigest()
137 137 else:
138 138 key = hashlib.sha1('{}{}'.format(section, val)).hexdigest()
139 139
140 140 new_ui.ui_key = key
141 141
142 142 Session().add(new_ui)
143 143 return new_ui
144 144
145 145 def create_or_update_hook(self, key, value):
146 146 ui = (
147 147 self.get_ui_by_section_and_key(self.HOOKS_SECTION, key) or
148 148 self.UiDbModel())
149 149 ui.ui_section = self.HOOKS_SECTION
150 150 ui.ui_active = True
151 151 ui.ui_key = key
152 152 ui.ui_value = value
153 153
154 154 if self.repo:
155 155 repo = self._get_repo(self.repo)
156 156 repository_id = repo.repo_id
157 157 ui.repository_id = repository_id
158 158
159 159 Session().add(ui)
160 160 return ui
161 161
162 162 def delete_ui(self, id_):
163 163 ui = self.UiDbModel.get(id_)
164 164 if not ui:
165 165 raise SettingNotFound(id_)
166 166 Session().delete(ui)
167 167
168 168 def get_setting_by_name(self, name):
169 169 q = self._get_settings_query()
170 170 q = q.filter(self.SettingsDbModel.app_settings_name == name)
171 171 return q.scalar()
172 172
173 173 def create_or_update_setting(
174 174 self, name, val=Optional(''), type_=Optional('unicode')):
175 175 """
176 176 Creates or updates RhodeCode setting. If updates is triggered it will
177 177 only update parameters that are explicitly set Optional instance will
178 178 be skipped
179 179
180 180 :param name:
181 181 :param val:
182 182 :param type_:
183 183 :return:
184 184 """
185 185
186 186 res = self.get_setting_by_name(name)
187 187 repo = self._get_repo(self.repo) if self.repo else None
188 188
189 189 if not res:
190 190 val = Optional.extract(val)
191 191 type_ = Optional.extract(type_)
192 192
193 193 args = (
194 194 (repo.repo_id, name, val, type_)
195 195 if repo else (name, val, type_))
196 196 res = self.SettingsDbModel(*args)
197 197
198 198 else:
199 199 if self.repo:
200 200 res.repository_id = repo.repo_id
201 201
202 202 res.app_settings_name = name
203 203 if not isinstance(type_, Optional):
204 204 # update if set
205 205 res.app_settings_type = type_
206 206 if not isinstance(val, Optional):
207 207 # update if set
208 208 res.app_settings_value = val
209 209
210 210 Session().add(res)
211 211 return res
212 212
213 213 def get_cache_region(self):
214 214 repo = self._get_repo(self.repo) if self.repo else None
215 215 cache_key = "repo.{}".format(repo.repo_id) if repo else "general_settings"
216 216 cache_namespace_uid = 'cache_settings.{}'.format(cache_key)
217 217 region = rc_cache.get_or_create_region('cache_general', cache_namespace_uid)
218 218 return region, cache_key
219 219
220 220 def invalidate_settings_cache(self):
221 221 region, cache_key = self.get_cache_region()
222 222 log.debug('Invalidation cache region %s for cache_key: %s', region, cache_key)
223 223 region.invalidate()
224 224
225 225 def get_all_settings(self, cache=False, from_request=True):
226 226 # defines if we use GLOBAL, or PER_REPO
227 227 repo = self._get_repo(self.repo) if self.repo else None
228 228
229 229 # initially try the requests context, this is the fastest
230 230 # we only fetch global config
231 231 if from_request:
232 232 request = get_current_request()
233 233
234 234 if request and not repo and hasattr(request, 'call_context') and hasattr(request.call_context, 'rc_config'):
235 235 rc_config = request.call_context.rc_config
236 236 if rc_config:
237 237 return rc_config
238 238
239 239 region, cache_key = self.get_cache_region()
240 240
241 241 @region.conditional_cache_on_arguments(condition=cache)
242 242 def _get_all_settings(name, key):
243 243 q = self._get_settings_query()
244 244 if not q:
245 245 raise Exception('Could not get application settings !')
246 246
247 247 settings = {
248 248 'rhodecode_' + res.app_settings_name: res.app_settings_value
249 249 for res in q
250 250 }
251 251 return settings
252 252
253 253 start = time.time()
254 254 result = _get_all_settings('rhodecode_settings', cache_key)
255 255 compute_time = time.time() - start
256 log.debug('cached method:%s took %.4fs', _get_all_settings.func_name, compute_time)
256 log.debug('cached method:%s took %.4fs', _get_all_settings.__name__, compute_time)
257 257
258 258 statsd = StatsdClient.statsd
259 259 if statsd:
260 260 elapsed_time_ms = round(1000.0 * compute_time) # use ms only
261 261 statsd.timing("rhodecode_settings_timing.histogram", elapsed_time_ms,
262 262 use_decimals=False)
263 263
264 264 log.debug('Fetching app settings for key: %s took: %.4fs: cache: %s', cache_key, compute_time, cache)
265 265
266 266 return result
267 267
268 268 def get_auth_settings(self):
269 269 q = self._get_settings_query()
270 270 q = q.filter(
271 271 self.SettingsDbModel.app_settings_name.startswith('auth_'))
272 272 rows = q.all()
273 273 auth_settings = {
274 274 row.app_settings_name: row.app_settings_value for row in rows}
275 275 return auth_settings
276 276
277 277 def get_auth_plugins(self):
278 278 auth_plugins = self.get_setting_by_name("auth_plugins")
279 279 return auth_plugins.app_settings_value
280 280
281 281 def get_default_repo_settings(self, strip_prefix=False):
282 282 q = self._get_settings_query()
283 283 q = q.filter(
284 284 self.SettingsDbModel.app_settings_name.startswith('default_'))
285 285 rows = q.all()
286 286
287 287 result = {}
288 288 for row in rows:
289 289 key = row.app_settings_name
290 290 if strip_prefix:
291 291 key = remove_prefix(key, prefix='default_')
292 292 result.update({key: row.app_settings_value})
293 293 return result
294 294
295 295 def get_repo(self):
296 296 repo = self._get_repo(self.repo)
297 297 if not repo:
298 298 raise Exception(
299 299 'Repository `{}` cannot be found inside the database'.format(
300 300 self.repo))
301 301 return repo
302 302
303 303 def _filter_by_repo(self, model, query):
304 304 if self.repo:
305 305 repo = self.get_repo()
306 306 query = query.filter(model.repository_id == repo.repo_id)
307 307 return query
308 308
309 309 def _get_hooks(self, query):
310 310 query = query.filter(self.UiDbModel.ui_section == self.HOOKS_SECTION)
311 311 query = self._filter_by_repo(RepoRhodeCodeUi, query)
312 312 return query.all()
313 313
314 314 def _get_settings_query(self):
315 315 q = self.SettingsDbModel.query()
316 316 return self._filter_by_repo(RepoRhodeCodeSetting, q)
317 317
318 318 def list_enabled_social_plugins(self, settings):
319 319 enabled = []
320 320 for plug in SOCIAL_PLUGINS_LIST:
321 321 if str2bool(settings.get('rhodecode_auth_{}_enabled'.format(plug)
322 322 )):
323 323 enabled.append(plug)
324 324 return enabled
325 325
326 326
327 327 def assert_repo_settings(func):
328 328 @wraps(func)
329 329 def _wrapper(self, *args, **kwargs):
330 330 if not self.repo_settings:
331 331 raise Exception('Repository is not specified')
332 332 return func(self, *args, **kwargs)
333 333 return _wrapper
334 334
335 335
336 336 class IssueTrackerSettingsModel(object):
337 337 INHERIT_SETTINGS = 'inherit_issue_tracker_settings'
338 338 SETTINGS_PREFIX = 'issuetracker_'
339 339
340 340 def __init__(self, sa=None, repo=None):
341 341 self.global_settings = SettingsModel(sa=sa)
342 342 self.repo_settings = SettingsModel(sa=sa, repo=repo) if repo else None
343 343
344 344 @property
345 345 def inherit_global_settings(self):
346 346 if not self.repo_settings:
347 347 return True
348 348 setting = self.repo_settings.get_setting_by_name(self.INHERIT_SETTINGS)
349 349 return setting.app_settings_value if setting else True
350 350
351 351 @inherit_global_settings.setter
352 352 def inherit_global_settings(self, value):
353 353 if self.repo_settings:
354 354 settings = self.repo_settings.create_or_update_setting(
355 355 self.INHERIT_SETTINGS, value, type_='bool')
356 356 Session().add(settings)
357 357
358 358 def _get_keyname(self, key, uid, prefix=''):
359 359 return '{0}{1}{2}_{3}'.format(
360 360 prefix, self.SETTINGS_PREFIX, key, uid)
361 361
362 362 def _make_dict_for_settings(self, qs):
363 363 prefix_match = self._get_keyname('pat', '', 'rhodecode_')
364 364
365 365 issuetracker_entries = {}
366 366 # create keys
367 367 for k, v in qs.items():
368 368 if k.startswith(prefix_match):
369 369 uid = k[len(prefix_match):]
370 370 issuetracker_entries[uid] = None
371 371
372 372 def url_cleaner(input_str):
373 373 input_str = input_str.replace('"', '').replace("'", '')
374 374 input_str = bleach.clean(input_str, strip=True)
375 375 return input_str
376 376
377 377 # populate
378 378 for uid in issuetracker_entries:
379 379 url_data = qs.get(self._get_keyname('url', uid, 'rhodecode_'))
380 380
381 381 pat = qs.get(self._get_keyname('pat', uid, 'rhodecode_'))
382 382 try:
383 383 pat_compiled = re.compile(r'%s' % pat)
384 384 except re.error:
385 385 pat_compiled = None
386 386
387 387 issuetracker_entries[uid] = AttributeDict({
388 388 'pat': pat,
389 389 'pat_compiled': pat_compiled,
390 390 'url': url_cleaner(
391 391 qs.get(self._get_keyname('url', uid, 'rhodecode_')) or ''),
392 392 'pref': bleach.clean(
393 393 qs.get(self._get_keyname('pref', uid, 'rhodecode_')) or ''),
394 394 'desc': qs.get(
395 395 self._get_keyname('desc', uid, 'rhodecode_')),
396 396 })
397 397
398 398 return issuetracker_entries
399 399
400 400 def get_global_settings(self, cache=False):
401 401 """
402 402 Returns list of global issue tracker settings
403 403 """
404 404 defaults = self.global_settings.get_all_settings(cache=cache)
405 405 settings = self._make_dict_for_settings(defaults)
406 406 return settings
407 407
408 408 def get_repo_settings(self, cache=False):
409 409 """
410 410 Returns list of issue tracker settings per repository
411 411 """
412 412 if not self.repo_settings:
413 413 raise Exception('Repository is not specified')
414 414 all_settings = self.repo_settings.get_all_settings(cache=cache)
415 415 settings = self._make_dict_for_settings(all_settings)
416 416 return settings
417 417
418 418 def get_settings(self, cache=False):
419 419 if self.inherit_global_settings:
420 420 return self.get_global_settings(cache=cache)
421 421 else:
422 422 return self.get_repo_settings(cache=cache)
423 423
424 424 def delete_entries(self, uid):
425 425 if self.repo_settings:
426 426 all_patterns = self.get_repo_settings()
427 427 settings_model = self.repo_settings
428 428 else:
429 429 all_patterns = self.get_global_settings()
430 430 settings_model = self.global_settings
431 431 entries = all_patterns.get(uid, [])
432 432
433 433 for del_key in entries:
434 434 setting_name = self._get_keyname(del_key, uid)
435 435 entry = settings_model.get_setting_by_name(setting_name)
436 436 if entry:
437 437 Session().delete(entry)
438 438
439 439 Session().commit()
440 440
441 441 def create_or_update_setting(
442 442 self, name, val=Optional(''), type_=Optional('unicode')):
443 443 if self.repo_settings:
444 444 setting = self.repo_settings.create_or_update_setting(
445 445 name, val, type_)
446 446 else:
447 447 setting = self.global_settings.create_or_update_setting(
448 448 name, val, type_)
449 449 return setting
450 450
451 451
452 452 class VcsSettingsModel(object):
453 453
454 454 INHERIT_SETTINGS = 'inherit_vcs_settings'
455 455 GENERAL_SETTINGS = (
456 456 'use_outdated_comments',
457 457 'pr_merge_enabled',
458 458 'hg_use_rebase_for_merging',
459 459 'hg_close_branch_before_merging',
460 460 'git_use_rebase_for_merging',
461 461 'git_close_branch_before_merging',
462 462 'diff_cache',
463 463 )
464 464
465 465 HOOKS_SETTINGS = (
466 466 ('hooks', 'changegroup.repo_size'),
467 467 ('hooks', 'changegroup.push_logger'),
468 468 ('hooks', 'outgoing.pull_logger'),
469 469 )
470 470 HG_SETTINGS = (
471 471 ('extensions', 'largefiles'),
472 472 ('phases', 'publish'),
473 473 ('extensions', 'evolve'),
474 474 ('extensions', 'topic'),
475 475 ('experimental', 'evolution'),
476 476 ('experimental', 'evolution.exchange'),
477 477 )
478 478 GIT_SETTINGS = (
479 479 ('vcs_git_lfs', 'enabled'),
480 480 )
481 481 GLOBAL_HG_SETTINGS = (
482 482 ('extensions', 'largefiles'),
483 483 ('largefiles', 'usercache'),
484 484 ('phases', 'publish'),
485 485 ('extensions', 'hgsubversion'),
486 486 ('extensions', 'evolve'),
487 487 ('extensions', 'topic'),
488 488 ('experimental', 'evolution'),
489 489 ('experimental', 'evolution.exchange'),
490 490 )
491 491
492 492 GLOBAL_GIT_SETTINGS = (
493 493 ('vcs_git_lfs', 'enabled'),
494 494 ('vcs_git_lfs', 'store_location')
495 495 )
496 496
497 497 GLOBAL_SVN_SETTINGS = (
498 498 ('vcs_svn_proxy', 'http_requests_enabled'),
499 499 ('vcs_svn_proxy', 'http_server_url')
500 500 )
501 501
502 502 SVN_BRANCH_SECTION = 'vcs_svn_branch'
503 503 SVN_TAG_SECTION = 'vcs_svn_tag'
504 504 SSL_SETTING = ('web', 'push_ssl')
505 505 PATH_SETTING = ('paths', '/')
506 506
507 507 def __init__(self, sa=None, repo=None):
508 508 self.global_settings = SettingsModel(sa=sa)
509 509 self.repo_settings = SettingsModel(sa=sa, repo=repo) if repo else None
510 510 self._ui_settings = (
511 511 self.HG_SETTINGS + self.GIT_SETTINGS + self.HOOKS_SETTINGS)
512 512 self._svn_sections = (self.SVN_BRANCH_SECTION, self.SVN_TAG_SECTION)
513 513
514 514 @property
515 515 @assert_repo_settings
516 516 def inherit_global_settings(self):
517 517 setting = self.repo_settings.get_setting_by_name(self.INHERIT_SETTINGS)
518 518 return setting.app_settings_value if setting else True
519 519
520 520 @inherit_global_settings.setter
521 521 @assert_repo_settings
522 522 def inherit_global_settings(self, value):
523 523 self.repo_settings.create_or_update_setting(
524 524 self.INHERIT_SETTINGS, value, type_='bool')
525 525
526 526 def get_global_svn_branch_patterns(self):
527 527 return self.global_settings.get_ui_by_section(self.SVN_BRANCH_SECTION)
528 528
529 529 @assert_repo_settings
530 530 def get_repo_svn_branch_patterns(self):
531 531 return self.repo_settings.get_ui_by_section(self.SVN_BRANCH_SECTION)
532 532
533 533 def get_global_svn_tag_patterns(self):
534 534 return self.global_settings.get_ui_by_section(self.SVN_TAG_SECTION)
535 535
536 536 @assert_repo_settings
537 537 def get_repo_svn_tag_patterns(self):
538 538 return self.repo_settings.get_ui_by_section(self.SVN_TAG_SECTION)
539 539
540 540 def get_global_settings(self):
541 541 return self._collect_all_settings(global_=True)
542 542
543 543 @assert_repo_settings
544 544 def get_repo_settings(self):
545 545 return self._collect_all_settings(global_=False)
546 546
547 547 @assert_repo_settings
548 548 def get_repo_settings_inherited(self):
549 549 global_settings = self.get_global_settings()
550 550 global_settings.update(self.get_repo_settings())
551 551 return global_settings
552 552
553 553 @assert_repo_settings
554 554 def create_or_update_repo_settings(
555 555 self, data, inherit_global_settings=False):
556 556 from rhodecode.model.scm import ScmModel
557 557
558 558 self.inherit_global_settings = inherit_global_settings
559 559
560 560 repo = self.repo_settings.get_repo()
561 561 if not inherit_global_settings:
562 562 if repo.repo_type == 'svn':
563 563 self.create_repo_svn_settings(data)
564 564 else:
565 565 self.create_or_update_repo_hook_settings(data)
566 566 self.create_or_update_repo_pr_settings(data)
567 567
568 568 if repo.repo_type == 'hg':
569 569 self.create_or_update_repo_hg_settings(data)
570 570
571 571 if repo.repo_type == 'git':
572 572 self.create_or_update_repo_git_settings(data)
573 573
574 574 ScmModel().mark_for_invalidation(repo.repo_name, delete=True)
575 575
576 576 @assert_repo_settings
577 577 def create_or_update_repo_hook_settings(self, data):
578 578 for section, key in self.HOOKS_SETTINGS:
579 579 data_key = self._get_form_ui_key(section, key)
580 580 if data_key not in data:
581 581 raise ValueError(
582 582 'The given data does not contain {} key'.format(data_key))
583 583
584 584 active = data.get(data_key)
585 585 repo_setting = self.repo_settings.get_ui_by_section_and_key(
586 586 section, key)
587 587 if not repo_setting:
588 588 global_setting = self.global_settings.\
589 589 get_ui_by_section_and_key(section, key)
590 590 self.repo_settings.create_ui_section_value(
591 591 section, global_setting.ui_value, key=key, active=active)
592 592 else:
593 593 repo_setting.ui_active = active
594 594 Session().add(repo_setting)
595 595
596 596 def update_global_hook_settings(self, data):
597 597 for section, key in self.HOOKS_SETTINGS:
598 598 data_key = self._get_form_ui_key(section, key)
599 599 if data_key not in data:
600 600 raise ValueError(
601 601 'The given data does not contain {} key'.format(data_key))
602 602 active = data.get(data_key)
603 603 repo_setting = self.global_settings.get_ui_by_section_and_key(
604 604 section, key)
605 605 repo_setting.ui_active = active
606 606 Session().add(repo_setting)
607 607
608 608 @assert_repo_settings
609 609 def create_or_update_repo_pr_settings(self, data):
610 610 return self._create_or_update_general_settings(
611 611 self.repo_settings, data)
612 612
613 613 def create_or_update_global_pr_settings(self, data):
614 614 return self._create_or_update_general_settings(
615 615 self.global_settings, data)
616 616
617 617 @assert_repo_settings
618 618 def create_repo_svn_settings(self, data):
619 619 return self._create_svn_settings(self.repo_settings, data)
620 620
621 621 def _set_evolution(self, settings, is_enabled):
622 622 if is_enabled:
623 623 # if evolve is active set evolution=all
624 624
625 625 self._create_or_update_ui(
626 626 settings, *('experimental', 'evolution'), value='all',
627 627 active=True)
628 628 self._create_or_update_ui(
629 629 settings, *('experimental', 'evolution.exchange'), value='yes',
630 630 active=True)
631 631 # if evolve is active set topics server support
632 632 self._create_or_update_ui(
633 633 settings, *('extensions', 'topic'), value='',
634 634 active=True)
635 635
636 636 else:
637 637 self._create_or_update_ui(
638 638 settings, *('experimental', 'evolution'), value='',
639 639 active=False)
640 640 self._create_or_update_ui(
641 641 settings, *('experimental', 'evolution.exchange'), value='no',
642 642 active=False)
643 643 self._create_or_update_ui(
644 644 settings, *('extensions', 'topic'), value='',
645 645 active=False)
646 646
647 647 @assert_repo_settings
648 648 def create_or_update_repo_hg_settings(self, data):
649 649 largefiles, phases, evolve = \
650 650 self.HG_SETTINGS[:3]
651 651 largefiles_key, phases_key, evolve_key = \
652 652 self._get_settings_keys(self.HG_SETTINGS[:3], data)
653 653
654 654 self._create_or_update_ui(
655 655 self.repo_settings, *largefiles, value='',
656 656 active=data[largefiles_key])
657 657 self._create_or_update_ui(
658 658 self.repo_settings, *evolve, value='',
659 659 active=data[evolve_key])
660 660 self._set_evolution(self.repo_settings, is_enabled=data[evolve_key])
661 661
662 662 self._create_or_update_ui(
663 663 self.repo_settings, *phases, value=safe_str(data[phases_key]))
664 664
665 665 def create_or_update_global_hg_settings(self, data):
666 666 largefiles, largefiles_store, phases, hgsubversion, evolve \
667 667 = self.GLOBAL_HG_SETTINGS[:5]
668 668 largefiles_key, largefiles_store_key, phases_key, subversion_key, evolve_key \
669 669 = self._get_settings_keys(self.GLOBAL_HG_SETTINGS[:5], data)
670 670
671 671 self._create_or_update_ui(
672 672 self.global_settings, *largefiles, value='',
673 673 active=data[largefiles_key])
674 674 self._create_or_update_ui(
675 675 self.global_settings, *largefiles_store, value=data[largefiles_store_key])
676 676 self._create_or_update_ui(
677 677 self.global_settings, *phases, value=safe_str(data[phases_key]))
678 678 self._create_or_update_ui(
679 679 self.global_settings, *hgsubversion, active=data[subversion_key])
680 680 self._create_or_update_ui(
681 681 self.global_settings, *evolve, value='',
682 682 active=data[evolve_key])
683 683 self._set_evolution(self.global_settings, is_enabled=data[evolve_key])
684 684
685 685 def create_or_update_repo_git_settings(self, data):
686 686 # NOTE(marcink): # comma makes unpack work properly
687 687 lfs_enabled, \
688 688 = self.GIT_SETTINGS
689 689
690 690 lfs_enabled_key, \
691 691 = self._get_settings_keys(self.GIT_SETTINGS, data)
692 692
693 693 self._create_or_update_ui(
694 694 self.repo_settings, *lfs_enabled, value=data[lfs_enabled_key],
695 695 active=data[lfs_enabled_key])
696 696
697 697 def create_or_update_global_git_settings(self, data):
698 698 lfs_enabled, lfs_store_location \
699 699 = self.GLOBAL_GIT_SETTINGS
700 700 lfs_enabled_key, lfs_store_location_key \
701 701 = self._get_settings_keys(self.GLOBAL_GIT_SETTINGS, data)
702 702
703 703 self._create_or_update_ui(
704 704 self.global_settings, *lfs_enabled, value=data[lfs_enabled_key],
705 705 active=data[lfs_enabled_key])
706 706 self._create_or_update_ui(
707 707 self.global_settings, *lfs_store_location,
708 708 value=data[lfs_store_location_key])
709 709
710 710 def create_or_update_global_svn_settings(self, data):
711 711 # branch/tags patterns
712 712 self._create_svn_settings(self.global_settings, data)
713 713
714 714 http_requests_enabled, http_server_url = self.GLOBAL_SVN_SETTINGS
715 715 http_requests_enabled_key, http_server_url_key = self._get_settings_keys(
716 716 self.GLOBAL_SVN_SETTINGS, data)
717 717
718 718 self._create_or_update_ui(
719 719 self.global_settings, *http_requests_enabled,
720 720 value=safe_str(data[http_requests_enabled_key]))
721 721 self._create_or_update_ui(
722 722 self.global_settings, *http_server_url,
723 723 value=data[http_server_url_key])
724 724
725 725 def update_global_ssl_setting(self, value):
726 726 self._create_or_update_ui(
727 727 self.global_settings, *self.SSL_SETTING, value=value)
728 728
729 729 def update_global_path_setting(self, value):
730 730 self._create_or_update_ui(
731 731 self.global_settings, *self.PATH_SETTING, value=value)
732 732
733 733 @assert_repo_settings
734 734 def delete_repo_svn_pattern(self, id_):
735 735 ui = self.repo_settings.UiDbModel.get(id_)
736 736 if ui and ui.repository.repo_name == self.repo_settings.repo:
737 737 # only delete if it's the same repo as initialized settings
738 738 self.repo_settings.delete_ui(id_)
739 739 else:
740 740 # raise error as if we wouldn't find this option
741 741 self.repo_settings.delete_ui(-1)
742 742
743 743 def delete_global_svn_pattern(self, id_):
744 744 self.global_settings.delete_ui(id_)
745 745
746 746 @assert_repo_settings
747 747 def get_repo_ui_settings(self, section=None, key=None):
748 748 global_uis = self.global_settings.get_ui(section, key)
749 749 repo_uis = self.repo_settings.get_ui(section, key)
750 750
751 751 filtered_repo_uis = self._filter_ui_settings(repo_uis)
752 752 filtered_repo_uis_keys = [
753 753 (s.section, s.key) for s in filtered_repo_uis]
754 754
755 755 def _is_global_ui_filtered(ui):
756 756 return (
757 757 (ui.section, ui.key) in filtered_repo_uis_keys
758 758 or ui.section in self._svn_sections)
759 759
760 760 filtered_global_uis = [
761 761 ui for ui in global_uis if not _is_global_ui_filtered(ui)]
762 762
763 763 return filtered_global_uis + filtered_repo_uis
764 764
765 765 def get_global_ui_settings(self, section=None, key=None):
766 766 return self.global_settings.get_ui(section, key)
767 767
768 768 def get_ui_settings_as_config_obj(self, section=None, key=None):
769 769 config = base.Config()
770 770
771 771 ui_settings = self.get_ui_settings(section=section, key=key)
772 772
773 773 for entry in ui_settings:
774 774 config.set(entry.section, entry.key, entry.value)
775 775
776 776 return config
777 777
778 778 def get_ui_settings(self, section=None, key=None):
779 779 if not self.repo_settings or self.inherit_global_settings:
780 780 return self.get_global_ui_settings(section, key)
781 781 else:
782 782 return self.get_repo_ui_settings(section, key)
783 783
784 784 def get_svn_patterns(self, section=None):
785 785 if not self.repo_settings:
786 786 return self.get_global_ui_settings(section)
787 787 else:
788 788 return self.get_repo_ui_settings(section)
789 789
790 790 @assert_repo_settings
791 791 def get_repo_general_settings(self):
792 792 global_settings = self.global_settings.get_all_settings()
793 793 repo_settings = self.repo_settings.get_all_settings()
794 794 filtered_repo_settings = self._filter_general_settings(repo_settings)
795 795 global_settings.update(filtered_repo_settings)
796 796 return global_settings
797 797
798 798 def get_global_general_settings(self):
799 799 return self.global_settings.get_all_settings()
800 800
801 801 def get_general_settings(self):
802 802 if not self.repo_settings or self.inherit_global_settings:
803 803 return self.get_global_general_settings()
804 804 else:
805 805 return self.get_repo_general_settings()
806 806
807 807 def get_repos_location(self):
808 808 return self.global_settings.get_ui_by_key('/').ui_value
809 809
810 810 def _filter_ui_settings(self, settings):
811 811 filtered_settings = [
812 812 s for s in settings if self._should_keep_setting(s)]
813 813 return filtered_settings
814 814
815 815 def _should_keep_setting(self, setting):
816 816 keep = (
817 817 (setting.section, setting.key) in self._ui_settings or
818 818 setting.section in self._svn_sections)
819 819 return keep
820 820
821 821 def _filter_general_settings(self, settings):
822 822 keys = ['rhodecode_{}'.format(key) for key in self.GENERAL_SETTINGS]
823 823 return {
824 824 k: settings[k]
825 825 for k in settings if k in keys}
826 826
827 827 def _collect_all_settings(self, global_=False):
828 828 settings = self.global_settings if global_ else self.repo_settings
829 829 result = {}
830 830
831 831 for section, key in self._ui_settings:
832 832 ui = settings.get_ui_by_section_and_key(section, key)
833 833 result_key = self._get_form_ui_key(section, key)
834 834
835 835 if ui:
836 836 if section in ('hooks', 'extensions'):
837 837 result[result_key] = ui.ui_active
838 838 elif result_key in ['vcs_git_lfs_enabled']:
839 839 result[result_key] = ui.ui_active
840 840 else:
841 841 result[result_key] = ui.ui_value
842 842
843 843 for name in self.GENERAL_SETTINGS:
844 844 setting = settings.get_setting_by_name(name)
845 845 if setting:
846 846 result_key = 'rhodecode_{}'.format(name)
847 847 result[result_key] = setting.app_settings_value
848 848
849 849 return result
850 850
851 851 def _get_form_ui_key(self, section, key):
852 852 return '{section}_{key}'.format(
853 853 section=section, key=key.replace('.', '_'))
854 854
855 855 def _create_or_update_ui(
856 856 self, settings, section, key, value=None, active=None):
857 857 ui = settings.get_ui_by_section_and_key(section, key)
858 858 if not ui:
859 859 active = True if active is None else active
860 860 settings.create_ui_section_value(
861 861 section, value, key=key, active=active)
862 862 else:
863 863 if active is not None:
864 864 ui.ui_active = active
865 865 if value is not None:
866 866 ui.ui_value = value
867 867 Session().add(ui)
868 868
869 869 def _create_svn_settings(self, settings, data):
870 870 svn_settings = {
871 871 'new_svn_branch': self.SVN_BRANCH_SECTION,
872 872 'new_svn_tag': self.SVN_TAG_SECTION
873 873 }
874 874 for key in svn_settings:
875 875 if data.get(key):
876 876 settings.create_ui_section_value(svn_settings[key], data[key])
877 877
878 878 def _create_or_update_general_settings(self, settings, data):
879 879 for name in self.GENERAL_SETTINGS:
880 880 data_key = 'rhodecode_{}'.format(name)
881 881 if data_key not in data:
882 882 raise ValueError(
883 883 'The given data does not contain {} key'.format(data_key))
884 884 setting = settings.create_or_update_setting(
885 885 name, data[data_key], 'bool')
886 886 Session().add(setting)
887 887
888 888 def _get_settings_keys(self, settings, data):
889 889 data_keys = [self._get_form_ui_key(*s) for s in settings]
890 890 for data_key in data_keys:
891 891 if data_key not in data:
892 892 raise ValueError(
893 893 'The given data does not contain {} key'.format(data_key))
894 894 return data_keys
895 895
896 896 def create_largeobjects_dirs_if_needed(self, repo_store_path):
897 897 """
898 898 This is subscribed to the `pyramid.events.ApplicationCreated` event. It
899 899 does a repository scan if enabled in the settings.
900 900 """
901 901
902 902 from rhodecode.lib.vcs.backends.hg import largefiles_store
903 903 from rhodecode.lib.vcs.backends.git import lfs_store
904 904
905 905 paths = [
906 906 largefiles_store(repo_store_path),
907 907 lfs_store(repo_store_path)]
908 908
909 909 for path in paths:
910 910 if os.path.isdir(path):
911 911 continue
912 912 if os.path.isfile(path):
913 913 continue
914 914 # not a file nor dir, we try to create it
915 915 try:
916 916 os.makedirs(path)
917 917 except Exception:
918 918 log.warning('Failed to create largefiles dir:%s', path)
@@ -1,255 +1,255 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2020 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import os
22 22 import time
23 23 import logging
24 24 import datetime
25 25 import hashlib
26 26 import tempfile
27 27 from os.path import join as jn
28 28
29 29 from tempfile import _RandomNameSequence
30 30
31 31 import pytest
32 32
33 33 from rhodecode.model.db import User
34 34 from rhodecode.lib import auth
35 35 from rhodecode.lib import helpers as h
36 36 from rhodecode.lib.helpers import flash
37 37 from rhodecode.lib.utils2 import safe_str
38 38
39 39
40 40 log = logging.getLogger(__name__)
41 41
42 42 __all__ = [
43 43 'get_new_dir', 'TestController', 'route_path_generator',
44 44 'clear_cache_regions',
45 45 'assert_session_flash', 'login_user', 'no_newline_id_generator',
46 46 'TESTS_TMP_PATH', 'HG_REPO', 'GIT_REPO', 'SVN_REPO',
47 47 'NEW_HG_REPO', 'NEW_GIT_REPO',
48 48 'HG_FORK', 'GIT_FORK', 'TEST_USER_ADMIN_LOGIN', 'TEST_USER_ADMIN_PASS',
49 49 'TEST_USER_REGULAR_LOGIN', 'TEST_USER_REGULAR_PASS',
50 50 'TEST_USER_REGULAR_EMAIL', 'TEST_USER_REGULAR2_LOGIN',
51 51 'TEST_USER_REGULAR2_PASS', 'TEST_USER_REGULAR2_EMAIL', 'TEST_HG_REPO',
52 52 'TEST_HG_REPO_CLONE', 'TEST_HG_REPO_PULL', 'TEST_GIT_REPO',
53 53 'TEST_GIT_REPO_CLONE', 'TEST_GIT_REPO_PULL', 'SCM_TESTS',
54 54 ]
55 55
56 56
57 57 # SOME GLOBALS FOR TESTS
58 58 TEST_DIR = tempfile.gettempdir()
59 59
60 TESTS_TMP_PATH = jn(TEST_DIR, 'rc_test_%s' % _RandomNameSequence().next())
60 TESTS_TMP_PATH = jn(TEST_DIR, 'rc_test_{}'.format(next(_RandomNameSequence())))
61 61 TEST_USER_ADMIN_LOGIN = 'test_admin'
62 62 TEST_USER_ADMIN_PASS = 'test12'
63 63 TEST_USER_ADMIN_EMAIL = 'test_admin@mail.com'
64 64
65 65 TEST_USER_REGULAR_LOGIN = 'test_regular'
66 66 TEST_USER_REGULAR_PASS = 'test12'
67 67 TEST_USER_REGULAR_EMAIL = 'test_regular@mail.com'
68 68
69 69 TEST_USER_REGULAR2_LOGIN = 'test_regular2'
70 70 TEST_USER_REGULAR2_PASS = 'test12'
71 71 TEST_USER_REGULAR2_EMAIL = 'test_regular2@mail.com'
72 72
73 73 HG_REPO = 'vcs_test_hg'
74 74 GIT_REPO = 'vcs_test_git'
75 75 SVN_REPO = 'vcs_test_svn'
76 76
77 77 NEW_HG_REPO = 'vcs_test_hg_new'
78 78 NEW_GIT_REPO = 'vcs_test_git_new'
79 79
80 80 HG_FORK = 'vcs_test_hg_fork'
81 81 GIT_FORK = 'vcs_test_git_fork'
82 82
83 83 ## VCS
84 84 SCM_TESTS = ['hg', 'git']
85 85 uniq_suffix = str(int(time.mktime(datetime.datetime.now().timetuple())))
86 86
87 87 TEST_GIT_REPO = jn(TESTS_TMP_PATH, GIT_REPO)
88 88 TEST_GIT_REPO_CLONE = jn(TESTS_TMP_PATH, 'vcsgitclone%s' % uniq_suffix)
89 89 TEST_GIT_REPO_PULL = jn(TESTS_TMP_PATH, 'vcsgitpull%s' % uniq_suffix)
90 90
91 91 TEST_HG_REPO = jn(TESTS_TMP_PATH, HG_REPO)
92 92 TEST_HG_REPO_CLONE = jn(TESTS_TMP_PATH, 'vcshgclone%s' % uniq_suffix)
93 93 TEST_HG_REPO_PULL = jn(TESTS_TMP_PATH, 'vcshgpull%s' % uniq_suffix)
94 94
95 95 TEST_REPO_PREFIX = 'vcs-test'
96 96
97 97
98 98 def clear_cache_regions(regions=None):
99 99 # dogpile
100 100 from rhodecode.lib.rc_cache import region_meta
101 101 for region_name, region in region_meta.dogpile_cache_regions.items():
102 102 if not regions or region_name in regions:
103 103 region.invalidate()
104 104
105 105
106 106 def get_new_dir(title):
107 107 """
108 108 Returns always new directory path.
109 109 """
110 110 from rhodecode.tests.vcs.utils import get_normalized_path
111 111 name_parts = [TEST_REPO_PREFIX]
112 112 if title:
113 113 name_parts.append(title)
114 114 hex_str = hashlib.sha1('%s %s' % (os.getpid(), time.time())).hexdigest()
115 115 name_parts.append(hex_str)
116 116 name = '-'.join(name_parts)
117 117 path = os.path.join(TEST_DIR, name)
118 118 return get_normalized_path(path)
119 119
120 120
121 121 def repo_id_generator(name):
122 122 numeric_hash = 0
123 123 for char in name:
124 124 numeric_hash += (ord(char))
125 125 return numeric_hash
126 126
127 127
128 128 @pytest.mark.usefixtures('app', 'index_location')
129 129 class TestController(object):
130 130
131 131 maxDiff = None
132 132
133 133 def log_user(self, username=TEST_USER_ADMIN_LOGIN,
134 134 password=TEST_USER_ADMIN_PASS):
135 135 self._logged_username = username
136 136 self._session = login_user_session(self.app, username, password)
137 137 self.csrf_token = auth.get_csrf_token(self._session)
138 138
139 139 return self._session['rhodecode_user']
140 140
141 141 def logout_user(self):
142 142 logout_user_session(self.app, auth.get_csrf_token(self._session))
143 143 self.csrf_token = None
144 144 self._logged_username = None
145 145 self._session = None
146 146
147 147 def _get_logged_user(self):
148 148 return User.get_by_username(self._logged_username)
149 149
150 150
151 151 def login_user_session(
152 152 app, username=TEST_USER_ADMIN_LOGIN, password=TEST_USER_ADMIN_PASS):
153 153
154 154 response = app.post(
155 155 h.route_path('login'),
156 156 {'username': username, 'password': password})
157 157 if 'invalid user name' in response.body:
158 158 pytest.fail('could not login using %s %s' % (username, password))
159 159
160 160 assert response.status == '302 Found'
161 161 response = response.follow()
162 162 assert response.status == '200 OK'
163 163
164 164 session = response.get_session_from_response()
165 165 assert 'rhodecode_user' in session
166 166 rc_user = session['rhodecode_user']
167 167 assert rc_user.get('username') == username
168 168 assert rc_user.get('is_authenticated')
169 169
170 170 return session
171 171
172 172
173 173 def logout_user_session(app, csrf_token):
174 174 app.post(h.route_path('logout'), {'csrf_token': csrf_token}, status=302)
175 175
176 176
177 177 def login_user(app, username=TEST_USER_ADMIN_LOGIN,
178 178 password=TEST_USER_ADMIN_PASS):
179 179 return login_user_session(app, username, password)['rhodecode_user']
180 180
181 181
182 182 def assert_session_flash(response, msg=None, category=None, no_=None):
183 183 """
184 184 Assert on a flash message in the current session.
185 185
186 186 :param response: Response from give calll, it will contain flash
187 187 messages or bound session with them.
188 188 :param msg: The expected message. Will be evaluated if a
189 189 :class:`LazyString` is passed in.
190 190 :param category: Optional. If passed, the message category will be
191 191 checked as well.
192 192 :param no_: Optional. If passed, the message will be checked to NOT
193 193 be in the flash session
194 194 """
195 195 if msg is None and no_ is None:
196 196 raise ValueError("Parameter msg or no_ is required.")
197 197
198 198 if msg and no_:
199 199 raise ValueError("Please specify either msg or no_, but not both")
200 200
201 201 session = response.get_session_from_response()
202 202 messages = flash.pop_messages(session=session)
203 203 msg = _eval_if_lazy(msg)
204 204
205 205 if no_:
206 206 error_msg = 'unable to detect no_ message `%s` in empty flash list' % no_
207 207 else:
208 208 error_msg = 'unable to find message `%s` in empty flash list' % msg
209 209 assert messages, error_msg
210 210 message = messages[0]
211 211
212 212 message_text = _eval_if_lazy(message.message) or ''
213 213
214 214 if no_:
215 215 if no_ in message_text:
216 216 msg = u'msg `%s` found in session flash.' % (no_,)
217 217 pytest.fail(safe_str(msg))
218 218 else:
219 219 if msg not in message_text:
220 220 fail_msg = u'msg `%s` not found in session ' \
221 221 u'flash: got `%s` (type:%s) instead' % (
222 222 msg, message_text, type(message_text))
223 223
224 224 pytest.fail(safe_str(fail_msg))
225 225 if category:
226 226 assert category == message.category
227 227
228 228
229 229 def _eval_if_lazy(value):
230 230 return value.eval() if hasattr(value, 'eval') else value
231 231
232 232
233 233 def no_newline_id_generator(test_name):
234 234 """
235 235 Generates a test name without spaces or newlines characters. Used for
236 236 nicer output of progress of test
237 237 """
238 238 org_name = test_name
239 239 test_name = safe_str(test_name)\
240 240 .replace('\n', '_N') \
241 241 .replace('\r', '_N') \
242 242 .replace('\t', '_T') \
243 243 .replace(' ', '_S')
244 244
245 245 return test_name or 'test-with-empty-name'
246 246
247 247
248 248 def route_path_generator(url_defs, name, params=None, **kwargs):
249 249 import urllib.request, urllib.parse, urllib.error
250 250
251 251 base_url = url_defs[name].format(**kwargs)
252 252
253 253 if params:
254 254 base_url = '{}?{}'.format(base_url, urllib.parse.urlencode(params))
255 255 return base_url
@@ -1,203 +1,203 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2020 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Test suite for making push/pull operations
23 23 """
24 24
25 25 import os
26 26 import sys
27 27 import shutil
28 28 import logging
29 29 from os.path import join as jn
30 30 from os.path import dirname as dn
31 31
32 32 from tempfile import _RandomNameSequence
33 33 from subprocess import Popen, PIPE
34 34
35 35 from rhodecode.lib.utils2 import engine_from_config
36 36 from rhodecode.lib.auth import get_crypt_password
37 37 from rhodecode.model import init_model
38 38 from rhodecode.model import meta
39 39 from rhodecode.model.db import User, Repository
40 40
41 41 from rhodecode.tests import TESTS_TMP_PATH, HG_REPO
42 42
43 43 rel_path = dn(dn(dn(dn(os.path.abspath(__file__)))))
44 44
45 45
46 46 USER = 'test_admin'
47 47 PASS = 'test12'
48 48 HOST = 'rc.local'
49 49 METHOD = 'pull'
50 50 DEBUG = True
51 51 log = logging.getLogger(__name__)
52 52
53 53
54 54 class Command(object):
55 55
56 56 def __init__(self, cwd):
57 57 self.cwd = cwd
58 58
59 59 def execute(self, cmd, *args):
60 60 """Runs command on the system with given ``args``.
61 61 """
62 62
63 63 command = cmd + ' ' + ' '.join(args)
64 64 log.debug('Executing %s', command)
65 65 if DEBUG:
66 66 print(command)
67 67 p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE, cwd=self.cwd)
68 68 stdout, stderr = p.communicate()
69 69 if DEBUG:
70 70 print('{} {}'.format(stdout, stderr))
71 71 return stdout, stderr
72 72
73 73
74 74 def get_session():
75 75 conf = {}
76 76 engine = engine_from_config(conf, 'sqlalchemy.db1.')
77 77 init_model(engine)
78 78 sa = meta.Session
79 79 return sa
80 80
81 81
82 82 def create_test_user(force=True):
83 83 print('creating test user')
84 84 sa = get_session()
85 85
86 86 user = sa.query(User).filter(User.username == USER).scalar()
87 87
88 88 if force and user is not None:
89 89 print('removing current user')
90 90 for repo in sa.query(Repository).filter(Repository.user == user).all():
91 91 sa.delete(repo)
92 92 sa.delete(user)
93 93 sa.commit()
94 94
95 95 if user is None or force:
96 96 print('creating new one')
97 97 new_usr = User()
98 98 new_usr.username = USER
99 99 new_usr.password = get_crypt_password(PASS)
100 100 new_usr.email = 'mail@mail.com'
101 101 new_usr.name = 'test'
102 102 new_usr.lastname = 'lasttestname'
103 103 new_usr.active = True
104 104 new_usr.admin = True
105 105 sa.add(new_usr)
106 106 sa.commit()
107 107
108 108 print('done')
109 109
110 110
111 111 def create_test_repo(force=True):
112 112 print('creating test repo')
113 113 from rhodecode.model.repo import RepoModel
114 114 sa = get_session()
115 115
116 116 user = sa.query(User).filter(User.username == USER).scalar()
117 117 if user is None:
118 118 raise Exception('user not found')
119 119
120 120 repo = sa.query(Repository).filter(Repository.repo_name == HG_REPO).scalar()
121 121
122 122 if repo is None:
123 123 print('repo not found creating')
124 124
125 125 form_data = {'repo_name': HG_REPO,
126 126 'repo_type': 'hg',
127 127 'private':False,
128 128 'clone_uri': '' }
129 129 rm = RepoModel(sa)
130 130 rm.base_path = '/home/hg'
131 131 rm.create(form_data, user)
132 132
133 133 print('done')
134 134
135 135
136 136 def get_anonymous_access():
137 137 sa = get_session()
138 138 return sa.query(User).filter(User.username == 'default').one().active
139 139
140 140
141 141 #==============================================================================
142 142 # TESTS
143 143 #==============================================================================
144 144 def test_clone_with_credentials(repo=HG_REPO, method=METHOD,
145 145 seq=None, backend='hg', check_output=True):
146 146 cwd = path = jn(TESTS_TMP_PATH, repo)
147 147
148 148 if seq is None:
149 seq = _RandomNameSequence().next()
149 seq = next(_RandomNameSequence())
150 150
151 151 try:
152 152 shutil.rmtree(path, ignore_errors=True)
153 153 os.makedirs(path)
154 154 except OSError:
155 155 raise
156 156
157 157 clone_url = 'http://%(user)s:%(pass)s@%(host)s/%(cloned_repo)s' % \
158 158 {'user': USER,
159 159 'pass': PASS,
160 160 'host': HOST,
161 161 'cloned_repo': repo, }
162 162
163 163 dest = path + seq
164 164 if method == 'pull':
165 165 stdout, stderr = Command(cwd).execute(backend, method, '--cwd', dest, clone_url)
166 166 else:
167 167 stdout, stderr = Command(cwd).execute(backend, method, clone_url, dest)
168 168 if check_output:
169 169 if backend == 'hg':
170 170 assert """adding file changes""" in stdout, 'no messages about cloning'
171 171 assert """abort""" not in stderr, 'got error from clone'
172 172 elif backend == 'git':
173 173 assert """Cloning into""" in stdout, 'no messages about cloning'
174 174
175 175
176 176 if __name__ == '__main__':
177 177 try:
178 178 create_test_user(force=False)
179 179 seq = None
180 180 import time
181 181
182 182 try:
183 183 METHOD = sys.argv[3]
184 184 except Exception:
185 185 pass
186 186
187 187 try:
188 188 backend = sys.argv[4]
189 189 except Exception:
190 190 backend = 'hg'
191 191
192 192 if METHOD == 'pull':
193 seq = _RandomNameSequence().next()
193 seq = next(_RandomNameSequence())
194 194 test_clone_with_credentials(repo=sys.argv[1], method='clone',
195 195 seq=seq, backend=backend)
196 196 s = time.time()
197 197 for i in range(1, int(sys.argv[2]) + 1):
198 198 print('take {}'.format(i))
199 199 test_clone_with_credentials(repo=sys.argv[1], method=METHOD,
200 200 seq=seq, backend=backend)
201 201 print('time taken %.4f' % (time.time() - s))
202 202 except Exception as e:
203 203 sys.exit('stop on %s' % e)
@@ -1,193 +1,193 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2020 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Base for test suite for making push/pull operations.
23 23
24 24 .. important::
25 25
26 26 You must have git >= 1.8.5 for tests to work fine. With 68b939b git started
27 27 to redirect things to stderr instead of stdout.
28 28 """
29 29
30 30 from os.path import join as jn
31 31 from subprocess import Popen, PIPE
32 32 import logging
33 33 import os
34 34 import tempfile
35 35
36 36 from rhodecode.tests import GIT_REPO, HG_REPO
37 37
38 38 DEBUG = True
39 39 RC_LOG = os.path.join(tempfile.gettempdir(), 'rc.log')
40 40 REPO_GROUP = 'a_repo_group'
41 41 HG_REPO_WITH_GROUP = '%s/%s' % (REPO_GROUP, HG_REPO)
42 42 GIT_REPO_WITH_GROUP = '%s/%s' % (REPO_GROUP, GIT_REPO)
43 43
44 44 log = logging.getLogger(__name__)
45 45
46 46
47 47 class Command(object):
48 48
49 49 def __init__(self, cwd):
50 50 self.cwd = cwd
51 51 self.process = None
52 52
53 53 def execute(self, cmd, *args):
54 54 """
55 55 Runs command on the system with given ``args``.
56 56 """
57 57
58 58 command = cmd + ' ' + ' '.join(args)
59 59 if DEBUG:
60 60 log.debug('*** CMD %s ***', command)
61 61
62 62 env = dict(os.environ)
63 63 # Delete coverage variables, as they make the test fail for Mercurial
64 64 for key in env.keys():
65 65 if key.startswith('COV_CORE_'):
66 66 del env[key]
67 67
68 68 self.process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE,
69 69 cwd=self.cwd, env=env)
70 70 stdout, stderr = self.process.communicate()
71 71 if DEBUG:
72 72 log.debug('STDOUT:%s', stdout)
73 73 log.debug('STDERR:%s', stderr)
74 74 return stdout, stderr
75 75
76 76 def assert_returncode_success(self):
77 77 assert self.process.returncode == 0
78 78
79 79
80 80 def _add_files(vcs, dest, clone_url=None, tags=None, target_branch=None, new_branch=False, **kwargs):
81 81 git_ident = "git config user.name {} && git config user.email {}".format(
82 82 'Marcin KuΕΊminski', 'me@email.com')
83 83 cwd = path = jn(dest)
84 84
85 85 tags = tags or []
86 added_file = jn(path, '%s_setup.py' % tempfile._RandomNameSequence().next())
86 added_file = jn(path, '{}_setup.py'.format(next(tempfile._RandomNameSequence())))
87 87 Command(cwd).execute('touch %s' % added_file)
88 88 Command(cwd).execute('%s add %s' % (vcs, added_file))
89 89 author_str = 'Marcin KuΕΊminski <me@email.com>'
90 90
91 91 for i in range(kwargs.get('files_no', 3)):
92 92 cmd = """echo 'added_line%s' >> %s""" % (i, added_file)
93 93 Command(cwd).execute(cmd)
94 94
95 95 if vcs == 'hg':
96 96 cmd = """hg commit -m 'committed new %s' -u '%s' %s """ % (
97 97 i, author_str, added_file
98 98 )
99 99 elif vcs == 'git':
100 100 cmd = """%s && git commit -m 'committed new %s' %s""" % (
101 101 git_ident, i, added_file)
102 102 Command(cwd).execute(cmd)
103 103
104 104 for tag in tags:
105 105 if vcs == 'hg':
106 106 Command(cwd).execute(
107 107 'hg tag -m "{}" -u "{}" '.format(tag['commit'], author_str), tag['name'])
108 108 elif vcs == 'git':
109 109 if tag['commit']:
110 110 # annotated tag
111 111 _stdout, _stderr = Command(cwd).execute(
112 112 """%s && git tag -a %s -m "%s" """ % (
113 113 git_ident, tag['name'], tag['commit']))
114 114 else:
115 115 # lightweight tag
116 116 _stdout, _stderr = Command(cwd).execute(
117 117 """%s && git tag %s""" % (
118 118 git_ident, tag['name']))
119 119
120 120
121 121 def _add_files_and_push(vcs, dest, clone_url=None, tags=None, target_branch=None,
122 122 new_branch=False, **kwargs):
123 123 """
124 124 Generate some files, add it to DEST repo and push back
125 125 vcs is git or hg and defines what VCS we want to make those files for
126 126 """
127 127 git_ident = "git config user.name {} && git config user.email {}".format(
128 128 'Marcin KuΕΊminski', 'me@email.com')
129 129 cwd = path = jn(dest)
130 130
131 131 # commit some stuff into this repo
132 132 _add_files(vcs, dest, clone_url, tags, target_branch, new_branch, **kwargs)
133 133
134 134 default_target_branch = {
135 135 'git': 'master',
136 136 'hg': 'default'
137 137 }.get(vcs)
138 138
139 139 target_branch = target_branch or default_target_branch
140 140
141 141 # PUSH it back
142 142 stdout = stderr = None
143 143 if vcs == 'hg':
144 144 maybe_new_branch = ''
145 145 if new_branch:
146 146 maybe_new_branch = '--new-branch'
147 147 stdout, stderr = Command(cwd).execute(
148 148 'hg push --verbose {} -r {} {}'.format(maybe_new_branch, target_branch, clone_url)
149 149 )
150 150 elif vcs == 'git':
151 151 stdout, stderr = Command(cwd).execute(
152 152 """{} &&
153 153 git push --verbose --tags {} {}""".format(git_ident, clone_url, target_branch)
154 154 )
155 155
156 156 return stdout, stderr
157 157
158 158
159 159 def _check_proper_git_push(
160 160 stdout, stderr, branch='master', should_set_default_branch=False):
161 161 # Note: Git is writing most information to stderr intentionally
162 162 assert 'fatal' not in stderr
163 163 assert 'rejected' not in stderr
164 164 assert 'Pushing to' in stderr
165 165 assert '%s -> %s' % (branch, branch) in stderr
166 166
167 167 if should_set_default_branch:
168 168 assert "Setting default branch to %s" % branch in stderr
169 169 else:
170 170 assert "Setting default branch" not in stderr
171 171
172 172
173 173 def _check_proper_hg_push(stdout, stderr, branch='default'):
174 174 assert 'pushing to' in stdout
175 175 assert 'searching for changes' in stdout
176 176
177 177 assert 'abort:' not in stderr
178 178
179 179
180 180 def _check_proper_clone(stdout, stderr, vcs):
181 181 if vcs == 'hg':
182 182 assert 'requesting all changes' in stdout
183 183 assert 'adding changesets' in stdout
184 184 assert 'adding manifests' in stdout
185 185 assert 'adding file changes' in stdout
186 186
187 187 assert stderr == ''
188 188
189 189 if vcs == 'git':
190 190 assert '' == stdout
191 191 assert 'Cloning into' in stderr
192 192 assert 'abort:' not in stderr
193 193 assert 'fatal:' not in stderr
General Comments 0
You need to be logged in to leave comments. Login now