##// END OF EJS Templates
pull-requests: loosen strict view of pull-requests that state is changing...
ergo -
r4103:78e087c7 default
parent child Browse files
Show More
@@ -1,762 +1,762 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2019 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 logging
22 22 import datetime
23 23 import string
24 24
25 25 import formencode
26 26 import formencode.htmlfill
27 27 import peppercorn
28 28 from pyramid.httpexceptions import HTTPFound
29 29 from pyramid.view import view_config
30 30
31 31 from rhodecode.apps._base import BaseAppView, DataGridAppView
32 32 from rhodecode import forms
33 33 from rhodecode.lib import helpers as h
34 34 from rhodecode.lib import audit_logger
35 35 from rhodecode.lib.ext_json import json
36 36 from rhodecode.lib.auth import LoginRequired, NotAnonymous, CSRFRequired, \
37 37 HasRepoPermissionAny, HasRepoGroupPermissionAny
38 38 from rhodecode.lib.channelstream import (
39 39 channelstream_request, ChannelstreamException)
40 40 from rhodecode.lib.utils2 import safe_int, md5, str2bool
41 41 from rhodecode.model.auth_token import AuthTokenModel
42 42 from rhodecode.model.comment import CommentsModel
43 43 from rhodecode.model.db import (
44 44 IntegrityError, joinedload,
45 45 Repository, UserEmailMap, UserApiKeys, UserFollowing,
46 46 PullRequest, UserBookmark, RepoGroup)
47 47 from rhodecode.model.meta import Session
48 48 from rhodecode.model.pull_request import PullRequestModel
49 49 from rhodecode.model.scm import RepoList
50 50 from rhodecode.model.user import UserModel
51 51 from rhodecode.model.repo import RepoModel
52 52 from rhodecode.model.user_group import UserGroupModel
53 53 from rhodecode.model.validation_schema.schemas import user_schema
54 54
55 55 log = logging.getLogger(__name__)
56 56
57 57
58 58 class MyAccountView(BaseAppView, DataGridAppView):
59 59 ALLOW_SCOPED_TOKENS = False
60 60 """
61 61 This view has alternative version inside EE, if modified please take a look
62 62 in there as well.
63 63 """
64 64
65 65 def load_default_context(self):
66 66 c = self._get_local_tmpl_context()
67 67 c.user = c.auth_user.get_instance()
68 68 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
69 69
70 70 return c
71 71
72 72 @LoginRequired()
73 73 @NotAnonymous()
74 74 @view_config(
75 75 route_name='my_account_profile', request_method='GET',
76 76 renderer='rhodecode:templates/admin/my_account/my_account.mako')
77 77 def my_account_profile(self):
78 78 c = self.load_default_context()
79 79 c.active = 'profile'
80 80 return self._get_template_context(c)
81 81
82 82 @LoginRequired()
83 83 @NotAnonymous()
84 84 @view_config(
85 85 route_name='my_account_password', request_method='GET',
86 86 renderer='rhodecode:templates/admin/my_account/my_account.mako')
87 87 def my_account_password(self):
88 88 c = self.load_default_context()
89 89 c.active = 'password'
90 90 c.extern_type = c.user.extern_type
91 91
92 92 schema = user_schema.ChangePasswordSchema().bind(
93 93 username=c.user.username)
94 94
95 95 form = forms.Form(
96 96 schema,
97 97 action=h.route_path('my_account_password_update'),
98 98 buttons=(forms.buttons.save, forms.buttons.reset))
99 99
100 100 c.form = form
101 101 return self._get_template_context(c)
102 102
103 103 @LoginRequired()
104 104 @NotAnonymous()
105 105 @CSRFRequired()
106 106 @view_config(
107 107 route_name='my_account_password_update', request_method='POST',
108 108 renderer='rhodecode:templates/admin/my_account/my_account.mako')
109 109 def my_account_password_update(self):
110 110 _ = self.request.translate
111 111 c = self.load_default_context()
112 112 c.active = 'password'
113 113 c.extern_type = c.user.extern_type
114 114
115 115 schema = user_schema.ChangePasswordSchema().bind(
116 116 username=c.user.username)
117 117
118 118 form = forms.Form(
119 119 schema, buttons=(forms.buttons.save, forms.buttons.reset))
120 120
121 121 if c.extern_type != 'rhodecode':
122 122 raise HTTPFound(self.request.route_path('my_account_password'))
123 123
124 124 controls = self.request.POST.items()
125 125 try:
126 126 valid_data = form.validate(controls)
127 127 UserModel().update_user(c.user.user_id, **valid_data)
128 128 c.user.update_userdata(force_password_change=False)
129 129 Session().commit()
130 130 except forms.ValidationFailure as e:
131 131 c.form = e
132 132 return self._get_template_context(c)
133 133
134 134 except Exception:
135 135 log.exception("Exception updating password")
136 136 h.flash(_('Error occurred during update of user password'),
137 137 category='error')
138 138 else:
139 139 instance = c.auth_user.get_instance()
140 140 self.session.setdefault('rhodecode_user', {}).update(
141 141 {'password': md5(instance.password)})
142 142 self.session.save()
143 143 h.flash(_("Successfully updated password"), category='success')
144 144
145 145 raise HTTPFound(self.request.route_path('my_account_password'))
146 146
147 147 @LoginRequired()
148 148 @NotAnonymous()
149 149 @view_config(
150 150 route_name='my_account_auth_tokens', request_method='GET',
151 151 renderer='rhodecode:templates/admin/my_account/my_account.mako')
152 152 def my_account_auth_tokens(self):
153 153 _ = self.request.translate
154 154
155 155 c = self.load_default_context()
156 156 c.active = 'auth_tokens'
157 157 c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_)
158 158 c.role_values = [
159 159 (x, AuthTokenModel.cls._get_role_name(x))
160 160 for x in AuthTokenModel.cls.ROLES]
161 161 c.role_options = [(c.role_values, _("Role"))]
162 162 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
163 163 c.user.user_id, show_expired=True)
164 164 c.role_vcs = AuthTokenModel.cls.ROLE_VCS
165 165 return self._get_template_context(c)
166 166
167 167 def maybe_attach_token_scope(self, token):
168 168 # implemented in EE edition
169 169 pass
170 170
171 171 @LoginRequired()
172 172 @NotAnonymous()
173 173 @CSRFRequired()
174 174 @view_config(
175 175 route_name='my_account_auth_tokens_add', request_method='POST',)
176 176 def my_account_auth_tokens_add(self):
177 177 _ = self.request.translate
178 178 c = self.load_default_context()
179 179
180 180 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
181 181 description = self.request.POST.get('description')
182 182 role = self.request.POST.get('role')
183 183
184 184 token = UserModel().add_auth_token(
185 185 user=c.user.user_id,
186 186 lifetime_minutes=lifetime, role=role, description=description,
187 187 scope_callback=self.maybe_attach_token_scope)
188 188 token_data = token.get_api_data()
189 189
190 190 audit_logger.store_web(
191 191 'user.edit.token.add', action_data={
192 192 'data': {'token': token_data, 'user': 'self'}},
193 193 user=self._rhodecode_user, )
194 194 Session().commit()
195 195
196 196 h.flash(_("Auth token successfully created"), category='success')
197 197 return HTTPFound(h.route_path('my_account_auth_tokens'))
198 198
199 199 @LoginRequired()
200 200 @NotAnonymous()
201 201 @CSRFRequired()
202 202 @view_config(
203 203 route_name='my_account_auth_tokens_delete', request_method='POST')
204 204 def my_account_auth_tokens_delete(self):
205 205 _ = self.request.translate
206 206 c = self.load_default_context()
207 207
208 208 del_auth_token = self.request.POST.get('del_auth_token')
209 209
210 210 if del_auth_token:
211 211 token = UserApiKeys.get_or_404(del_auth_token)
212 212 token_data = token.get_api_data()
213 213
214 214 AuthTokenModel().delete(del_auth_token, c.user.user_id)
215 215 audit_logger.store_web(
216 216 'user.edit.token.delete', action_data={
217 217 'data': {'token': token_data, 'user': 'self'}},
218 218 user=self._rhodecode_user,)
219 219 Session().commit()
220 220 h.flash(_("Auth token successfully deleted"), category='success')
221 221
222 222 return HTTPFound(h.route_path('my_account_auth_tokens'))
223 223
224 224 @LoginRequired()
225 225 @NotAnonymous()
226 226 @view_config(
227 227 route_name='my_account_emails', request_method='GET',
228 228 renderer='rhodecode:templates/admin/my_account/my_account.mako')
229 229 def my_account_emails(self):
230 230 _ = self.request.translate
231 231
232 232 c = self.load_default_context()
233 233 c.active = 'emails'
234 234
235 235 c.user_email_map = UserEmailMap.query()\
236 236 .filter(UserEmailMap.user == c.user).all()
237 237
238 238 schema = user_schema.AddEmailSchema().bind(
239 239 username=c.user.username, user_emails=c.user.emails)
240 240
241 241 form = forms.RcForm(schema,
242 242 action=h.route_path('my_account_emails_add'),
243 243 buttons=(forms.buttons.save, forms.buttons.reset))
244 244
245 245 c.form = form
246 246 return self._get_template_context(c)
247 247
248 248 @LoginRequired()
249 249 @NotAnonymous()
250 250 @CSRFRequired()
251 251 @view_config(
252 252 route_name='my_account_emails_add', request_method='POST',
253 253 renderer='rhodecode:templates/admin/my_account/my_account.mako')
254 254 def my_account_emails_add(self):
255 255 _ = self.request.translate
256 256 c = self.load_default_context()
257 257 c.active = 'emails'
258 258
259 259 schema = user_schema.AddEmailSchema().bind(
260 260 username=c.user.username, user_emails=c.user.emails)
261 261
262 262 form = forms.RcForm(
263 263 schema, action=h.route_path('my_account_emails_add'),
264 264 buttons=(forms.buttons.save, forms.buttons.reset))
265 265
266 266 controls = self.request.POST.items()
267 267 try:
268 268 valid_data = form.validate(controls)
269 269 UserModel().add_extra_email(c.user.user_id, valid_data['email'])
270 270 audit_logger.store_web(
271 271 'user.edit.email.add', action_data={
272 272 'data': {'email': valid_data['email'], 'user': 'self'}},
273 273 user=self._rhodecode_user,)
274 274 Session().commit()
275 275 except formencode.Invalid as error:
276 276 h.flash(h.escape(error.error_dict['email']), category='error')
277 277 except forms.ValidationFailure as e:
278 278 c.user_email_map = UserEmailMap.query() \
279 279 .filter(UserEmailMap.user == c.user).all()
280 280 c.form = e
281 281 return self._get_template_context(c)
282 282 except Exception:
283 283 log.exception("Exception adding email")
284 284 h.flash(_('Error occurred during adding email'),
285 285 category='error')
286 286 else:
287 287 h.flash(_("Successfully added email"), category='success')
288 288
289 289 raise HTTPFound(self.request.route_path('my_account_emails'))
290 290
291 291 @LoginRequired()
292 292 @NotAnonymous()
293 293 @CSRFRequired()
294 294 @view_config(
295 295 route_name='my_account_emails_delete', request_method='POST')
296 296 def my_account_emails_delete(self):
297 297 _ = self.request.translate
298 298 c = self.load_default_context()
299 299
300 300 del_email_id = self.request.POST.get('del_email_id')
301 301 if del_email_id:
302 302 email = UserEmailMap.get_or_404(del_email_id).email
303 303 UserModel().delete_extra_email(c.user.user_id, del_email_id)
304 304 audit_logger.store_web(
305 305 'user.edit.email.delete', action_data={
306 306 'data': {'email': email, 'user': 'self'}},
307 307 user=self._rhodecode_user,)
308 308 Session().commit()
309 309 h.flash(_("Email successfully deleted"),
310 310 category='success')
311 311 return HTTPFound(h.route_path('my_account_emails'))
312 312
313 313 @LoginRequired()
314 314 @NotAnonymous()
315 315 @CSRFRequired()
316 316 @view_config(
317 317 route_name='my_account_notifications_test_channelstream',
318 318 request_method='POST', renderer='json_ext')
319 319 def my_account_notifications_test_channelstream(self):
320 320 message = 'Test message sent via Channelstream by user: {}, on {}'.format(
321 321 self._rhodecode_user.username, datetime.datetime.now())
322 322 payload = {
323 323 # 'channel': 'broadcast',
324 324 'type': 'message',
325 325 'timestamp': datetime.datetime.utcnow(),
326 326 'user': 'system',
327 327 'pm_users': [self._rhodecode_user.username],
328 328 'message': {
329 329 'message': message,
330 330 'level': 'info',
331 331 'topic': '/notifications'
332 332 }
333 333 }
334 334
335 335 registry = self.request.registry
336 336 rhodecode_plugins = getattr(registry, 'rhodecode_plugins', {})
337 337 channelstream_config = rhodecode_plugins.get('channelstream', {})
338 338
339 339 try:
340 340 channelstream_request(channelstream_config, [payload], '/message')
341 341 except ChannelstreamException as e:
342 342 log.exception('Failed to send channelstream data')
343 343 return {"response": 'ERROR: {}'.format(e.__class__.__name__)}
344 344 return {"response": 'Channelstream data sent. '
345 345 'You should see a new live message now.'}
346 346
347 347 def _load_my_repos_data(self, watched=False):
348 348 if watched:
349 349 admin = False
350 350 follows_repos = Session().query(UserFollowing)\
351 351 .filter(UserFollowing.user_id == self._rhodecode_user.user_id)\
352 352 .options(joinedload(UserFollowing.follows_repository))\
353 353 .all()
354 354 repo_list = [x.follows_repository for x in follows_repos]
355 355 else:
356 356 admin = True
357 357 repo_list = Repository.get_all_repos(
358 358 user_id=self._rhodecode_user.user_id)
359 359 repo_list = RepoList(repo_list, perm_set=[
360 360 'repository.read', 'repository.write', 'repository.admin'])
361 361
362 362 repos_data = RepoModel().get_repos_as_dict(
363 363 repo_list=repo_list, admin=admin, short_name=False)
364 364 # json used to render the grid
365 365 return json.dumps(repos_data)
366 366
367 367 @LoginRequired()
368 368 @NotAnonymous()
369 369 @view_config(
370 370 route_name='my_account_repos', request_method='GET',
371 371 renderer='rhodecode:templates/admin/my_account/my_account.mako')
372 372 def my_account_repos(self):
373 373 c = self.load_default_context()
374 374 c.active = 'repos'
375 375
376 376 # json used to render the grid
377 377 c.data = self._load_my_repos_data()
378 378 return self._get_template_context(c)
379 379
380 380 @LoginRequired()
381 381 @NotAnonymous()
382 382 @view_config(
383 383 route_name='my_account_watched', request_method='GET',
384 384 renderer='rhodecode:templates/admin/my_account/my_account.mako')
385 385 def my_account_watched(self):
386 386 c = self.load_default_context()
387 387 c.active = 'watched'
388 388
389 389 # json used to render the grid
390 390 c.data = self._load_my_repos_data(watched=True)
391 391 return self._get_template_context(c)
392 392
393 393 @LoginRequired()
394 394 @NotAnonymous()
395 395 @view_config(
396 396 route_name='my_account_bookmarks', request_method='GET',
397 397 renderer='rhodecode:templates/admin/my_account/my_account.mako')
398 398 def my_account_bookmarks(self):
399 399 c = self.load_default_context()
400 400 c.active = 'bookmarks'
401 401 return self._get_template_context(c)
402 402
403 403 def _process_bookmark_entry(self, entry, user_id):
404 404 position = safe_int(entry.get('position'))
405 405 cur_position = safe_int(entry.get('cur_position'))
406 406 if position is None or cur_position is None:
407 407 return
408 408
409 409 # check if this is an existing entry
410 410 is_new = False
411 411 db_entry = UserBookmark().get_by_position_for_user(cur_position, user_id)
412 412
413 413 if db_entry and str2bool(entry.get('remove')):
414 414 log.debug('Marked bookmark %s for deletion', db_entry)
415 415 Session().delete(db_entry)
416 416 return
417 417
418 418 if not db_entry:
419 419 # new
420 420 db_entry = UserBookmark()
421 421 is_new = True
422 422
423 423 should_save = False
424 424 default_redirect_url = ''
425 425
426 426 # save repo
427 427 if entry.get('bookmark_repo') and safe_int(entry.get('bookmark_repo')):
428 428 repo = Repository.get(entry['bookmark_repo'])
429 429 perm_check = HasRepoPermissionAny(
430 430 'repository.read', 'repository.write', 'repository.admin')
431 431 if repo and perm_check(repo_name=repo.repo_name):
432 432 db_entry.repository = repo
433 433 should_save = True
434 434 default_redirect_url = '${repo_url}'
435 435 # save repo group
436 436 elif entry.get('bookmark_repo_group') and safe_int(entry.get('bookmark_repo_group')):
437 437 repo_group = RepoGroup.get(entry['bookmark_repo_group'])
438 438 perm_check = HasRepoGroupPermissionAny(
439 439 'group.read', 'group.write', 'group.admin')
440 440
441 441 if repo_group and perm_check(group_name=repo_group.group_name):
442 442 db_entry.repository_group = repo_group
443 443 should_save = True
444 444 default_redirect_url = '${repo_group_url}'
445 445 # save generic info
446 446 elif entry.get('title') and entry.get('redirect_url'):
447 447 should_save = True
448 448
449 449 if should_save:
450 450 # mark user and position
451 451 db_entry.user_id = user_id
452 452 db_entry.position = position
453 453 db_entry.title = entry.get('title')
454 454 db_entry.redirect_url = entry.get('redirect_url') or default_redirect_url
455 455 log.debug('Saving bookmark %s, new:%s', db_entry, is_new)
456 456
457 457 Session().add(db_entry)
458 458
459 459 @LoginRequired()
460 460 @NotAnonymous()
461 461 @CSRFRequired()
462 462 @view_config(
463 463 route_name='my_account_bookmarks_update', request_method='POST')
464 464 def my_account_bookmarks_update(self):
465 465 _ = self.request.translate
466 466 c = self.load_default_context()
467 467 c.active = 'bookmarks'
468 468
469 469 controls = peppercorn.parse(self.request.POST.items())
470 470 user_id = c.user.user_id
471 471
472 472 # validate positions
473 473 positions = {}
474 474 for entry in controls.get('bookmarks', []):
475 475 position = safe_int(entry['position'])
476 476 if position is None:
477 477 continue
478 478
479 479 if position in positions:
480 480 h.flash(_("Position {} is defined twice. "
481 481 "Please correct this error.").format(position), category='error')
482 482 return HTTPFound(h.route_path('my_account_bookmarks'))
483 483
484 484 entry['position'] = position
485 485 entry['cur_position'] = safe_int(entry.get('cur_position'))
486 486 positions[position] = entry
487 487
488 488 try:
489 489 for entry in positions.values():
490 490 self._process_bookmark_entry(entry, user_id)
491 491
492 492 Session().commit()
493 493 h.flash(_("Update Bookmarks"), category='success')
494 494 except IntegrityError:
495 495 h.flash(_("Failed to update bookmarks. "
496 496 "Make sure an unique position is used."), category='error')
497 497
498 498 return HTTPFound(h.route_path('my_account_bookmarks'))
499 499
500 500 @LoginRequired()
501 501 @NotAnonymous()
502 502 @view_config(
503 503 route_name='my_account_goto_bookmark', request_method='GET',
504 504 renderer='rhodecode:templates/admin/my_account/my_account.mako')
505 505 def my_account_goto_bookmark(self):
506 506
507 507 bookmark_id = self.request.matchdict['bookmark_id']
508 508 user_bookmark = UserBookmark().query()\
509 509 .filter(UserBookmark.user_id == self.request.user.user_id) \
510 510 .filter(UserBookmark.position == bookmark_id).scalar()
511 511
512 512 redirect_url = h.route_path('my_account_bookmarks')
513 513 if not user_bookmark:
514 514 raise HTTPFound(redirect_url)
515 515
516 516 # repository set
517 517 if user_bookmark.repository:
518 518 repo_name = user_bookmark.repository.repo_name
519 519 base_redirect_url = h.route_path(
520 520 'repo_summary', repo_name=repo_name)
521 521 if user_bookmark.redirect_url and \
522 522 '${repo_url}' in user_bookmark.redirect_url:
523 523 redirect_url = string.Template(user_bookmark.redirect_url)\
524 524 .safe_substitute({'repo_url': base_redirect_url})
525 525 else:
526 526 redirect_url = base_redirect_url
527 527 # repository group set
528 528 elif user_bookmark.repository_group:
529 529 repo_group_name = user_bookmark.repository_group.group_name
530 530 base_redirect_url = h.route_path(
531 531 'repo_group_home', repo_group_name=repo_group_name)
532 532 if user_bookmark.redirect_url and \
533 533 '${repo_group_url}' in user_bookmark.redirect_url:
534 534 redirect_url = string.Template(user_bookmark.redirect_url)\
535 535 .safe_substitute({'repo_group_url': base_redirect_url})
536 536 else:
537 537 redirect_url = base_redirect_url
538 538 # custom URL set
539 539 elif user_bookmark.redirect_url:
540 540 server_url = h.route_url('home').rstrip('/')
541 541 redirect_url = string.Template(user_bookmark.redirect_url) \
542 542 .safe_substitute({'server_url': server_url})
543 543
544 544 log.debug('Redirecting bookmark %s to %s', user_bookmark, redirect_url)
545 545 raise HTTPFound(redirect_url)
546 546
547 547 @LoginRequired()
548 548 @NotAnonymous()
549 549 @view_config(
550 550 route_name='my_account_perms', request_method='GET',
551 551 renderer='rhodecode:templates/admin/my_account/my_account.mako')
552 552 def my_account_perms(self):
553 553 c = self.load_default_context()
554 554 c.active = 'perms'
555 555
556 556 c.perm_user = c.auth_user
557 557 return self._get_template_context(c)
558 558
559 559 @LoginRequired()
560 560 @NotAnonymous()
561 561 @view_config(
562 562 route_name='my_account_notifications', request_method='GET',
563 563 renderer='rhodecode:templates/admin/my_account/my_account.mako')
564 564 def my_notifications(self):
565 565 c = self.load_default_context()
566 566 c.active = 'notifications'
567 567
568 568 return self._get_template_context(c)
569 569
570 570 @LoginRequired()
571 571 @NotAnonymous()
572 572 @CSRFRequired()
573 573 @view_config(
574 574 route_name='my_account_notifications_toggle_visibility',
575 575 request_method='POST', renderer='json_ext')
576 576 def my_notifications_toggle_visibility(self):
577 577 user = self._rhodecode_db_user
578 578 new_status = not user.user_data.get('notification_status', True)
579 579 user.update_userdata(notification_status=new_status)
580 580 Session().commit()
581 581 return user.user_data['notification_status']
582 582
583 583 @LoginRequired()
584 584 @NotAnonymous()
585 585 @view_config(
586 586 route_name='my_account_edit',
587 587 request_method='GET',
588 588 renderer='rhodecode:templates/admin/my_account/my_account.mako')
589 589 def my_account_edit(self):
590 590 c = self.load_default_context()
591 591 c.active = 'profile_edit'
592 592 c.extern_type = c.user.extern_type
593 593 c.extern_name = c.user.extern_name
594 594
595 595 schema = user_schema.UserProfileSchema().bind(
596 596 username=c.user.username, user_emails=c.user.emails)
597 597 appstruct = {
598 598 'username': c.user.username,
599 599 'email': c.user.email,
600 600 'firstname': c.user.firstname,
601 601 'lastname': c.user.lastname,
602 602 'description': c.user.description,
603 603 }
604 604 c.form = forms.RcForm(
605 605 schema, appstruct=appstruct,
606 606 action=h.route_path('my_account_update'),
607 607 buttons=(forms.buttons.save, forms.buttons.reset))
608 608
609 609 return self._get_template_context(c)
610 610
611 611 @LoginRequired()
612 612 @NotAnonymous()
613 613 @CSRFRequired()
614 614 @view_config(
615 615 route_name='my_account_update',
616 616 request_method='POST',
617 617 renderer='rhodecode:templates/admin/my_account/my_account.mako')
618 618 def my_account_update(self):
619 619 _ = self.request.translate
620 620 c = self.load_default_context()
621 621 c.active = 'profile_edit'
622 622 c.perm_user = c.auth_user
623 623 c.extern_type = c.user.extern_type
624 624 c.extern_name = c.user.extern_name
625 625
626 626 schema = user_schema.UserProfileSchema().bind(
627 627 username=c.user.username, user_emails=c.user.emails)
628 628 form = forms.RcForm(
629 629 schema, buttons=(forms.buttons.save, forms.buttons.reset))
630 630
631 631 controls = self.request.POST.items()
632 632 try:
633 633 valid_data = form.validate(controls)
634 634 skip_attrs = ['admin', 'active', 'extern_type', 'extern_name',
635 635 'new_password', 'password_confirmation']
636 636 if c.extern_type != "rhodecode":
637 637 # forbid updating username for external accounts
638 638 skip_attrs.append('username')
639 639 old_email = c.user.email
640 640 UserModel().update_user(
641 641 self._rhodecode_user.user_id, skip_attrs=skip_attrs,
642 642 **valid_data)
643 643 if old_email != valid_data['email']:
644 644 old = UserEmailMap.query() \
645 645 .filter(UserEmailMap.user == c.user).filter(UserEmailMap.email == valid_data['email']).first()
646 646 old.email = old_email
647 647 h.flash(_('Your account was updated successfully'), category='success')
648 648 Session().commit()
649 649 except forms.ValidationFailure as e:
650 650 c.form = e
651 651 return self._get_template_context(c)
652 652 except Exception:
653 653 log.exception("Exception updating user")
654 654 h.flash(_('Error occurred during update of user'),
655 655 category='error')
656 656 raise HTTPFound(h.route_path('my_account_profile'))
657 657
658 658 def _get_pull_requests_list(self, statuses):
659 659 draw, start, limit = self._extract_chunk(self.request)
660 660 search_q, order_by, order_dir = self._extract_ordering(self.request)
661 661 _render = self.request.get_partial_renderer(
662 662 'rhodecode:templates/data_table/_dt_elements.mako')
663 663
664 664 pull_requests = PullRequestModel().get_im_participating_in(
665 665 user_id=self._rhodecode_user.user_id,
666 666 statuses=statuses,
667 667 offset=start, length=limit, order_by=order_by,
668 668 order_dir=order_dir)
669 669
670 670 pull_requests_total_count = PullRequestModel().count_im_participating_in(
671 671 user_id=self._rhodecode_user.user_id, statuses=statuses)
672 672
673 673 data = []
674 674 comments_model = CommentsModel()
675 675 for pr in pull_requests:
676 676 repo_id = pr.target_repo_id
677 677 comments = comments_model.get_all_comments(
678 678 repo_id, pull_request=pr)
679 679 owned = pr.user_id == self._rhodecode_user.user_id
680 680
681 681 data.append({
682 682 'target_repo': _render('pullrequest_target_repo',
683 683 pr.target_repo.repo_name),
684 684 'name': _render('pullrequest_name',
685 pr.pull_request_id, pr.work_in_progress,
686 pr.target_repo.repo_name,
685 pr.pull_request_id, pr.pull_request_state,
686 pr.work_in_progress, pr.target_repo.repo_name,
687 687 short=True),
688 688 'name_raw': pr.pull_request_id,
689 689 'status': _render('pullrequest_status',
690 690 pr.calculated_review_status()),
691 691 'title': _render('pullrequest_title', pr.title, pr.description),
692 692 'description': h.escape(pr.description),
693 693 'updated_on': _render('pullrequest_updated_on',
694 694 h.datetime_to_time(pr.updated_on)),
695 695 'updated_on_raw': h.datetime_to_time(pr.updated_on),
696 696 'created_on': _render('pullrequest_updated_on',
697 697 h.datetime_to_time(pr.created_on)),
698 698 'created_on_raw': h.datetime_to_time(pr.created_on),
699 699 'state': pr.pull_request_state,
700 700 'author': _render('pullrequest_author',
701 701 pr.author.full_contact, ),
702 702 'author_raw': pr.author.full_name,
703 703 'comments': _render('pullrequest_comments', len(comments)),
704 704 'comments_raw': len(comments),
705 705 'closed': pr.is_closed(),
706 706 'owned': owned
707 707 })
708 708
709 709 # json used to render the grid
710 710 data = ({
711 711 'draw': draw,
712 712 'data': data,
713 713 'recordsTotal': pull_requests_total_count,
714 714 'recordsFiltered': pull_requests_total_count,
715 715 })
716 716 return data
717 717
718 718 @LoginRequired()
719 719 @NotAnonymous()
720 720 @view_config(
721 721 route_name='my_account_pullrequests',
722 722 request_method='GET',
723 723 renderer='rhodecode:templates/admin/my_account/my_account.mako')
724 724 def my_account_pullrequests(self):
725 725 c = self.load_default_context()
726 726 c.active = 'pullrequests'
727 727 req_get = self.request.GET
728 728
729 729 c.closed = str2bool(req_get.get('pr_show_closed'))
730 730
731 731 return self._get_template_context(c)
732 732
733 733 @LoginRequired()
734 734 @NotAnonymous()
735 735 @view_config(
736 736 route_name='my_account_pullrequests_data',
737 737 request_method='GET', renderer='json_ext')
738 738 def my_account_pullrequests_data(self):
739 739 self.load_default_context()
740 740 req_get = self.request.GET
741 741 closed = str2bool(req_get.get('closed'))
742 742
743 743 statuses = [PullRequest.STATUS_NEW, PullRequest.STATUS_OPEN]
744 744 if closed:
745 745 statuses += [PullRequest.STATUS_CLOSED]
746 746
747 747 data = self._get_pull_requests_list(statuses=statuses)
748 748 return data
749 749
750 750 @LoginRequired()
751 751 @NotAnonymous()
752 752 @view_config(
753 753 route_name='my_account_user_group_membership',
754 754 request_method='GET',
755 755 renderer='rhodecode:templates/admin/my_account/my_account.mako')
756 756 def my_account_user_group_membership(self):
757 757 c = self.load_default_context()
758 758 c.active = 'user_group_membership'
759 759 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
760 760 for group in self._rhodecode_db_user.group_member]
761 761 c.user_groups = json.dumps(groups)
762 762 return self._get_template_context(c)
@@ -1,1482 +1,1476 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2019 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 logging
22 22 import collections
23 23
24 24 import formencode
25 25 import formencode.htmlfill
26 26 import peppercorn
27 27 from pyramid.httpexceptions import (
28 28 HTTPFound, HTTPNotFound, HTTPForbidden, HTTPBadRequest)
29 29 from pyramid.view import view_config
30 30 from pyramid.renderers import render
31 31
32 32 from rhodecode.apps._base import RepoAppView, DataGridAppView
33 33
34 34 from rhodecode.lib import helpers as h, diffs, codeblocks, channelstream
35 35 from rhodecode.lib.base import vcs_operation_context
36 36 from rhodecode.lib.diffs import load_cached_diff, cache_diff, diff_cache_exist
37 37 from rhodecode.lib.ext_json import json
38 38 from rhodecode.lib.auth import (
39 39 LoginRequired, HasRepoPermissionAny, HasRepoPermissionAnyDecorator,
40 40 NotAnonymous, CSRFRequired)
41 41 from rhodecode.lib.utils2 import str2bool, safe_str, safe_unicode
42 42 from rhodecode.lib.vcs.backends.base import EmptyCommit, UpdateFailureReason
43 43 from rhodecode.lib.vcs.exceptions import (CommitDoesNotExistError,
44 44 RepositoryRequirementError, EmptyRepositoryError)
45 45 from rhodecode.model.changeset_status import ChangesetStatusModel
46 46 from rhodecode.model.comment import CommentsModel
47 47 from rhodecode.model.db import (func, or_, PullRequest, PullRequestVersion,
48 48 ChangesetComment, ChangesetStatus, Repository)
49 49 from rhodecode.model.forms import PullRequestForm
50 50 from rhodecode.model.meta import Session
51 51 from rhodecode.model.pull_request import PullRequestModel, MergeCheck
52 52 from rhodecode.model.scm import ScmModel
53 53
54 54 log = logging.getLogger(__name__)
55 55
56 56
57 57 class RepoPullRequestsView(RepoAppView, DataGridAppView):
58 58
59 59 def load_default_context(self):
60 60 c = self._get_local_tmpl_context(include_app_defaults=True)
61 61 c.REVIEW_STATUS_APPROVED = ChangesetStatus.STATUS_APPROVED
62 62 c.REVIEW_STATUS_REJECTED = ChangesetStatus.STATUS_REJECTED
63 63 # backward compat., we use for OLD PRs a plain renderer
64 64 c.renderer = 'plain'
65 65 return c
66 66
67 67 def _get_pull_requests_list(
68 68 self, repo_name, source, filter_type, opened_by, statuses):
69 69
70 70 draw, start, limit = self._extract_chunk(self.request)
71 71 search_q, order_by, order_dir = self._extract_ordering(self.request)
72 72 _render = self.request.get_partial_renderer(
73 73 'rhodecode:templates/data_table/_dt_elements.mako')
74 74
75 75 # pagination
76 76
77 77 if filter_type == 'awaiting_review':
78 78 pull_requests = PullRequestModel().get_awaiting_review(
79 79 repo_name, search_q=search_q, source=source, opened_by=opened_by,
80 80 statuses=statuses, offset=start, length=limit,
81 81 order_by=order_by, order_dir=order_dir)
82 82 pull_requests_total_count = PullRequestModel().count_awaiting_review(
83 83 repo_name, search_q=search_q, source=source, statuses=statuses,
84 84 opened_by=opened_by)
85 85 elif filter_type == 'awaiting_my_review':
86 86 pull_requests = PullRequestModel().get_awaiting_my_review(
87 87 repo_name, search_q=search_q, source=source, opened_by=opened_by,
88 88 user_id=self._rhodecode_user.user_id, statuses=statuses,
89 89 offset=start, length=limit, order_by=order_by,
90 90 order_dir=order_dir)
91 91 pull_requests_total_count = PullRequestModel().count_awaiting_my_review(
92 92 repo_name, search_q=search_q, source=source, user_id=self._rhodecode_user.user_id,
93 93 statuses=statuses, opened_by=opened_by)
94 94 else:
95 95 pull_requests = PullRequestModel().get_all(
96 96 repo_name, search_q=search_q, source=source, opened_by=opened_by,
97 97 statuses=statuses, offset=start, length=limit,
98 98 order_by=order_by, order_dir=order_dir)
99 99 pull_requests_total_count = PullRequestModel().count_all(
100 100 repo_name, search_q=search_q, source=source, statuses=statuses,
101 101 opened_by=opened_by)
102 102
103 103 data = []
104 104 comments_model = CommentsModel()
105 105 for pr in pull_requests:
106 106 comments = comments_model.get_all_comments(
107 107 self.db_repo.repo_id, pull_request=pr)
108 108
109 109 data.append({
110 110 'name': _render('pullrequest_name',
111 pr.pull_request_id, pr.work_in_progress,
112 pr.target_repo.repo_name),
111 pr.pull_request_id, pr.pull_request_state,
112 pr.work_in_progress, pr.target_repo.repo_name),
113 113 'name_raw': pr.pull_request_id,
114 114 'status': _render('pullrequest_status',
115 115 pr.calculated_review_status()),
116 116 'title': _render('pullrequest_title', pr.title, pr.description),
117 117 'description': h.escape(pr.description),
118 118 'updated_on': _render('pullrequest_updated_on',
119 119 h.datetime_to_time(pr.updated_on)),
120 120 'updated_on_raw': h.datetime_to_time(pr.updated_on),
121 121 'created_on': _render('pullrequest_updated_on',
122 122 h.datetime_to_time(pr.created_on)),
123 123 'created_on_raw': h.datetime_to_time(pr.created_on),
124 124 'state': pr.pull_request_state,
125 125 'author': _render('pullrequest_author',
126 126 pr.author.full_contact, ),
127 127 'author_raw': pr.author.full_name,
128 128 'comments': _render('pullrequest_comments', len(comments)),
129 129 'comments_raw': len(comments),
130 130 'closed': pr.is_closed(),
131 131 })
132 132
133 133 data = ({
134 134 'draw': draw,
135 135 'data': data,
136 136 'recordsTotal': pull_requests_total_count,
137 137 'recordsFiltered': pull_requests_total_count,
138 138 })
139 139 return data
140 140
141 141 @LoginRequired()
142 142 @HasRepoPermissionAnyDecorator(
143 143 'repository.read', 'repository.write', 'repository.admin')
144 144 @view_config(
145 145 route_name='pullrequest_show_all', request_method='GET',
146 146 renderer='rhodecode:templates/pullrequests/pullrequests.mako')
147 147 def pull_request_list(self):
148 148 c = self.load_default_context()
149 149
150 150 req_get = self.request.GET
151 151 c.source = str2bool(req_get.get('source'))
152 152 c.closed = str2bool(req_get.get('closed'))
153 153 c.my = str2bool(req_get.get('my'))
154 154 c.awaiting_review = str2bool(req_get.get('awaiting_review'))
155 155 c.awaiting_my_review = str2bool(req_get.get('awaiting_my_review'))
156 156
157 157 c.active = 'open'
158 158 if c.my:
159 159 c.active = 'my'
160 160 if c.closed:
161 161 c.active = 'closed'
162 162 if c.awaiting_review and not c.source:
163 163 c.active = 'awaiting'
164 164 if c.source and not c.awaiting_review:
165 165 c.active = 'source'
166 166 if c.awaiting_my_review:
167 167 c.active = 'awaiting_my'
168 168
169 169 return self._get_template_context(c)
170 170
171 171 @LoginRequired()
172 172 @HasRepoPermissionAnyDecorator(
173 173 'repository.read', 'repository.write', 'repository.admin')
174 174 @view_config(
175 175 route_name='pullrequest_show_all_data', request_method='GET',
176 176 renderer='json_ext', xhr=True)
177 177 def pull_request_list_data(self):
178 178 self.load_default_context()
179 179
180 180 # additional filters
181 181 req_get = self.request.GET
182 182 source = str2bool(req_get.get('source'))
183 183 closed = str2bool(req_get.get('closed'))
184 184 my = str2bool(req_get.get('my'))
185 185 awaiting_review = str2bool(req_get.get('awaiting_review'))
186 186 awaiting_my_review = str2bool(req_get.get('awaiting_my_review'))
187 187
188 188 filter_type = 'awaiting_review' if awaiting_review \
189 189 else 'awaiting_my_review' if awaiting_my_review \
190 190 else None
191 191
192 192 opened_by = None
193 193 if my:
194 194 opened_by = [self._rhodecode_user.user_id]
195 195
196 196 statuses = [PullRequest.STATUS_NEW, PullRequest.STATUS_OPEN]
197 197 if closed:
198 198 statuses = [PullRequest.STATUS_CLOSED]
199 199
200 200 data = self._get_pull_requests_list(
201 201 repo_name=self.db_repo_name, source=source,
202 202 filter_type=filter_type, opened_by=opened_by, statuses=statuses)
203 203
204 204 return data
205 205
206 206 def _is_diff_cache_enabled(self, target_repo):
207 207 caching_enabled = self._get_general_setting(
208 208 target_repo, 'rhodecode_diff_cache')
209 209 log.debug('Diff caching enabled: %s', caching_enabled)
210 210 return caching_enabled
211 211
212 212 def _get_diffset(self, source_repo_name, source_repo,
213 213 source_ref_id, target_ref_id,
214 214 target_commit, source_commit, diff_limit, file_limit,
215 215 fulldiff, hide_whitespace_changes, diff_context):
216 216
217 217 vcs_diff = PullRequestModel().get_diff(
218 218 source_repo, source_ref_id, target_ref_id,
219 219 hide_whitespace_changes, diff_context)
220 220
221 221 diff_processor = diffs.DiffProcessor(
222 222 vcs_diff, format='newdiff', diff_limit=diff_limit,
223 223 file_limit=file_limit, show_full_diff=fulldiff)
224 224
225 225 _parsed = diff_processor.prepare()
226 226
227 227 diffset = codeblocks.DiffSet(
228 228 repo_name=self.db_repo_name,
229 229 source_repo_name=source_repo_name,
230 230 source_node_getter=codeblocks.diffset_node_getter(target_commit),
231 231 target_node_getter=codeblocks.diffset_node_getter(source_commit),
232 232 )
233 233 diffset = self.path_filter.render_patchset_filtered(
234 234 diffset, _parsed, target_commit.raw_id, source_commit.raw_id)
235 235
236 236 return diffset
237 237
238 238 def _get_range_diffset(self, source_scm, source_repo,
239 239 commit1, commit2, diff_limit, file_limit,
240 240 fulldiff, hide_whitespace_changes, diff_context):
241 241 vcs_diff = source_scm.get_diff(
242 242 commit1, commit2,
243 243 ignore_whitespace=hide_whitespace_changes,
244 244 context=diff_context)
245 245
246 246 diff_processor = diffs.DiffProcessor(
247 247 vcs_diff, format='newdiff', diff_limit=diff_limit,
248 248 file_limit=file_limit, show_full_diff=fulldiff)
249 249
250 250 _parsed = diff_processor.prepare()
251 251
252 252 diffset = codeblocks.DiffSet(
253 253 repo_name=source_repo.repo_name,
254 254 source_node_getter=codeblocks.diffset_node_getter(commit1),
255 255 target_node_getter=codeblocks.diffset_node_getter(commit2))
256 256
257 257 diffset = self.path_filter.render_patchset_filtered(
258 258 diffset, _parsed, commit1.raw_id, commit2.raw_id)
259 259
260 260 return diffset
261 261
262 262 @LoginRequired()
263 263 @HasRepoPermissionAnyDecorator(
264 264 'repository.read', 'repository.write', 'repository.admin')
265 265 @view_config(
266 266 route_name='pullrequest_show', request_method='GET',
267 267 renderer='rhodecode:templates/pullrequests/pullrequest_show.mako')
268 268 def pull_request_show(self):
269 269 _ = self.request.translate
270 270 c = self.load_default_context()
271 271
272 272 pull_request = PullRequest.get_or_404(
273 273 self.request.matchdict['pull_request_id'])
274 274 pull_request_id = pull_request.pull_request_id
275 275
276 if pull_request.pull_request_state != PullRequest.STATE_CREATED:
277 log.debug('show: forbidden because pull request is in state %s',
278 pull_request.pull_request_state)
279 msg = _(u'Cannot show pull requests in state other than `{}`. '
280 u'Current state is: `{}`').format(PullRequest.STATE_CREATED,
281 pull_request.pull_request_state)
282 h.flash(msg, category='error')
283 raise HTTPFound(h.route_path('pullrequest_show_all',
284 repo_name=self.db_repo_name))
276 c.state_progressing = pull_request.is_state_changing()
285 277
286 278 version = self.request.GET.get('version')
287 279 from_version = self.request.GET.get('from_version') or version
288 280 merge_checks = self.request.GET.get('merge_checks')
289 281 c.fulldiff = str2bool(self.request.GET.get('fulldiff'))
290 282
291 283 # fetch global flags of ignore ws or context lines
292 284 diff_context = diffs.get_diff_context(self.request)
293 285 hide_whitespace_changes = diffs.get_diff_whitespace_flag(self.request)
294 286
295 287 force_refresh = str2bool(self.request.GET.get('force_refresh'))
296 288
297 289 (pull_request_latest,
298 290 pull_request_at_ver,
299 291 pull_request_display_obj,
300 292 at_version) = PullRequestModel().get_pr_version(
301 293 pull_request_id, version=version)
302 294 pr_closed = pull_request_latest.is_closed()
303 295
304 296 if pr_closed and (version or from_version):
305 297 # not allow to browse versions
306 298 raise HTTPFound(h.route_path(
307 299 'pullrequest_show', repo_name=self.db_repo_name,
308 300 pull_request_id=pull_request_id))
309 301
310 302 versions = pull_request_display_obj.versions()
311 303 # used to store per-commit range diffs
312 304 c.changes = collections.OrderedDict()
313 305 c.range_diff_on = self.request.GET.get('range-diff') == "1"
314 306
315 307 c.at_version = at_version
316 308 c.at_version_num = (at_version
317 309 if at_version and at_version != 'latest'
318 310 else None)
319 311 c.at_version_pos = ChangesetComment.get_index_from_version(
320 312 c.at_version_num, versions)
321 313
322 314 (prev_pull_request_latest,
323 315 prev_pull_request_at_ver,
324 316 prev_pull_request_display_obj,
325 317 prev_at_version) = PullRequestModel().get_pr_version(
326 318 pull_request_id, version=from_version)
327 319
328 320 c.from_version = prev_at_version
329 321 c.from_version_num = (prev_at_version
330 322 if prev_at_version and prev_at_version != 'latest'
331 323 else None)
332 324 c.from_version_pos = ChangesetComment.get_index_from_version(
333 325 c.from_version_num, versions)
334 326
335 327 # define if we're in COMPARE mode or VIEW at version mode
336 328 compare = at_version != prev_at_version
337 329
338 330 # pull_requests repo_name we opened it against
339 331 # ie. target_repo must match
340 332 if self.db_repo_name != pull_request_at_ver.target_repo.repo_name:
341 333 raise HTTPNotFound()
342 334
343 335 c.shadow_clone_url = PullRequestModel().get_shadow_clone_url(
344 336 pull_request_at_ver)
345 337
346 338 c.pull_request = pull_request_display_obj
347 339 c.renderer = pull_request_at_ver.description_renderer or c.renderer
348 340 c.pull_request_latest = pull_request_latest
349 341
350 342 if compare or (at_version and not at_version == 'latest'):
351 343 c.allowed_to_change_status = False
352 344 c.allowed_to_update = False
353 345 c.allowed_to_merge = False
354 346 c.allowed_to_delete = False
355 347 c.allowed_to_comment = False
356 348 c.allowed_to_close = False
357 349 else:
358 350 can_change_status = PullRequestModel().check_user_change_status(
359 351 pull_request_at_ver, self._rhodecode_user)
360 352 c.allowed_to_change_status = can_change_status and not pr_closed
361 353
362 354 c.allowed_to_update = PullRequestModel().check_user_update(
363 355 pull_request_latest, self._rhodecode_user) and not pr_closed
364 356 c.allowed_to_merge = PullRequestModel().check_user_merge(
365 357 pull_request_latest, self._rhodecode_user) and not pr_closed
366 358 c.allowed_to_delete = PullRequestModel().check_user_delete(
367 359 pull_request_latest, self._rhodecode_user) and not pr_closed
368 360 c.allowed_to_comment = not pr_closed
369 361 c.allowed_to_close = c.allowed_to_merge and not pr_closed
370 362
371 363 c.forbid_adding_reviewers = False
372 364 c.forbid_author_to_review = False
373 365 c.forbid_commit_author_to_review = False
374 366
375 367 if pull_request_latest.reviewer_data and \
376 368 'rules' in pull_request_latest.reviewer_data:
377 369 rules = pull_request_latest.reviewer_data['rules'] or {}
378 370 try:
379 371 c.forbid_adding_reviewers = rules.get(
380 372 'forbid_adding_reviewers')
381 373 c.forbid_author_to_review = rules.get(
382 374 'forbid_author_to_review')
383 375 c.forbid_commit_author_to_review = rules.get(
384 376 'forbid_commit_author_to_review')
385 377 except Exception:
386 378 pass
387 379
388 380 # check merge capabilities
389 381 _merge_check = MergeCheck.validate(
390 382 pull_request_latest, auth_user=self._rhodecode_user,
391 383 translator=self.request.translate,
392 384 force_shadow_repo_refresh=force_refresh)
393 385 c.pr_merge_errors = _merge_check.error_details
394 386 c.pr_merge_possible = not _merge_check.failed
395 387 c.pr_merge_message = _merge_check.merge_msg
396 388
397 389 c.pr_merge_info = MergeCheck.get_merge_conditions(
398 390 pull_request_latest, translator=self.request.translate)
399 391
400 392 c.pull_request_review_status = _merge_check.review_status
401 393 if merge_checks:
402 394 self.request.override_renderer = \
403 395 'rhodecode:templates/pullrequests/pullrequest_merge_checks.mako'
404 396 return self._get_template_context(c)
405 397
406 398 comments_model = CommentsModel()
407 399
408 400 # reviewers and statuses
409 401 c.pull_request_reviewers = pull_request_at_ver.reviewers_statuses()
410 402 allowed_reviewers = [x[0].user_id for x in c.pull_request_reviewers]
411 403
412 404 # GENERAL COMMENTS with versions #
413 405 q = comments_model._all_general_comments_of_pull_request(pull_request_latest)
414 406 q = q.order_by(ChangesetComment.comment_id.asc())
415 407 general_comments = q
416 408
417 409 # pick comments we want to render at current version
418 410 c.comment_versions = comments_model.aggregate_comments(
419 411 general_comments, versions, c.at_version_num)
420 412 c.comments = c.comment_versions[c.at_version_num]['until']
421 413
422 414 # INLINE COMMENTS with versions #
423 415 q = comments_model._all_inline_comments_of_pull_request(pull_request_latest)
424 416 q = q.order_by(ChangesetComment.comment_id.asc())
425 417 inline_comments = q
426 418
427 419 c.inline_versions = comments_model.aggregate_comments(
428 420 inline_comments, versions, c.at_version_num, inline=True)
429 421
430 422 # TODOs
431 423 c.unresolved_comments = CommentsModel() \
432 424 .get_pull_request_unresolved_todos(pull_request)
433 425 c.resolved_comments = CommentsModel() \
434 426 .get_pull_request_resolved_todos(pull_request)
435 427
436 428 # inject latest version
437 429 latest_ver = PullRequest.get_pr_display_object(
438 430 pull_request_latest, pull_request_latest)
439 431
440 432 c.versions = versions + [latest_ver]
441 433
442 434 # if we use version, then do not show later comments
443 435 # than current version
444 436 display_inline_comments = collections.defaultdict(
445 437 lambda: collections.defaultdict(list))
446 438 for co in inline_comments:
447 439 if c.at_version_num:
448 440 # pick comments that are at least UPTO given version, so we
449 441 # don't render comments for higher version
450 442 should_render = co.pull_request_version_id and \
451 443 co.pull_request_version_id <= c.at_version_num
452 444 else:
453 445 # showing all, for 'latest'
454 446 should_render = True
455 447
456 448 if should_render:
457 449 display_inline_comments[co.f_path][co.line_no].append(co)
458 450
459 451 # load diff data into template context, if we use compare mode then
460 452 # diff is calculated based on changes between versions of PR
461 453
462 454 source_repo = pull_request_at_ver.source_repo
463 455 source_ref_id = pull_request_at_ver.source_ref_parts.commit_id
464 456
465 457 target_repo = pull_request_at_ver.target_repo
466 458 target_ref_id = pull_request_at_ver.target_ref_parts.commit_id
467 459
468 460 if compare:
469 461 # in compare switch the diff base to latest commit from prev version
470 462 target_ref_id = prev_pull_request_display_obj.revisions[0]
471 463
472 464 # despite opening commits for bookmarks/branches/tags, we always
473 465 # convert this to rev to prevent changes after bookmark or branch change
474 466 c.source_ref_type = 'rev'
475 467 c.source_ref = source_ref_id
476 468
477 469 c.target_ref_type = 'rev'
478 470 c.target_ref = target_ref_id
479 471
480 472 c.source_repo = source_repo
481 473 c.target_repo = target_repo
482 474
483 475 c.commit_ranges = []
484 476 source_commit = EmptyCommit()
485 477 target_commit = EmptyCommit()
486 478 c.missing_requirements = False
487 479
488 480 source_scm = source_repo.scm_instance()
489 481 target_scm = target_repo.scm_instance()
490 482
491 483 shadow_scm = None
492 484 try:
493 485 shadow_scm = pull_request_latest.get_shadow_repo()
494 486 except Exception:
495 487 log.debug('Failed to get shadow repo', exc_info=True)
496 488 # try first the existing source_repo, and then shadow
497 489 # repo if we can obtain one
498 490 commits_source_repo = source_scm or shadow_scm
499 491
500 492 c.commits_source_repo = commits_source_repo
501 493 c.ancestor = None # set it to None, to hide it from PR view
502 494
503 495 # empty version means latest, so we keep this to prevent
504 496 # double caching
505 497 version_normalized = version or 'latest'
506 498 from_version_normalized = from_version or 'latest'
507 499
508 500 cache_path = self.rhodecode_vcs_repo.get_create_shadow_cache_pr_path(target_repo)
509 501 cache_file_path = diff_cache_exist(
510 502 cache_path, 'pull_request', pull_request_id, version_normalized,
511 503 from_version_normalized, source_ref_id, target_ref_id,
512 504 hide_whitespace_changes, diff_context, c.fulldiff)
513 505
514 506 caching_enabled = self._is_diff_cache_enabled(c.target_repo)
515 507 force_recache = self.get_recache_flag()
516 508
517 509 cached_diff = None
518 510 if caching_enabled:
519 511 cached_diff = load_cached_diff(cache_file_path)
520 512
521 513 has_proper_commit_cache = (
522 514 cached_diff and cached_diff.get('commits')
523 515 and len(cached_diff.get('commits', [])) == 5
524 516 and cached_diff.get('commits')[0]
525 517 and cached_diff.get('commits')[3])
526 518
527 519 if not force_recache and not c.range_diff_on and has_proper_commit_cache:
528 520 diff_commit_cache = \
529 521 (ancestor_commit, commit_cache, missing_requirements,
530 522 source_commit, target_commit) = cached_diff['commits']
531 523 else:
532 524 diff_commit_cache = \
533 525 (ancestor_commit, commit_cache, missing_requirements,
534 526 source_commit, target_commit) = self.get_commits(
535 527 commits_source_repo,
536 528 pull_request_at_ver,
537 529 source_commit,
538 530 source_ref_id,
539 531 source_scm,
540 532 target_commit,
541 533 target_ref_id,
542 534 target_scm)
543 535
544 536 # register our commit range
545 537 for comm in commit_cache.values():
546 538 c.commit_ranges.append(comm)
547 539
548 540 c.missing_requirements = missing_requirements
549 541 c.ancestor_commit = ancestor_commit
550 542 c.statuses = source_repo.statuses(
551 543 [x.raw_id for x in c.commit_ranges])
552 544
553 545 # auto collapse if we have more than limit
554 546 collapse_limit = diffs.DiffProcessor._collapse_commits_over
555 547 c.collapse_all_commits = len(c.commit_ranges) > collapse_limit
556 548 c.compare_mode = compare
557 549
558 550 # diff_limit is the old behavior, will cut off the whole diff
559 551 # if the limit is applied otherwise will just hide the
560 552 # big files from the front-end
561 553 diff_limit = c.visual.cut_off_limit_diff
562 554 file_limit = c.visual.cut_off_limit_file
563 555
564 556 c.missing_commits = False
565 557 if (c.missing_requirements
566 558 or isinstance(source_commit, EmptyCommit)
567 559 or source_commit == target_commit):
568 560
569 561 c.missing_commits = True
570 562 else:
571 563 c.inline_comments = display_inline_comments
572 564
573 565 has_proper_diff_cache = cached_diff and cached_diff.get('commits')
574 566 if not force_recache and has_proper_diff_cache:
575 567 c.diffset = cached_diff['diff']
576 568 (ancestor_commit, commit_cache, missing_requirements,
577 569 source_commit, target_commit) = cached_diff['commits']
578 570 else:
579 571 c.diffset = self._get_diffset(
580 572 c.source_repo.repo_name, commits_source_repo,
581 573 source_ref_id, target_ref_id,
582 574 target_commit, source_commit,
583 575 diff_limit, file_limit, c.fulldiff,
584 576 hide_whitespace_changes, diff_context)
585 577
586 578 # save cached diff
587 579 if caching_enabled:
588 580 cache_diff(cache_file_path, c.diffset, diff_commit_cache)
589 581
590 582 c.limited_diff = c.diffset.limited_diff
591 583
592 584 # calculate removed files that are bound to comments
593 585 comment_deleted_files = [
594 586 fname for fname in display_inline_comments
595 587 if fname not in c.diffset.file_stats]
596 588
597 589 c.deleted_files_comments = collections.defaultdict(dict)
598 590 for fname, per_line_comments in display_inline_comments.items():
599 591 if fname in comment_deleted_files:
600 592 c.deleted_files_comments[fname]['stats'] = 0
601 593 c.deleted_files_comments[fname]['comments'] = list()
602 594 for lno, comments in per_line_comments.items():
603 595 c.deleted_files_comments[fname]['comments'].extend(comments)
604 596
605 597 # maybe calculate the range diff
606 598 if c.range_diff_on:
607 599 # TODO(marcink): set whitespace/context
608 600 context_lcl = 3
609 601 ign_whitespace_lcl = False
610 602
611 603 for commit in c.commit_ranges:
612 604 commit2 = commit
613 605 commit1 = commit.first_parent
614 606
615 607 range_diff_cache_file_path = diff_cache_exist(
616 608 cache_path, 'diff', commit.raw_id,
617 609 ign_whitespace_lcl, context_lcl, c.fulldiff)
618 610
619 611 cached_diff = None
620 612 if caching_enabled:
621 613 cached_diff = load_cached_diff(range_diff_cache_file_path)
622 614
623 615 has_proper_diff_cache = cached_diff and cached_diff.get('diff')
624 616 if not force_recache and has_proper_diff_cache:
625 617 diffset = cached_diff['diff']
626 618 else:
627 619 diffset = self._get_range_diffset(
628 620 source_scm, source_repo,
629 621 commit1, commit2, diff_limit, file_limit,
630 622 c.fulldiff, ign_whitespace_lcl, context_lcl
631 623 )
632 624
633 625 # save cached diff
634 626 if caching_enabled:
635 627 cache_diff(range_diff_cache_file_path, diffset, None)
636 628
637 629 c.changes[commit.raw_id] = diffset
638 630
639 631 # this is a hack to properly display links, when creating PR, the
640 632 # compare view and others uses different notation, and
641 633 # compare_commits.mako renders links based on the target_repo.
642 634 # We need to swap that here to generate it properly on the html side
643 635 c.target_repo = c.source_repo
644 636
645 637 c.commit_statuses = ChangesetStatus.STATUSES
646 638
647 639 c.show_version_changes = not pr_closed
648 640 if c.show_version_changes:
649 641 cur_obj = pull_request_at_ver
650 642 prev_obj = prev_pull_request_at_ver
651 643
652 644 old_commit_ids = prev_obj.revisions
653 645 new_commit_ids = cur_obj.revisions
654 646 commit_changes = PullRequestModel()._calculate_commit_id_changes(
655 647 old_commit_ids, new_commit_ids)
656 648 c.commit_changes_summary = commit_changes
657 649
658 650 # calculate the diff for commits between versions
659 651 c.commit_changes = []
660 652 mark = lambda cs, fw: list(
661 653 h.itertools.izip_longest([], cs, fillvalue=fw))
662 654 for c_type, raw_id in mark(commit_changes.added, 'a') \
663 655 + mark(commit_changes.removed, 'r') \
664 656 + mark(commit_changes.common, 'c'):
665 657
666 658 if raw_id in commit_cache:
667 659 commit = commit_cache[raw_id]
668 660 else:
669 661 try:
670 662 commit = commits_source_repo.get_commit(raw_id)
671 663 except CommitDoesNotExistError:
672 664 # in case we fail extracting still use "dummy" commit
673 665 # for display in commit diff
674 666 commit = h.AttributeDict(
675 667 {'raw_id': raw_id,
676 668 'message': 'EMPTY or MISSING COMMIT'})
677 669 c.commit_changes.append([c_type, commit])
678 670
679 671 # current user review statuses for each version
680 672 c.review_versions = {}
681 673 if self._rhodecode_user.user_id in allowed_reviewers:
682 674 for co in general_comments:
683 675 if co.author.user_id == self._rhodecode_user.user_id:
684 676 status = co.status_change
685 677 if status:
686 678 _ver_pr = status[0].comment.pull_request_version_id
687 679 c.review_versions[_ver_pr] = status[0]
688 680
689 681 return self._get_template_context(c)
690 682
691 683 def get_commits(
692 684 self, commits_source_repo, pull_request_at_ver, source_commit,
693 685 source_ref_id, source_scm, target_commit, target_ref_id, target_scm):
694 686 commit_cache = collections.OrderedDict()
695 687 missing_requirements = False
696 688 try:
697 689 pre_load = ["author", "date", "message", "branch", "parents"]
698 690 show_revs = pull_request_at_ver.revisions
699 691 for rev in show_revs:
700 692 comm = commits_source_repo.get_commit(
701 693 commit_id=rev, pre_load=pre_load)
702 694 commit_cache[comm.raw_id] = comm
703 695
704 696 # Order here matters, we first need to get target, and then
705 697 # the source
706 698 target_commit = commits_source_repo.get_commit(
707 699 commit_id=safe_str(target_ref_id))
708 700
709 701 source_commit = commits_source_repo.get_commit(
710 702 commit_id=safe_str(source_ref_id))
711 703 except CommitDoesNotExistError:
712 704 log.warning(
713 705 'Failed to get commit from `{}` repo'.format(
714 706 commits_source_repo), exc_info=True)
715 707 except RepositoryRequirementError:
716 708 log.warning(
717 709 'Failed to get all required data from repo', exc_info=True)
718 710 missing_requirements = True
719 711 ancestor_commit = None
720 712 try:
721 713 ancestor_id = source_scm.get_common_ancestor(
722 714 source_commit.raw_id, target_commit.raw_id, target_scm)
723 715 ancestor_commit = source_scm.get_commit(ancestor_id)
724 716 except Exception:
725 717 ancestor_commit = None
726 718 return ancestor_commit, commit_cache, missing_requirements, source_commit, target_commit
727 719
728 720 def assure_not_empty_repo(self):
729 721 _ = self.request.translate
730 722
731 723 try:
732 724 self.db_repo.scm_instance().get_commit()
733 725 except EmptyRepositoryError:
734 726 h.flash(h.literal(_('There are no commits yet')),
735 727 category='warning')
736 728 raise HTTPFound(
737 729 h.route_path('repo_summary', repo_name=self.db_repo.repo_name))
738 730
739 731 @LoginRequired()
740 732 @NotAnonymous()
741 733 @HasRepoPermissionAnyDecorator(
742 734 'repository.read', 'repository.write', 'repository.admin')
743 735 @view_config(
744 736 route_name='pullrequest_new', request_method='GET',
745 737 renderer='rhodecode:templates/pullrequests/pullrequest.mako')
746 738 def pull_request_new(self):
747 739 _ = self.request.translate
748 740 c = self.load_default_context()
749 741
750 742 self.assure_not_empty_repo()
751 743 source_repo = self.db_repo
752 744
753 745 commit_id = self.request.GET.get('commit')
754 746 branch_ref = self.request.GET.get('branch')
755 747 bookmark_ref = self.request.GET.get('bookmark')
756 748
757 749 try:
758 750 source_repo_data = PullRequestModel().generate_repo_data(
759 751 source_repo, commit_id=commit_id,
760 752 branch=branch_ref, bookmark=bookmark_ref,
761 753 translator=self.request.translate)
762 754 except CommitDoesNotExistError as e:
763 755 log.exception(e)
764 756 h.flash(_('Commit does not exist'), 'error')
765 757 raise HTTPFound(
766 758 h.route_path('pullrequest_new', repo_name=source_repo.repo_name))
767 759
768 760 default_target_repo = source_repo
769 761
770 762 if source_repo.parent and c.has_origin_repo_read_perm:
771 763 parent_vcs_obj = source_repo.parent.scm_instance()
772 764 if parent_vcs_obj and not parent_vcs_obj.is_empty():
773 765 # change default if we have a parent repo
774 766 default_target_repo = source_repo.parent
775 767
776 768 target_repo_data = PullRequestModel().generate_repo_data(
777 769 default_target_repo, translator=self.request.translate)
778 770
779 771 selected_source_ref = source_repo_data['refs']['selected_ref']
780 772 title_source_ref = ''
781 773 if selected_source_ref:
782 774 title_source_ref = selected_source_ref.split(':', 2)[1]
783 775 c.default_title = PullRequestModel().generate_pullrequest_title(
784 776 source=source_repo.repo_name,
785 777 source_ref=title_source_ref,
786 778 target=default_target_repo.repo_name
787 779 )
788 780
789 781 c.default_repo_data = {
790 782 'source_repo_name': source_repo.repo_name,
791 783 'source_refs_json': json.dumps(source_repo_data),
792 784 'target_repo_name': default_target_repo.repo_name,
793 785 'target_refs_json': json.dumps(target_repo_data),
794 786 }
795 787 c.default_source_ref = selected_source_ref
796 788
797 789 return self._get_template_context(c)
798 790
799 791 @LoginRequired()
800 792 @NotAnonymous()
801 793 @HasRepoPermissionAnyDecorator(
802 794 'repository.read', 'repository.write', 'repository.admin')
803 795 @view_config(
804 796 route_name='pullrequest_repo_refs', request_method='GET',
805 797 renderer='json_ext', xhr=True)
806 798 def pull_request_repo_refs(self):
807 799 self.load_default_context()
808 800 target_repo_name = self.request.matchdict['target_repo_name']
809 801 repo = Repository.get_by_repo_name(target_repo_name)
810 802 if not repo:
811 803 raise HTTPNotFound()
812 804
813 805 target_perm = HasRepoPermissionAny(
814 806 'repository.read', 'repository.write', 'repository.admin')(
815 807 target_repo_name)
816 808 if not target_perm:
817 809 raise HTTPNotFound()
818 810
819 811 return PullRequestModel().generate_repo_data(
820 812 repo, translator=self.request.translate)
821 813
822 814 @LoginRequired()
823 815 @NotAnonymous()
824 816 @HasRepoPermissionAnyDecorator(
825 817 'repository.read', 'repository.write', 'repository.admin')
826 818 @view_config(
827 819 route_name='pullrequest_repo_targets', request_method='GET',
828 820 renderer='json_ext', xhr=True)
829 821 def pullrequest_repo_targets(self):
830 822 _ = self.request.translate
831 823 filter_query = self.request.GET.get('query')
832 824
833 825 # get the parents
834 826 parent_target_repos = []
835 827 if self.db_repo.parent:
836 828 parents_query = Repository.query() \
837 829 .order_by(func.length(Repository.repo_name)) \
838 830 .filter(Repository.fork_id == self.db_repo.parent.repo_id)
839 831
840 832 if filter_query:
841 833 ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
842 834 parents_query = parents_query.filter(
843 835 Repository.repo_name.ilike(ilike_expression))
844 836 parents = parents_query.limit(20).all()
845 837
846 838 for parent in parents:
847 839 parent_vcs_obj = parent.scm_instance()
848 840 if parent_vcs_obj and not parent_vcs_obj.is_empty():
849 841 parent_target_repos.append(parent)
850 842
851 843 # get other forks, and repo itself
852 844 query = Repository.query() \
853 845 .order_by(func.length(Repository.repo_name)) \
854 846 .filter(
855 847 or_(Repository.repo_id == self.db_repo.repo_id, # repo itself
856 848 Repository.fork_id == self.db_repo.repo_id) # forks of this repo
857 849 ) \
858 850 .filter(~Repository.repo_id.in_([x.repo_id for x in parent_target_repos]))
859 851
860 852 if filter_query:
861 853 ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
862 854 query = query.filter(Repository.repo_name.ilike(ilike_expression))
863 855
864 856 limit = max(20 - len(parent_target_repos), 5) # not less then 5
865 857 target_repos = query.limit(limit).all()
866 858
867 859 all_target_repos = target_repos + parent_target_repos
868 860
869 861 repos = []
870 862 # This checks permissions to the repositories
871 863 for obj in ScmModel().get_repos(all_target_repos):
872 864 repos.append({
873 865 'id': obj['name'],
874 866 'text': obj['name'],
875 867 'type': 'repo',
876 868 'repo_id': obj['dbrepo']['repo_id'],
877 869 'repo_type': obj['dbrepo']['repo_type'],
878 870 'private': obj['dbrepo']['private'],
879 871
880 872 })
881 873
882 874 data = {
883 875 'more': False,
884 876 'results': [{
885 877 'text': _('Repositories'),
886 878 'children': repos
887 879 }] if repos else []
888 880 }
889 881 return data
890 882
891 883 @LoginRequired()
892 884 @NotAnonymous()
893 885 @HasRepoPermissionAnyDecorator(
894 886 'repository.read', 'repository.write', 'repository.admin')
895 887 @CSRFRequired()
896 888 @view_config(
897 889 route_name='pullrequest_create', request_method='POST',
898 890 renderer=None)
899 891 def pull_request_create(self):
900 892 _ = self.request.translate
901 893 self.assure_not_empty_repo()
902 894 self.load_default_context()
903 895
904 896 controls = peppercorn.parse(self.request.POST.items())
905 897
906 898 try:
907 899 form = PullRequestForm(
908 900 self.request.translate, self.db_repo.repo_id)()
909 901 _form = form.to_python(controls)
910 902 except formencode.Invalid as errors:
911 903 if errors.error_dict.get('revisions'):
912 904 msg = 'Revisions: %s' % errors.error_dict['revisions']
913 905 elif errors.error_dict.get('pullrequest_title'):
914 906 msg = errors.error_dict.get('pullrequest_title')
915 907 else:
916 908 msg = _('Error creating pull request: {}').format(errors)
917 909 log.exception(msg)
918 910 h.flash(msg, 'error')
919 911
920 912 # would rather just go back to form ...
921 913 raise HTTPFound(
922 914 h.route_path('pullrequest_new', repo_name=self.db_repo_name))
923 915
924 916 source_repo = _form['source_repo']
925 917 source_ref = _form['source_ref']
926 918 target_repo = _form['target_repo']
927 919 target_ref = _form['target_ref']
928 920 commit_ids = _form['revisions'][::-1]
929 921
930 922 # find the ancestor for this pr
931 923 source_db_repo = Repository.get_by_repo_name(_form['source_repo'])
932 924 target_db_repo = Repository.get_by_repo_name(_form['target_repo'])
933 925
934 926 if not (source_db_repo or target_db_repo):
935 927 h.flash(_('source_repo or target repo not found'), category='error')
936 928 raise HTTPFound(
937 929 h.route_path('pullrequest_new', repo_name=self.db_repo_name))
938 930
939 931 # re-check permissions again here
940 932 # source_repo we must have read permissions
941 933
942 934 source_perm = HasRepoPermissionAny(
943 935 'repository.read', 'repository.write', 'repository.admin')(
944 936 source_db_repo.repo_name)
945 937 if not source_perm:
946 938 msg = _('Not Enough permissions to source repo `{}`.'.format(
947 939 source_db_repo.repo_name))
948 940 h.flash(msg, category='error')
949 941 # copy the args back to redirect
950 942 org_query = self.request.GET.mixed()
951 943 raise HTTPFound(
952 944 h.route_path('pullrequest_new', repo_name=self.db_repo_name,
953 945 _query=org_query))
954 946
955 947 # target repo we must have read permissions, and also later on
956 948 # we want to check branch permissions here
957 949 target_perm = HasRepoPermissionAny(
958 950 'repository.read', 'repository.write', 'repository.admin')(
959 951 target_db_repo.repo_name)
960 952 if not target_perm:
961 953 msg = _('Not Enough permissions to target repo `{}`.'.format(
962 954 target_db_repo.repo_name))
963 955 h.flash(msg, category='error')
964 956 # copy the args back to redirect
965 957 org_query = self.request.GET.mixed()
966 958 raise HTTPFound(
967 959 h.route_path('pullrequest_new', repo_name=self.db_repo_name,
968 960 _query=org_query))
969 961
970 962 source_scm = source_db_repo.scm_instance()
971 963 target_scm = target_db_repo.scm_instance()
972 964
973 965 source_commit = source_scm.get_commit(source_ref.split(':')[-1])
974 966 target_commit = target_scm.get_commit(target_ref.split(':')[-1])
975 967
976 968 ancestor = source_scm.get_common_ancestor(
977 969 source_commit.raw_id, target_commit.raw_id, target_scm)
978 970
979 971 # recalculate target ref based on ancestor
980 972 target_ref_type, target_ref_name, __ = _form['target_ref'].split(':')
981 973 target_ref = ':'.join((target_ref_type, target_ref_name, ancestor))
982 974
983 975 get_default_reviewers_data, validate_default_reviewers = \
984 976 PullRequestModel().get_reviewer_functions()
985 977
986 978 # recalculate reviewers logic, to make sure we can validate this
987 979 reviewer_rules = get_default_reviewers_data(
988 980 self._rhodecode_db_user, source_db_repo,
989 981 source_commit, target_db_repo, target_commit)
990 982
991 983 given_reviewers = _form['review_members']
992 984 reviewers = validate_default_reviewers(
993 985 given_reviewers, reviewer_rules)
994 986
995 987 pullrequest_title = _form['pullrequest_title']
996 988 title_source_ref = source_ref.split(':', 2)[1]
997 989 if not pullrequest_title:
998 990 pullrequest_title = PullRequestModel().generate_pullrequest_title(
999 991 source=source_repo,
1000 992 source_ref=title_source_ref,
1001 993 target=target_repo
1002 994 )
1003 995
1004 996 description = _form['pullrequest_desc']
1005 997 description_renderer = _form['description_renderer']
1006 998
1007 999 try:
1008 1000 pull_request = PullRequestModel().create(
1009 1001 created_by=self._rhodecode_user.user_id,
1010 1002 source_repo=source_repo,
1011 1003 source_ref=source_ref,
1012 1004 target_repo=target_repo,
1013 1005 target_ref=target_ref,
1014 1006 revisions=commit_ids,
1015 1007 reviewers=reviewers,
1016 1008 title=pullrequest_title,
1017 1009 description=description,
1018 1010 description_renderer=description_renderer,
1019 1011 reviewer_data=reviewer_rules,
1020 1012 auth_user=self._rhodecode_user
1021 1013 )
1022 1014 Session().commit()
1023 1015
1024 1016 h.flash(_('Successfully opened new pull request'),
1025 1017 category='success')
1026 1018 except Exception:
1027 1019 msg = _('Error occurred during creation of this pull request.')
1028 1020 log.exception(msg)
1029 1021 h.flash(msg, category='error')
1030 1022
1031 1023 # copy the args back to redirect
1032 1024 org_query = self.request.GET.mixed()
1033 1025 raise HTTPFound(
1034 1026 h.route_path('pullrequest_new', repo_name=self.db_repo_name,
1035 1027 _query=org_query))
1036 1028
1037 1029 raise HTTPFound(
1038 1030 h.route_path('pullrequest_show', repo_name=target_repo,
1039 1031 pull_request_id=pull_request.pull_request_id))
1040 1032
1041 1033 @LoginRequired()
1042 1034 @NotAnonymous()
1043 1035 @HasRepoPermissionAnyDecorator(
1044 1036 'repository.read', 'repository.write', 'repository.admin')
1045 1037 @CSRFRequired()
1046 1038 @view_config(
1047 1039 route_name='pullrequest_update', request_method='POST',
1048 1040 renderer='json_ext')
1049 1041 def pull_request_update(self):
1050 1042 pull_request = PullRequest.get_or_404(
1051 1043 self.request.matchdict['pull_request_id'])
1052 1044 _ = self.request.translate
1053 1045
1054 1046 self.load_default_context()
1055 1047 redirect_url = None
1056 1048
1057 1049 if pull_request.is_closed():
1058 1050 log.debug('update: forbidden because pull request is closed')
1059 1051 msg = _(u'Cannot update closed pull requests.')
1060 1052 h.flash(msg, category='error')
1061 1053 return {'response': True,
1062 1054 'redirect_url': redirect_url}
1063 1055
1064 if pull_request.pull_request_state != PullRequest.STATE_CREATED:
1065 log.debug('update: forbidden because pull request is in state %s',
1066 pull_request.pull_request_state)
1067 msg = _(u'Cannot update pull requests in state other than `{}`. '
1068 u'Current state is: `{}`').format(PullRequest.STATE_CREATED,
1069 pull_request.pull_request_state)
1070 h.flash(msg, category='error')
1071 return {'response': True,
1072 'redirect_url': redirect_url}
1056 is_state_changing = pull_request.is_state_changing()
1073 1057
1074 1058 # only owner or admin can update it
1075 1059 allowed_to_update = PullRequestModel().check_user_update(
1076 1060 pull_request, self._rhodecode_user)
1077 1061 if allowed_to_update:
1078 1062 controls = peppercorn.parse(self.request.POST.items())
1079 1063 force_refresh = str2bool(self.request.POST.get('force_refresh'))
1080 1064
1081 1065 if 'review_members' in controls:
1082 1066 self._update_reviewers(
1083 1067 pull_request, controls['review_members'],
1084 1068 pull_request.reviewer_data)
1085 1069 elif str2bool(self.request.POST.get('update_commits', 'false')):
1070 if is_state_changing:
1071 log.debug('commits update: forbidden because pull request is in state %s',
1072 pull_request.pull_request_state)
1073 msg = _(u'Cannot update pull requests commits in state other than `{}`. '
1074 u'Current state is: `{}`').format(
1075 PullRequest.STATE_CREATED, pull_request.pull_request_state)
1076 h.flash(msg, category='error')
1077 return {'response': True,
1078 'redirect_url': redirect_url}
1079
1086 1080 self._update_commits(pull_request)
1087 1081 if force_refresh:
1088 1082 redirect_url = h.route_path(
1089 1083 'pullrequest_show', repo_name=self.db_repo_name,
1090 1084 pull_request_id=pull_request.pull_request_id,
1091 1085 _query={"force_refresh": 1})
1092 1086 elif str2bool(self.request.POST.get('edit_pull_request', 'false')):
1093 1087 self._edit_pull_request(pull_request)
1094 1088 else:
1095 1089 raise HTTPBadRequest()
1096 1090
1097 1091 return {'response': True,
1098 1092 'redirect_url': redirect_url}
1099 1093 raise HTTPForbidden()
1100 1094
1101 1095 def _edit_pull_request(self, pull_request):
1102 1096 _ = self.request.translate
1103 1097
1104 1098 try:
1105 1099 PullRequestModel().edit(
1106 1100 pull_request,
1107 1101 self.request.POST.get('title'),
1108 1102 self.request.POST.get('description'),
1109 1103 self.request.POST.get('description_renderer'),
1110 1104 self._rhodecode_user)
1111 1105 except ValueError:
1112 1106 msg = _(u'Cannot update closed pull requests.')
1113 1107 h.flash(msg, category='error')
1114 1108 return
1115 1109 else:
1116 1110 Session().commit()
1117 1111
1118 1112 msg = _(u'Pull request title & description updated.')
1119 1113 h.flash(msg, category='success')
1120 1114 return
1121 1115
1122 1116 def _update_commits(self, pull_request):
1123 1117 _ = self.request.translate
1124 1118
1125 1119 with pull_request.set_state(PullRequest.STATE_UPDATING):
1126 1120 resp = PullRequestModel().update_commits(pull_request)
1127 1121
1128 1122 if resp.executed:
1129 1123
1130 1124 if resp.target_changed and resp.source_changed:
1131 1125 changed = 'target and source repositories'
1132 1126 elif resp.target_changed and not resp.source_changed:
1133 1127 changed = 'target repository'
1134 1128 elif not resp.target_changed and resp.source_changed:
1135 1129 changed = 'source repository'
1136 1130 else:
1137 1131 changed = 'nothing'
1138 1132
1139 1133 msg = _(u'Pull request updated to "{source_commit_id}" with '
1140 1134 u'{count_added} added, {count_removed} removed commits. '
1141 1135 u'Source of changes: {change_source}')
1142 1136 msg = msg.format(
1143 1137 source_commit_id=pull_request.source_ref_parts.commit_id,
1144 1138 count_added=len(resp.changes.added),
1145 1139 count_removed=len(resp.changes.removed),
1146 1140 change_source=changed)
1147 1141 h.flash(msg, category='success')
1148 1142
1149 1143 channel = '/repo${}$/pr/{}'.format(
1150 1144 pull_request.target_repo.repo_name, pull_request.pull_request_id)
1151 1145 message = msg + (
1152 1146 ' - <a onclick="window.location.reload()">'
1153 1147 '<strong>{}</strong></a>'.format(_('Reload page')))
1154 1148 channelstream.post_message(
1155 1149 channel, message, self._rhodecode_user.username,
1156 1150 registry=self.request.registry)
1157 1151 else:
1158 1152 msg = PullRequestModel.UPDATE_STATUS_MESSAGES[resp.reason]
1159 1153 warning_reasons = [
1160 1154 UpdateFailureReason.NO_CHANGE,
1161 1155 UpdateFailureReason.WRONG_REF_TYPE,
1162 1156 ]
1163 1157 category = 'warning' if resp.reason in warning_reasons else 'error'
1164 1158 h.flash(msg, category=category)
1165 1159
1166 1160 @LoginRequired()
1167 1161 @NotAnonymous()
1168 1162 @HasRepoPermissionAnyDecorator(
1169 1163 'repository.read', 'repository.write', 'repository.admin')
1170 1164 @CSRFRequired()
1171 1165 @view_config(
1172 1166 route_name='pullrequest_merge', request_method='POST',
1173 1167 renderer='json_ext')
1174 1168 def pull_request_merge(self):
1175 1169 """
1176 1170 Merge will perform a server-side merge of the specified
1177 1171 pull request, if the pull request is approved and mergeable.
1178 1172 After successful merging, the pull request is automatically
1179 1173 closed, with a relevant comment.
1180 1174 """
1181 1175 pull_request = PullRequest.get_or_404(
1182 1176 self.request.matchdict['pull_request_id'])
1183 1177 _ = self.request.translate
1184 1178
1185 if pull_request.pull_request_state != PullRequest.STATE_CREATED:
1179 if pull_request.is_state_changing():
1186 1180 log.debug('show: forbidden because pull request is in state %s',
1187 1181 pull_request.pull_request_state)
1188 1182 msg = _(u'Cannot merge pull requests in state other than `{}`. '
1189 1183 u'Current state is: `{}`').format(PullRequest.STATE_CREATED,
1190 1184 pull_request.pull_request_state)
1191 1185 h.flash(msg, category='error')
1192 1186 raise HTTPFound(
1193 1187 h.route_path('pullrequest_show',
1194 1188 repo_name=pull_request.target_repo.repo_name,
1195 1189 pull_request_id=pull_request.pull_request_id))
1196 1190
1197 1191 self.load_default_context()
1198 1192
1199 1193 with pull_request.set_state(PullRequest.STATE_UPDATING):
1200 1194 check = MergeCheck.validate(
1201 1195 pull_request, auth_user=self._rhodecode_user,
1202 1196 translator=self.request.translate)
1203 1197 merge_possible = not check.failed
1204 1198
1205 1199 for err_type, error_msg in check.errors:
1206 1200 h.flash(error_msg, category=err_type)
1207 1201
1208 1202 if merge_possible:
1209 1203 log.debug("Pre-conditions checked, trying to merge.")
1210 1204 extras = vcs_operation_context(
1211 1205 self.request.environ, repo_name=pull_request.target_repo.repo_name,
1212 1206 username=self._rhodecode_db_user.username, action='push',
1213 1207 scm=pull_request.target_repo.repo_type)
1214 1208 with pull_request.set_state(PullRequest.STATE_UPDATING):
1215 1209 self._merge_pull_request(
1216 1210 pull_request, self._rhodecode_db_user, extras)
1217 1211 else:
1218 1212 log.debug("Pre-conditions failed, NOT merging.")
1219 1213
1220 1214 raise HTTPFound(
1221 1215 h.route_path('pullrequest_show',
1222 1216 repo_name=pull_request.target_repo.repo_name,
1223 1217 pull_request_id=pull_request.pull_request_id))
1224 1218
1225 1219 def _merge_pull_request(self, pull_request, user, extras):
1226 1220 _ = self.request.translate
1227 1221 merge_resp = PullRequestModel().merge_repo(pull_request, user, extras=extras)
1228 1222
1229 1223 if merge_resp.executed:
1230 1224 log.debug("The merge was successful, closing the pull request.")
1231 1225 PullRequestModel().close_pull_request(
1232 1226 pull_request.pull_request_id, user)
1233 1227 Session().commit()
1234 1228 msg = _('Pull request was successfully merged and closed.')
1235 1229 h.flash(msg, category='success')
1236 1230 else:
1237 1231 log.debug(
1238 1232 "The merge was not successful. Merge response: %s", merge_resp)
1239 1233 msg = merge_resp.merge_status_message
1240 1234 h.flash(msg, category='error')
1241 1235
1242 1236 def _update_reviewers(self, pull_request, review_members, reviewer_rules):
1243 1237 _ = self.request.translate
1244 1238
1245 1239 get_default_reviewers_data, validate_default_reviewers = \
1246 1240 PullRequestModel().get_reviewer_functions()
1247 1241
1248 1242 try:
1249 1243 reviewers = validate_default_reviewers(review_members, reviewer_rules)
1250 1244 except ValueError as e:
1251 1245 log.error('Reviewers Validation: {}'.format(e))
1252 1246 h.flash(e, category='error')
1253 1247 return
1254 1248
1255 1249 old_calculated_status = pull_request.calculated_review_status()
1256 1250 PullRequestModel().update_reviewers(
1257 1251 pull_request, reviewers, self._rhodecode_user)
1258 1252 h.flash(_('Pull request reviewers updated.'), category='success')
1259 1253 Session().commit()
1260 1254
1261 1255 # trigger status changed if change in reviewers changes the status
1262 1256 calculated_status = pull_request.calculated_review_status()
1263 1257 if old_calculated_status != calculated_status:
1264 1258 PullRequestModel().trigger_pull_request_hook(
1265 1259 pull_request, self._rhodecode_user, 'review_status_change',
1266 1260 data={'status': calculated_status})
1267 1261
1268 1262 @LoginRequired()
1269 1263 @NotAnonymous()
1270 1264 @HasRepoPermissionAnyDecorator(
1271 1265 'repository.read', 'repository.write', 'repository.admin')
1272 1266 @CSRFRequired()
1273 1267 @view_config(
1274 1268 route_name='pullrequest_delete', request_method='POST',
1275 1269 renderer='json_ext')
1276 1270 def pull_request_delete(self):
1277 1271 _ = self.request.translate
1278 1272
1279 1273 pull_request = PullRequest.get_or_404(
1280 1274 self.request.matchdict['pull_request_id'])
1281 1275 self.load_default_context()
1282 1276
1283 1277 pr_closed = pull_request.is_closed()
1284 1278 allowed_to_delete = PullRequestModel().check_user_delete(
1285 1279 pull_request, self._rhodecode_user) and not pr_closed
1286 1280
1287 1281 # only owner can delete it !
1288 1282 if allowed_to_delete:
1289 1283 PullRequestModel().delete(pull_request, self._rhodecode_user)
1290 1284 Session().commit()
1291 1285 h.flash(_('Successfully deleted pull request'),
1292 1286 category='success')
1293 1287 raise HTTPFound(h.route_path('pullrequest_show_all',
1294 1288 repo_name=self.db_repo_name))
1295 1289
1296 1290 log.warning('user %s tried to delete pull request without access',
1297 1291 self._rhodecode_user)
1298 1292 raise HTTPNotFound()
1299 1293
1300 1294 @LoginRequired()
1301 1295 @NotAnonymous()
1302 1296 @HasRepoPermissionAnyDecorator(
1303 1297 'repository.read', 'repository.write', 'repository.admin')
1304 1298 @CSRFRequired()
1305 1299 @view_config(
1306 1300 route_name='pullrequest_comment_create', request_method='POST',
1307 1301 renderer='json_ext')
1308 1302 def pull_request_comment_create(self):
1309 1303 _ = self.request.translate
1310 1304
1311 1305 pull_request = PullRequest.get_or_404(
1312 1306 self.request.matchdict['pull_request_id'])
1313 1307 pull_request_id = pull_request.pull_request_id
1314 1308
1315 1309 if pull_request.is_closed():
1316 1310 log.debug('comment: forbidden because pull request is closed')
1317 1311 raise HTTPForbidden()
1318 1312
1319 1313 allowed_to_comment = PullRequestModel().check_user_comment(
1320 1314 pull_request, self._rhodecode_user)
1321 1315 if not allowed_to_comment:
1322 1316 log.debug(
1323 1317 'comment: forbidden because pull request is from forbidden repo')
1324 1318 raise HTTPForbidden()
1325 1319
1326 1320 c = self.load_default_context()
1327 1321
1328 1322 status = self.request.POST.get('changeset_status', None)
1329 1323 text = self.request.POST.get('text')
1330 1324 comment_type = self.request.POST.get('comment_type')
1331 1325 resolves_comment_id = self.request.POST.get('resolves_comment_id', None)
1332 1326 close_pull_request = self.request.POST.get('close_pull_request')
1333 1327
1334 1328 # the logic here should work like following, if we submit close
1335 1329 # pr comment, use `close_pull_request_with_comment` function
1336 1330 # else handle regular comment logic
1337 1331
1338 1332 if close_pull_request:
1339 1333 # only owner or admin or person with write permissions
1340 1334 allowed_to_close = PullRequestModel().check_user_update(
1341 1335 pull_request, self._rhodecode_user)
1342 1336 if not allowed_to_close:
1343 1337 log.debug('comment: forbidden because not allowed to close '
1344 1338 'pull request %s', pull_request_id)
1345 1339 raise HTTPForbidden()
1346 1340
1347 1341 # This also triggers `review_status_change`
1348 1342 comment, status = PullRequestModel().close_pull_request_with_comment(
1349 1343 pull_request, self._rhodecode_user, self.db_repo, message=text,
1350 1344 auth_user=self._rhodecode_user)
1351 1345 Session().flush()
1352 1346
1353 1347 PullRequestModel().trigger_pull_request_hook(
1354 1348 pull_request, self._rhodecode_user, 'comment',
1355 1349 data={'comment': comment})
1356 1350
1357 1351 else:
1358 1352 # regular comment case, could be inline, or one with status.
1359 1353 # for that one we check also permissions
1360 1354
1361 1355 allowed_to_change_status = PullRequestModel().check_user_change_status(
1362 1356 pull_request, self._rhodecode_user)
1363 1357
1364 1358 if status and allowed_to_change_status:
1365 1359 message = (_('Status change %(transition_icon)s %(status)s')
1366 1360 % {'transition_icon': '>',
1367 1361 'status': ChangesetStatus.get_status_lbl(status)})
1368 1362 text = text or message
1369 1363
1370 1364 comment = CommentsModel().create(
1371 1365 text=text,
1372 1366 repo=self.db_repo.repo_id,
1373 1367 user=self._rhodecode_user.user_id,
1374 1368 pull_request=pull_request,
1375 1369 f_path=self.request.POST.get('f_path'),
1376 1370 line_no=self.request.POST.get('line'),
1377 1371 status_change=(ChangesetStatus.get_status_lbl(status)
1378 1372 if status and allowed_to_change_status else None),
1379 1373 status_change_type=(status
1380 1374 if status and allowed_to_change_status else None),
1381 1375 comment_type=comment_type,
1382 1376 resolves_comment_id=resolves_comment_id,
1383 1377 auth_user=self._rhodecode_user
1384 1378 )
1385 1379
1386 1380 if allowed_to_change_status:
1387 1381 # calculate old status before we change it
1388 1382 old_calculated_status = pull_request.calculated_review_status()
1389 1383
1390 1384 # get status if set !
1391 1385 if status:
1392 1386 ChangesetStatusModel().set_status(
1393 1387 self.db_repo.repo_id,
1394 1388 status,
1395 1389 self._rhodecode_user.user_id,
1396 1390 comment,
1397 1391 pull_request=pull_request
1398 1392 )
1399 1393
1400 1394 Session().flush()
1401 1395 # this is somehow required to get access to some relationship
1402 1396 # loaded on comment
1403 1397 Session().refresh(comment)
1404 1398
1405 1399 PullRequestModel().trigger_pull_request_hook(
1406 1400 pull_request, self._rhodecode_user, 'comment',
1407 1401 data={'comment': comment})
1408 1402
1409 1403 # we now calculate the status of pull request, and based on that
1410 1404 # calculation we set the commits status
1411 1405 calculated_status = pull_request.calculated_review_status()
1412 1406 if old_calculated_status != calculated_status:
1413 1407 PullRequestModel().trigger_pull_request_hook(
1414 1408 pull_request, self._rhodecode_user, 'review_status_change',
1415 1409 data={'status': calculated_status})
1416 1410
1417 1411 Session().commit()
1418 1412
1419 1413 data = {
1420 1414 'target_id': h.safeid(h.safe_unicode(
1421 1415 self.request.POST.get('f_path'))),
1422 1416 }
1423 1417 if comment:
1424 1418 c.co = comment
1425 1419 rendered_comment = render(
1426 1420 'rhodecode:templates/changeset/changeset_comment_block.mako',
1427 1421 self._get_template_context(c), self.request)
1428 1422
1429 1423 data.update(comment.get_dict())
1430 1424 data.update({'rendered_text': rendered_comment})
1431 1425
1432 1426 return data
1433 1427
1434 1428 @LoginRequired()
1435 1429 @NotAnonymous()
1436 1430 @HasRepoPermissionAnyDecorator(
1437 1431 'repository.read', 'repository.write', 'repository.admin')
1438 1432 @CSRFRequired()
1439 1433 @view_config(
1440 1434 route_name='pullrequest_comment_delete', request_method='POST',
1441 1435 renderer='json_ext')
1442 1436 def pull_request_comment_delete(self):
1443 1437 pull_request = PullRequest.get_or_404(
1444 1438 self.request.matchdict['pull_request_id'])
1445 1439
1446 1440 comment = ChangesetComment.get_or_404(
1447 1441 self.request.matchdict['comment_id'])
1448 1442 comment_id = comment.comment_id
1449 1443
1450 1444 if pull_request.is_closed():
1451 1445 log.debug('comment: forbidden because pull request is closed')
1452 1446 raise HTTPForbidden()
1453 1447
1454 1448 if not comment:
1455 1449 log.debug('Comment with id:%s not found, skipping', comment_id)
1456 1450 # comment already deleted in another call probably
1457 1451 return True
1458 1452
1459 1453 if comment.pull_request.is_closed():
1460 1454 # don't allow deleting comments on closed pull request
1461 1455 raise HTTPForbidden()
1462 1456
1463 1457 is_repo_admin = h.HasRepoPermissionAny('repository.admin')(self.db_repo_name)
1464 1458 super_admin = h.HasPermissionAny('hg.admin')()
1465 1459 comment_owner = comment.author.user_id == self._rhodecode_user.user_id
1466 1460 is_repo_comment = comment.repo.repo_name == self.db_repo_name
1467 1461 comment_repo_admin = is_repo_admin and is_repo_comment
1468 1462
1469 1463 if super_admin or comment_owner or comment_repo_admin:
1470 1464 old_calculated_status = comment.pull_request.calculated_review_status()
1471 1465 CommentsModel().delete(comment=comment, auth_user=self._rhodecode_user)
1472 1466 Session().commit()
1473 1467 calculated_status = comment.pull_request.calculated_review_status()
1474 1468 if old_calculated_status != calculated_status:
1475 1469 PullRequestModel().trigger_pull_request_hook(
1476 1470 comment.pull_request, self._rhodecode_user, 'review_status_change',
1477 1471 data={'status': calculated_status})
1478 1472 return True
1479 1473 else:
1480 1474 log.warning('No permissions for user %s to delete comment_id: %s',
1481 1475 self._rhodecode_db_user, comment_id)
1482 1476 raise HTTPNotFound()
@@ -1,5454 +1,5463 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2019 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
45 45 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
46 46 from sqlalchemy.orm import (
47 47 relationship, 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 import compat
54 54 from pyramid.threadlocal import get_current_request
55 55 from webhelpers2.text import remove_formatting
56 56
57 57 from rhodecode.translation import _
58 58 from rhodecode.lib.vcs import get_vcs_instance
59 59 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
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, OrderedDefaultDict)
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 return prefix + obj.username
107 107
108 108
109 109 def display_user_group_sort(obj):
110 110 """
111 111 Sort function used to sort permissions in .permissions() function of
112 112 Repository, RepoGroup, UserGroup. Also it put the default user in front
113 113 of all other resources
114 114 """
115 115
116 116 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
117 117 return prefix + obj.users_group_name
118 118
119 119
120 120 def _hash_key(k):
121 121 return sha1_safe(k)
122 122
123 123
124 124 def in_filter_generator(qry, items, limit=500):
125 125 """
126 126 Splits IN() into multiple with OR
127 127 e.g.::
128 128 cnt = Repository.query().filter(
129 129 or_(
130 130 *in_filter_generator(Repository.repo_id, range(100000))
131 131 )).count()
132 132 """
133 133 if not items:
134 134 # empty list will cause empty query which might cause security issues
135 135 # this can lead to hidden unpleasant results
136 136 items = [-1]
137 137
138 138 parts = []
139 139 for chunk in xrange(0, len(items), limit):
140 140 parts.append(
141 141 qry.in_(items[chunk: chunk + limit])
142 142 )
143 143
144 144 return parts
145 145
146 146
147 147 base_table_args = {
148 148 'extend_existing': True,
149 149 'mysql_engine': 'InnoDB',
150 150 'mysql_charset': 'utf8',
151 151 'sqlite_autoincrement': True
152 152 }
153 153
154 154
155 155 class EncryptedTextValue(TypeDecorator):
156 156 """
157 157 Special column for encrypted long text data, use like::
158 158
159 159 value = Column("encrypted_value", EncryptedValue(), nullable=False)
160 160
161 161 This column is intelligent so if value is in unencrypted form it return
162 162 unencrypted form, but on save it always encrypts
163 163 """
164 164 impl = Text
165 165
166 166 def process_bind_param(self, value, dialect):
167 167 """
168 168 Setter for storing value
169 169 """
170 170 import rhodecode
171 171 if not value:
172 172 return value
173 173
174 174 # protect against double encrypting if values is already encrypted
175 175 if value.startswith('enc$aes$') \
176 176 or value.startswith('enc$aes_hmac$') \
177 177 or value.startswith('enc2$'):
178 178 raise ValueError('value needs to be in unencrypted format, '
179 179 'ie. not starting with enc$ or enc2$')
180 180
181 181 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
182 182 if algo == 'aes':
183 183 return 'enc$aes_hmac$%s' % AESCipher(ENCRYPTION_KEY, hmac=True).encrypt(value)
184 184 elif algo == 'fernet':
185 185 return Encryptor(ENCRYPTION_KEY).encrypt(value)
186 186 else:
187 187 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
188 188
189 189 def process_result_value(self, value, dialect):
190 190 """
191 191 Getter for retrieving value
192 192 """
193 193
194 194 import rhodecode
195 195 if not value:
196 196 return value
197 197
198 198 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
199 199 enc_strict_mode = str2bool(rhodecode.CONFIG.get('rhodecode.encrypted_values.strict') or True)
200 200 if algo == 'aes':
201 201 decrypted_data = validate_and_get_enc_data(value, ENCRYPTION_KEY, enc_strict_mode)
202 202 elif algo == 'fernet':
203 203 return Encryptor(ENCRYPTION_KEY).decrypt(value)
204 204 else:
205 205 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
206 206 return decrypted_data
207 207
208 208
209 209 class BaseModel(object):
210 210 """
211 211 Base Model for all classes
212 212 """
213 213
214 214 @classmethod
215 215 def _get_keys(cls):
216 216 """return column names for this model """
217 217 return class_mapper(cls).c.keys()
218 218
219 219 def get_dict(self):
220 220 """
221 221 return dict with keys and values corresponding
222 222 to this model data """
223 223
224 224 d = {}
225 225 for k in self._get_keys():
226 226 d[k] = getattr(self, k)
227 227
228 228 # also use __json__() if present to get additional fields
229 229 _json_attr = getattr(self, '__json__', None)
230 230 if _json_attr:
231 231 # update with attributes from __json__
232 232 if callable(_json_attr):
233 233 _json_attr = _json_attr()
234 234 for k, val in _json_attr.iteritems():
235 235 d[k] = val
236 236 return d
237 237
238 238 def get_appstruct(self):
239 239 """return list with keys and values tuples corresponding
240 240 to this model data """
241 241
242 242 lst = []
243 243 for k in self._get_keys():
244 244 lst.append((k, getattr(self, k),))
245 245 return lst
246 246
247 247 def populate_obj(self, populate_dict):
248 248 """populate model with data from given populate_dict"""
249 249
250 250 for k in self._get_keys():
251 251 if k in populate_dict:
252 252 setattr(self, k, populate_dict[k])
253 253
254 254 @classmethod
255 255 def query(cls):
256 256 return Session().query(cls)
257 257
258 258 @classmethod
259 259 def get(cls, id_):
260 260 if id_:
261 261 return cls.query().get(id_)
262 262
263 263 @classmethod
264 264 def get_or_404(cls, id_):
265 265 from pyramid.httpexceptions import HTTPNotFound
266 266
267 267 try:
268 268 id_ = int(id_)
269 269 except (TypeError, ValueError):
270 270 raise HTTPNotFound()
271 271
272 272 res = cls.query().get(id_)
273 273 if not res:
274 274 raise HTTPNotFound()
275 275 return res
276 276
277 277 @classmethod
278 278 def getAll(cls):
279 279 # deprecated and left for backward compatibility
280 280 return cls.get_all()
281 281
282 282 @classmethod
283 283 def get_all(cls):
284 284 return cls.query().all()
285 285
286 286 @classmethod
287 287 def delete(cls, id_):
288 288 obj = cls.query().get(id_)
289 289 Session().delete(obj)
290 290
291 291 @classmethod
292 292 def identity_cache(cls, session, attr_name, value):
293 293 exist_in_session = []
294 294 for (item_cls, pkey), instance in session.identity_map.items():
295 295 if cls == item_cls and getattr(instance, attr_name) == value:
296 296 exist_in_session.append(instance)
297 297 if exist_in_session:
298 298 if len(exist_in_session) == 1:
299 299 return exist_in_session[0]
300 300 log.exception(
301 301 'multiple objects with attr %s and '
302 302 'value %s found with same name: %r',
303 303 attr_name, value, exist_in_session)
304 304
305 305 def __repr__(self):
306 306 if hasattr(self, '__unicode__'):
307 307 # python repr needs to return str
308 308 try:
309 309 return safe_str(self.__unicode__())
310 310 except UnicodeDecodeError:
311 311 pass
312 312 return '<DB:%s>' % (self.__class__.__name__)
313 313
314 314
315 315 class RhodeCodeSetting(Base, BaseModel):
316 316 __tablename__ = 'rhodecode_settings'
317 317 __table_args__ = (
318 318 UniqueConstraint('app_settings_name'),
319 319 base_table_args
320 320 )
321 321
322 322 SETTINGS_TYPES = {
323 323 'str': safe_str,
324 324 'int': safe_int,
325 325 'unicode': safe_unicode,
326 326 'bool': str2bool,
327 327 'list': functools.partial(aslist, sep=',')
328 328 }
329 329 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
330 330 GLOBAL_CONF_KEY = 'app_settings'
331 331
332 332 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
333 333 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
334 334 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
335 335 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
336 336
337 337 def __init__(self, key='', val='', type='unicode'):
338 338 self.app_settings_name = key
339 339 self.app_settings_type = type
340 340 self.app_settings_value = val
341 341
342 342 @validates('_app_settings_value')
343 343 def validate_settings_value(self, key, val):
344 344 assert type(val) == unicode
345 345 return val
346 346
347 347 @hybrid_property
348 348 def app_settings_value(self):
349 349 v = self._app_settings_value
350 350 _type = self.app_settings_type
351 351 if _type:
352 352 _type = self.app_settings_type.split('.')[0]
353 353 # decode the encrypted value
354 354 if 'encrypted' in self.app_settings_type:
355 355 cipher = EncryptedTextValue()
356 356 v = safe_unicode(cipher.process_result_value(v, None))
357 357
358 358 converter = self.SETTINGS_TYPES.get(_type) or \
359 359 self.SETTINGS_TYPES['unicode']
360 360 return converter(v)
361 361
362 362 @app_settings_value.setter
363 363 def app_settings_value(self, val):
364 364 """
365 365 Setter that will always make sure we use unicode in app_settings_value
366 366
367 367 :param val:
368 368 """
369 369 val = safe_unicode(val)
370 370 # encode the encrypted value
371 371 if 'encrypted' in self.app_settings_type:
372 372 cipher = EncryptedTextValue()
373 373 val = safe_unicode(cipher.process_bind_param(val, None))
374 374 self._app_settings_value = val
375 375
376 376 @hybrid_property
377 377 def app_settings_type(self):
378 378 return self._app_settings_type
379 379
380 380 @app_settings_type.setter
381 381 def app_settings_type(self, val):
382 382 if val.split('.')[0] not in self.SETTINGS_TYPES:
383 383 raise Exception('type must be one of %s got %s'
384 384 % (self.SETTINGS_TYPES.keys(), val))
385 385 self._app_settings_type = val
386 386
387 387 @classmethod
388 388 def get_by_prefix(cls, prefix):
389 389 return RhodeCodeSetting.query()\
390 390 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
391 391 .all()
392 392
393 393 def __unicode__(self):
394 394 return u"<%s('%s:%s[%s]')>" % (
395 395 self.__class__.__name__,
396 396 self.app_settings_name, self.app_settings_value,
397 397 self.app_settings_type
398 398 )
399 399
400 400
401 401 class RhodeCodeUi(Base, BaseModel):
402 402 __tablename__ = 'rhodecode_ui'
403 403 __table_args__ = (
404 404 UniqueConstraint('ui_key'),
405 405 base_table_args
406 406 )
407 407
408 408 HOOK_REPO_SIZE = 'changegroup.repo_size'
409 409 # HG
410 410 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
411 411 HOOK_PULL = 'outgoing.pull_logger'
412 412 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
413 413 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
414 414 HOOK_PUSH = 'changegroup.push_logger'
415 415 HOOK_PUSH_KEY = 'pushkey.key_push'
416 416
417 417 HOOKS_BUILTIN = [
418 418 HOOK_PRE_PULL,
419 419 HOOK_PULL,
420 420 HOOK_PRE_PUSH,
421 421 HOOK_PRETX_PUSH,
422 422 HOOK_PUSH,
423 423 HOOK_PUSH_KEY,
424 424 ]
425 425
426 426 # TODO: johbo: Unify way how hooks are configured for git and hg,
427 427 # git part is currently hardcoded.
428 428
429 429 # SVN PATTERNS
430 430 SVN_BRANCH_ID = 'vcs_svn_branch'
431 431 SVN_TAG_ID = 'vcs_svn_tag'
432 432
433 433 ui_id = Column(
434 434 "ui_id", Integer(), nullable=False, unique=True, default=None,
435 435 primary_key=True)
436 436 ui_section = Column(
437 437 "ui_section", String(255), nullable=True, unique=None, default=None)
438 438 ui_key = Column(
439 439 "ui_key", String(255), nullable=True, unique=None, default=None)
440 440 ui_value = Column(
441 441 "ui_value", String(255), nullable=True, unique=None, default=None)
442 442 ui_active = Column(
443 443 "ui_active", Boolean(), nullable=True, unique=None, default=True)
444 444
445 445 def __repr__(self):
446 446 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
447 447 self.ui_key, self.ui_value)
448 448
449 449
450 450 class RepoRhodeCodeSetting(Base, BaseModel):
451 451 __tablename__ = 'repo_rhodecode_settings'
452 452 __table_args__ = (
453 453 UniqueConstraint(
454 454 'app_settings_name', 'repository_id',
455 455 name='uq_repo_rhodecode_setting_name_repo_id'),
456 456 base_table_args
457 457 )
458 458
459 459 repository_id = Column(
460 460 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
461 461 nullable=False)
462 462 app_settings_id = Column(
463 463 "app_settings_id", Integer(), nullable=False, unique=True,
464 464 default=None, primary_key=True)
465 465 app_settings_name = Column(
466 466 "app_settings_name", String(255), nullable=True, unique=None,
467 467 default=None)
468 468 _app_settings_value = Column(
469 469 "app_settings_value", String(4096), nullable=True, unique=None,
470 470 default=None)
471 471 _app_settings_type = Column(
472 472 "app_settings_type", String(255), nullable=True, unique=None,
473 473 default=None)
474 474
475 475 repository = relationship('Repository')
476 476
477 477 def __init__(self, repository_id, key='', val='', type='unicode'):
478 478 self.repository_id = repository_id
479 479 self.app_settings_name = key
480 480 self.app_settings_type = type
481 481 self.app_settings_value = val
482 482
483 483 @validates('_app_settings_value')
484 484 def validate_settings_value(self, key, val):
485 485 assert type(val) == unicode
486 486 return val
487 487
488 488 @hybrid_property
489 489 def app_settings_value(self):
490 490 v = self._app_settings_value
491 491 type_ = self.app_settings_type
492 492 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
493 493 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
494 494 return converter(v)
495 495
496 496 @app_settings_value.setter
497 497 def app_settings_value(self, val):
498 498 """
499 499 Setter that will always make sure we use unicode in app_settings_value
500 500
501 501 :param val:
502 502 """
503 503 self._app_settings_value = safe_unicode(val)
504 504
505 505 @hybrid_property
506 506 def app_settings_type(self):
507 507 return self._app_settings_type
508 508
509 509 @app_settings_type.setter
510 510 def app_settings_type(self, val):
511 511 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
512 512 if val not in SETTINGS_TYPES:
513 513 raise Exception('type must be one of %s got %s'
514 514 % (SETTINGS_TYPES.keys(), val))
515 515 self._app_settings_type = val
516 516
517 517 def __unicode__(self):
518 518 return u"<%s('%s:%s:%s[%s]')>" % (
519 519 self.__class__.__name__, self.repository.repo_name,
520 520 self.app_settings_name, self.app_settings_value,
521 521 self.app_settings_type
522 522 )
523 523
524 524
525 525 class RepoRhodeCodeUi(Base, BaseModel):
526 526 __tablename__ = 'repo_rhodecode_ui'
527 527 __table_args__ = (
528 528 UniqueConstraint(
529 529 'repository_id', 'ui_section', 'ui_key',
530 530 name='uq_repo_rhodecode_ui_repository_id_section_key'),
531 531 base_table_args
532 532 )
533 533
534 534 repository_id = Column(
535 535 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
536 536 nullable=False)
537 537 ui_id = Column(
538 538 "ui_id", Integer(), nullable=False, unique=True, default=None,
539 539 primary_key=True)
540 540 ui_section = Column(
541 541 "ui_section", String(255), nullable=True, unique=None, default=None)
542 542 ui_key = Column(
543 543 "ui_key", String(255), nullable=True, unique=None, default=None)
544 544 ui_value = Column(
545 545 "ui_value", String(255), nullable=True, unique=None, default=None)
546 546 ui_active = Column(
547 547 "ui_active", Boolean(), nullable=True, unique=None, default=True)
548 548
549 549 repository = relationship('Repository')
550 550
551 551 def __repr__(self):
552 552 return '<%s[%s:%s]%s=>%s]>' % (
553 553 self.__class__.__name__, self.repository.repo_name,
554 554 self.ui_section, self.ui_key, self.ui_value)
555 555
556 556
557 557 class User(Base, BaseModel):
558 558 __tablename__ = 'users'
559 559 __table_args__ = (
560 560 UniqueConstraint('username'), UniqueConstraint('email'),
561 561 Index('u_username_idx', 'username'),
562 562 Index('u_email_idx', 'email'),
563 563 base_table_args
564 564 )
565 565
566 566 DEFAULT_USER = 'default'
567 567 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
568 568 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
569 569
570 570 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
571 571 username = Column("username", String(255), nullable=True, unique=None, default=None)
572 572 password = Column("password", String(255), nullable=True, unique=None, default=None)
573 573 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
574 574 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
575 575 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
576 576 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
577 577 _email = Column("email", String(255), nullable=True, unique=None, default=None)
578 578 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
579 579 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
580 580 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
581 581
582 582 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
583 583 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
584 584 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
585 585 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
586 586 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
587 587 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
588 588
589 589 user_log = relationship('UserLog')
590 590 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all, delete-orphan')
591 591
592 592 repositories = relationship('Repository')
593 593 repository_groups = relationship('RepoGroup')
594 594 user_groups = relationship('UserGroup')
595 595
596 596 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
597 597 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
598 598
599 599 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all, delete-orphan')
600 600 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
601 601 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
602 602
603 603 group_member = relationship('UserGroupMember', cascade='all')
604 604
605 605 notifications = relationship('UserNotification', cascade='all')
606 606 # notifications assigned to this user
607 607 user_created_notifications = relationship('Notification', cascade='all')
608 608 # comments created by this user
609 609 user_comments = relationship('ChangesetComment', cascade='all')
610 610 # user profile extra info
611 611 user_emails = relationship('UserEmailMap', cascade='all')
612 612 user_ip_map = relationship('UserIpMap', cascade='all')
613 613 user_auth_tokens = relationship('UserApiKeys', cascade='all')
614 614 user_ssh_keys = relationship('UserSshKeys', cascade='all')
615 615
616 616 # gists
617 617 user_gists = relationship('Gist', cascade='all')
618 618 # user pull requests
619 619 user_pull_requests = relationship('PullRequest', cascade='all')
620 620 # external identities
621 621 external_identities = relationship(
622 622 'ExternalIdentity',
623 623 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
624 624 cascade='all')
625 625 # review rules
626 626 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
627 627
628 628 # artifacts owned
629 629 artifacts = relationship('FileStore', primaryjoin='FileStore.user_id==User.user_id')
630 630
631 631 # no cascade, set NULL
632 632 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_user_id==User.user_id')
633 633
634 634 def __unicode__(self):
635 635 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
636 636 self.user_id, self.username)
637 637
638 638 @hybrid_property
639 639 def email(self):
640 640 return self._email
641 641
642 642 @email.setter
643 643 def email(self, val):
644 644 self._email = val.lower() if val else None
645 645
646 646 @hybrid_property
647 647 def first_name(self):
648 648 from rhodecode.lib import helpers as h
649 649 if self.name:
650 650 return h.escape(self.name)
651 651 return self.name
652 652
653 653 @hybrid_property
654 654 def last_name(self):
655 655 from rhodecode.lib import helpers as h
656 656 if self.lastname:
657 657 return h.escape(self.lastname)
658 658 return self.lastname
659 659
660 660 @hybrid_property
661 661 def api_key(self):
662 662 """
663 663 Fetch if exist an auth-token with role ALL connected to this user
664 664 """
665 665 user_auth_token = UserApiKeys.query()\
666 666 .filter(UserApiKeys.user_id == self.user_id)\
667 667 .filter(or_(UserApiKeys.expires == -1,
668 668 UserApiKeys.expires >= time.time()))\
669 669 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
670 670 if user_auth_token:
671 671 user_auth_token = user_auth_token.api_key
672 672
673 673 return user_auth_token
674 674
675 675 @api_key.setter
676 676 def api_key(self, val):
677 677 # don't allow to set API key this is deprecated for now
678 678 self._api_key = None
679 679
680 680 @property
681 681 def reviewer_pull_requests(self):
682 682 return PullRequestReviewers.query() \
683 683 .options(joinedload(PullRequestReviewers.pull_request)) \
684 684 .filter(PullRequestReviewers.user_id == self.user_id) \
685 685 .all()
686 686
687 687 @property
688 688 def firstname(self):
689 689 # alias for future
690 690 return self.name
691 691
692 692 @property
693 693 def emails(self):
694 694 other = UserEmailMap.query()\
695 695 .filter(UserEmailMap.user == self) \
696 696 .order_by(UserEmailMap.email_id.asc()) \
697 697 .all()
698 698 return [self.email] + [x.email for x in other]
699 699
700 700 def emails_cached(self):
701 701 emails = UserEmailMap.query()\
702 702 .filter(UserEmailMap.user == self) \
703 703 .order_by(UserEmailMap.email_id.asc())
704 704
705 705 emails = emails.options(
706 706 FromCache("sql_cache_short", "get_user_{}_emails".format(self.user_id))
707 707 )
708 708
709 709 return [self.email] + [x.email for x in emails]
710 710
711 711 @property
712 712 def auth_tokens(self):
713 713 auth_tokens = self.get_auth_tokens()
714 714 return [x.api_key for x in auth_tokens]
715 715
716 716 def get_auth_tokens(self):
717 717 return UserApiKeys.query()\
718 718 .filter(UserApiKeys.user == self)\
719 719 .order_by(UserApiKeys.user_api_key_id.asc())\
720 720 .all()
721 721
722 722 @LazyProperty
723 723 def feed_token(self):
724 724 return self.get_feed_token()
725 725
726 726 def get_feed_token(self, cache=True):
727 727 feed_tokens = UserApiKeys.query()\
728 728 .filter(UserApiKeys.user == self)\
729 729 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
730 730 if cache:
731 731 feed_tokens = feed_tokens.options(
732 732 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
733 733
734 734 feed_tokens = feed_tokens.all()
735 735 if feed_tokens:
736 736 return feed_tokens[0].api_key
737 737 return 'NO_FEED_TOKEN_AVAILABLE'
738 738
739 739 @LazyProperty
740 740 def artifact_token(self):
741 741 return self.get_artifact_token()
742 742
743 743 def get_artifact_token(self, cache=True):
744 744 artifacts_tokens = UserApiKeys.query()\
745 745 .filter(UserApiKeys.user == self)\
746 746 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
747 747 if cache:
748 748 artifacts_tokens = artifacts_tokens.options(
749 749 FromCache("sql_cache_short", "get_user_artifact_token_%s" % self.user_id))
750 750
751 751 artifacts_tokens = artifacts_tokens.all()
752 752 if artifacts_tokens:
753 753 return artifacts_tokens[0].api_key
754 754 return 'NO_ARTIFACT_TOKEN_AVAILABLE'
755 755
756 756 @classmethod
757 757 def get(cls, user_id, cache=False):
758 758 if not user_id:
759 759 return
760 760
761 761 user = cls.query()
762 762 if cache:
763 763 user = user.options(
764 764 FromCache("sql_cache_short", "get_users_%s" % user_id))
765 765 return user.get(user_id)
766 766
767 767 @classmethod
768 768 def extra_valid_auth_tokens(cls, user, role=None):
769 769 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
770 770 .filter(or_(UserApiKeys.expires == -1,
771 771 UserApiKeys.expires >= time.time()))
772 772 if role:
773 773 tokens = tokens.filter(or_(UserApiKeys.role == role,
774 774 UserApiKeys.role == UserApiKeys.ROLE_ALL))
775 775 return tokens.all()
776 776
777 777 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
778 778 from rhodecode.lib import auth
779 779
780 780 log.debug('Trying to authenticate user: %s via auth-token, '
781 781 'and roles: %s', self, roles)
782 782
783 783 if not auth_token:
784 784 return False
785 785
786 786 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
787 787 tokens_q = UserApiKeys.query()\
788 788 .filter(UserApiKeys.user_id == self.user_id)\
789 789 .filter(or_(UserApiKeys.expires == -1,
790 790 UserApiKeys.expires >= time.time()))
791 791
792 792 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
793 793
794 794 crypto_backend = auth.crypto_backend()
795 795 enc_token_map = {}
796 796 plain_token_map = {}
797 797 for token in tokens_q:
798 798 if token.api_key.startswith(crypto_backend.ENC_PREF):
799 799 enc_token_map[token.api_key] = token
800 800 else:
801 801 plain_token_map[token.api_key] = token
802 802 log.debug(
803 803 'Found %s plain and %s encrypted tokens to check for authentication for this user',
804 804 len(plain_token_map), len(enc_token_map))
805 805
806 806 # plain token match comes first
807 807 match = plain_token_map.get(auth_token)
808 808
809 809 # check encrypted tokens now
810 810 if not match:
811 811 for token_hash, token in enc_token_map.items():
812 812 # NOTE(marcink): this is expensive to calculate, but most secure
813 813 if crypto_backend.hash_check(auth_token, token_hash):
814 814 match = token
815 815 break
816 816
817 817 if match:
818 818 log.debug('Found matching token %s', match)
819 819 if match.repo_id:
820 820 log.debug('Found scope, checking for scope match of token %s', match)
821 821 if match.repo_id == scope_repo_id:
822 822 return True
823 823 else:
824 824 log.debug(
825 825 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
826 826 'and calling scope is:%s, skipping further checks',
827 827 match.repo, scope_repo_id)
828 828 return False
829 829 else:
830 830 return True
831 831
832 832 return False
833 833
834 834 @property
835 835 def ip_addresses(self):
836 836 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
837 837 return [x.ip_addr for x in ret]
838 838
839 839 @property
840 840 def username_and_name(self):
841 841 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
842 842
843 843 @property
844 844 def username_or_name_or_email(self):
845 845 full_name = self.full_name if self.full_name is not ' ' else None
846 846 return self.username or full_name or self.email
847 847
848 848 @property
849 849 def full_name(self):
850 850 return '%s %s' % (self.first_name, self.last_name)
851 851
852 852 @property
853 853 def full_name_or_username(self):
854 854 return ('%s %s' % (self.first_name, self.last_name)
855 855 if (self.first_name and self.last_name) else self.username)
856 856
857 857 @property
858 858 def full_contact(self):
859 859 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
860 860
861 861 @property
862 862 def short_contact(self):
863 863 return '%s %s' % (self.first_name, self.last_name)
864 864
865 865 @property
866 866 def is_admin(self):
867 867 return self.admin
868 868
869 869 @property
870 870 def language(self):
871 871 return self.user_data.get('language')
872 872
873 873 def AuthUser(self, **kwargs):
874 874 """
875 875 Returns instance of AuthUser for this user
876 876 """
877 877 from rhodecode.lib.auth import AuthUser
878 878 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
879 879
880 880 @hybrid_property
881 881 def user_data(self):
882 882 if not self._user_data:
883 883 return {}
884 884
885 885 try:
886 886 return json.loads(self._user_data)
887 887 except TypeError:
888 888 return {}
889 889
890 890 @user_data.setter
891 891 def user_data(self, val):
892 892 if not isinstance(val, dict):
893 893 raise Exception('user_data must be dict, got %s' % type(val))
894 894 try:
895 895 self._user_data = json.dumps(val)
896 896 except Exception:
897 897 log.error(traceback.format_exc())
898 898
899 899 @classmethod
900 900 def get_by_username(cls, username, case_insensitive=False,
901 901 cache=False, identity_cache=False):
902 902 session = Session()
903 903
904 904 if case_insensitive:
905 905 q = cls.query().filter(
906 906 func.lower(cls.username) == func.lower(username))
907 907 else:
908 908 q = cls.query().filter(cls.username == username)
909 909
910 910 if cache:
911 911 if identity_cache:
912 912 val = cls.identity_cache(session, 'username', username)
913 913 if val:
914 914 return val
915 915 else:
916 916 cache_key = "get_user_by_name_%s" % _hash_key(username)
917 917 q = q.options(
918 918 FromCache("sql_cache_short", cache_key))
919 919
920 920 return q.scalar()
921 921
922 922 @classmethod
923 923 def get_by_auth_token(cls, auth_token, cache=False):
924 924 q = UserApiKeys.query()\
925 925 .filter(UserApiKeys.api_key == auth_token)\
926 926 .filter(or_(UserApiKeys.expires == -1,
927 927 UserApiKeys.expires >= time.time()))
928 928 if cache:
929 929 q = q.options(
930 930 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
931 931
932 932 match = q.first()
933 933 if match:
934 934 return match.user
935 935
936 936 @classmethod
937 937 def get_by_email(cls, email, case_insensitive=False, cache=False):
938 938
939 939 if case_insensitive:
940 940 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
941 941
942 942 else:
943 943 q = cls.query().filter(cls.email == email)
944 944
945 945 email_key = _hash_key(email)
946 946 if cache:
947 947 q = q.options(
948 948 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
949 949
950 950 ret = q.scalar()
951 951 if ret is None:
952 952 q = UserEmailMap.query()
953 953 # try fetching in alternate email map
954 954 if case_insensitive:
955 955 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
956 956 else:
957 957 q = q.filter(UserEmailMap.email == email)
958 958 q = q.options(joinedload(UserEmailMap.user))
959 959 if cache:
960 960 q = q.options(
961 961 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
962 962 ret = getattr(q.scalar(), 'user', None)
963 963
964 964 return ret
965 965
966 966 @classmethod
967 967 def get_from_cs_author(cls, author):
968 968 """
969 969 Tries to get User objects out of commit author string
970 970
971 971 :param author:
972 972 """
973 973 from rhodecode.lib.helpers import email, author_name
974 974 # Valid email in the attribute passed, see if they're in the system
975 975 _email = email(author)
976 976 if _email:
977 977 user = cls.get_by_email(_email, case_insensitive=True)
978 978 if user:
979 979 return user
980 980 # Maybe we can match by username?
981 981 _author = author_name(author)
982 982 user = cls.get_by_username(_author, case_insensitive=True)
983 983 if user:
984 984 return user
985 985
986 986 def update_userdata(self, **kwargs):
987 987 usr = self
988 988 old = usr.user_data
989 989 old.update(**kwargs)
990 990 usr.user_data = old
991 991 Session().add(usr)
992 992 log.debug('updated userdata with %s', kwargs)
993 993
994 994 def update_lastlogin(self):
995 995 """Update user lastlogin"""
996 996 self.last_login = datetime.datetime.now()
997 997 Session().add(self)
998 998 log.debug('updated user %s lastlogin', self.username)
999 999
1000 1000 def update_password(self, new_password):
1001 1001 from rhodecode.lib.auth import get_crypt_password
1002 1002
1003 1003 self.password = get_crypt_password(new_password)
1004 1004 Session().add(self)
1005 1005
1006 1006 @classmethod
1007 1007 def get_first_super_admin(cls):
1008 1008 user = User.query()\
1009 1009 .filter(User.admin == true()) \
1010 1010 .order_by(User.user_id.asc()) \
1011 1011 .first()
1012 1012
1013 1013 if user is None:
1014 1014 raise Exception('FATAL: Missing administrative account!')
1015 1015 return user
1016 1016
1017 1017 @classmethod
1018 1018 def get_all_super_admins(cls, only_active=False):
1019 1019 """
1020 1020 Returns all admin accounts sorted by username
1021 1021 """
1022 1022 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
1023 1023 if only_active:
1024 1024 qry = qry.filter(User.active == true())
1025 1025 return qry.all()
1026 1026
1027 1027 @classmethod
1028 1028 def get_default_user(cls, cache=False, refresh=False):
1029 1029 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
1030 1030 if user is None:
1031 1031 raise Exception('FATAL: Missing default account!')
1032 1032 if refresh:
1033 1033 # The default user might be based on outdated state which
1034 1034 # has been loaded from the cache.
1035 1035 # A call to refresh() ensures that the
1036 1036 # latest state from the database is used.
1037 1037 Session().refresh(user)
1038 1038 return user
1039 1039
1040 1040 def _get_default_perms(self, user, suffix=''):
1041 1041 from rhodecode.model.permission import PermissionModel
1042 1042 return PermissionModel().get_default_perms(user.user_perms, suffix)
1043 1043
1044 1044 def get_default_perms(self, suffix=''):
1045 1045 return self._get_default_perms(self, suffix)
1046 1046
1047 1047 def get_api_data(self, include_secrets=False, details='full'):
1048 1048 """
1049 1049 Common function for generating user related data for API
1050 1050
1051 1051 :param include_secrets: By default secrets in the API data will be replaced
1052 1052 by a placeholder value to prevent exposing this data by accident. In case
1053 1053 this data shall be exposed, set this flag to ``True``.
1054 1054
1055 1055 :param details: details can be 'basic|full' basic gives only a subset of
1056 1056 the available user information that includes user_id, name and emails.
1057 1057 """
1058 1058 user = self
1059 1059 user_data = self.user_data
1060 1060 data = {
1061 1061 'user_id': user.user_id,
1062 1062 'username': user.username,
1063 1063 'firstname': user.name,
1064 1064 'lastname': user.lastname,
1065 1065 'description': user.description,
1066 1066 'email': user.email,
1067 1067 'emails': user.emails,
1068 1068 }
1069 1069 if details == 'basic':
1070 1070 return data
1071 1071
1072 1072 auth_token_length = 40
1073 1073 auth_token_replacement = '*' * auth_token_length
1074 1074
1075 1075 extras = {
1076 1076 'auth_tokens': [auth_token_replacement],
1077 1077 'active': user.active,
1078 1078 'admin': user.admin,
1079 1079 'extern_type': user.extern_type,
1080 1080 'extern_name': user.extern_name,
1081 1081 'last_login': user.last_login,
1082 1082 'last_activity': user.last_activity,
1083 1083 'ip_addresses': user.ip_addresses,
1084 1084 'language': user_data.get('language')
1085 1085 }
1086 1086 data.update(extras)
1087 1087
1088 1088 if include_secrets:
1089 1089 data['auth_tokens'] = user.auth_tokens
1090 1090 return data
1091 1091
1092 1092 def __json__(self):
1093 1093 data = {
1094 1094 'full_name': self.full_name,
1095 1095 'full_name_or_username': self.full_name_or_username,
1096 1096 'short_contact': self.short_contact,
1097 1097 'full_contact': self.full_contact,
1098 1098 }
1099 1099 data.update(self.get_api_data())
1100 1100 return data
1101 1101
1102 1102
1103 1103 class UserApiKeys(Base, BaseModel):
1104 1104 __tablename__ = 'user_api_keys'
1105 1105 __table_args__ = (
1106 1106 Index('uak_api_key_idx', 'api_key'),
1107 1107 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1108 1108 base_table_args
1109 1109 )
1110 1110 __mapper_args__ = {}
1111 1111
1112 1112 # ApiKey role
1113 1113 ROLE_ALL = 'token_role_all'
1114 1114 ROLE_HTTP = 'token_role_http'
1115 1115 ROLE_VCS = 'token_role_vcs'
1116 1116 ROLE_API = 'token_role_api'
1117 1117 ROLE_FEED = 'token_role_feed'
1118 1118 ROLE_ARTIFACT_DOWNLOAD = 'role_artifact_download'
1119 1119 ROLE_PASSWORD_RESET = 'token_password_reset'
1120 1120
1121 1121 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED, ROLE_ARTIFACT_DOWNLOAD]
1122 1122
1123 1123 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1124 1124 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1125 1125 api_key = Column("api_key", String(255), nullable=False, unique=True)
1126 1126 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1127 1127 expires = Column('expires', Float(53), nullable=False)
1128 1128 role = Column('role', String(255), nullable=True)
1129 1129 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1130 1130
1131 1131 # scope columns
1132 1132 repo_id = Column(
1133 1133 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1134 1134 nullable=True, unique=None, default=None)
1135 1135 repo = relationship('Repository', lazy='joined')
1136 1136
1137 1137 repo_group_id = Column(
1138 1138 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1139 1139 nullable=True, unique=None, default=None)
1140 1140 repo_group = relationship('RepoGroup', lazy='joined')
1141 1141
1142 1142 user = relationship('User', lazy='joined')
1143 1143
1144 1144 def __unicode__(self):
1145 1145 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1146 1146
1147 1147 def __json__(self):
1148 1148 data = {
1149 1149 'auth_token': self.api_key,
1150 1150 'role': self.role,
1151 1151 'scope': self.scope_humanized,
1152 1152 'expired': self.expired
1153 1153 }
1154 1154 return data
1155 1155
1156 1156 def get_api_data(self, include_secrets=False):
1157 1157 data = self.__json__()
1158 1158 if include_secrets:
1159 1159 return data
1160 1160 else:
1161 1161 data['auth_token'] = self.token_obfuscated
1162 1162 return data
1163 1163
1164 1164 @hybrid_property
1165 1165 def description_safe(self):
1166 1166 from rhodecode.lib import helpers as h
1167 1167 return h.escape(self.description)
1168 1168
1169 1169 @property
1170 1170 def expired(self):
1171 1171 if self.expires == -1:
1172 1172 return False
1173 1173 return time.time() > self.expires
1174 1174
1175 1175 @classmethod
1176 1176 def _get_role_name(cls, role):
1177 1177 return {
1178 1178 cls.ROLE_ALL: _('all'),
1179 1179 cls.ROLE_HTTP: _('http/web interface'),
1180 1180 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1181 1181 cls.ROLE_API: _('api calls'),
1182 1182 cls.ROLE_FEED: _('feed access'),
1183 1183 cls.ROLE_ARTIFACT_DOWNLOAD: _('artifacts downloads'),
1184 1184 }.get(role, role)
1185 1185
1186 1186 @property
1187 1187 def role_humanized(self):
1188 1188 return self._get_role_name(self.role)
1189 1189
1190 1190 def _get_scope(self):
1191 1191 if self.repo:
1192 1192 return 'Repository: {}'.format(self.repo.repo_name)
1193 1193 if self.repo_group:
1194 1194 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1195 1195 return 'Global'
1196 1196
1197 1197 @property
1198 1198 def scope_humanized(self):
1199 1199 return self._get_scope()
1200 1200
1201 1201 @property
1202 1202 def token_obfuscated(self):
1203 1203 if self.api_key:
1204 1204 return self.api_key[:4] + "****"
1205 1205
1206 1206
1207 1207 class UserEmailMap(Base, BaseModel):
1208 1208 __tablename__ = 'user_email_map'
1209 1209 __table_args__ = (
1210 1210 Index('uem_email_idx', 'email'),
1211 1211 UniqueConstraint('email'),
1212 1212 base_table_args
1213 1213 )
1214 1214 __mapper_args__ = {}
1215 1215
1216 1216 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1217 1217 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1218 1218 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1219 1219 user = relationship('User', lazy='joined')
1220 1220
1221 1221 @validates('_email')
1222 1222 def validate_email(self, key, email):
1223 1223 # check if this email is not main one
1224 1224 main_email = Session().query(User).filter(User.email == email).scalar()
1225 1225 if main_email is not None:
1226 1226 raise AttributeError('email %s is present is user table' % email)
1227 1227 return email
1228 1228
1229 1229 @hybrid_property
1230 1230 def email(self):
1231 1231 return self._email
1232 1232
1233 1233 @email.setter
1234 1234 def email(self, val):
1235 1235 self._email = val.lower() if val else None
1236 1236
1237 1237
1238 1238 class UserIpMap(Base, BaseModel):
1239 1239 __tablename__ = 'user_ip_map'
1240 1240 __table_args__ = (
1241 1241 UniqueConstraint('user_id', 'ip_addr'),
1242 1242 base_table_args
1243 1243 )
1244 1244 __mapper_args__ = {}
1245 1245
1246 1246 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1247 1247 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1248 1248 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1249 1249 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1250 1250 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1251 1251 user = relationship('User', lazy='joined')
1252 1252
1253 1253 @hybrid_property
1254 1254 def description_safe(self):
1255 1255 from rhodecode.lib import helpers as h
1256 1256 return h.escape(self.description)
1257 1257
1258 1258 @classmethod
1259 1259 def _get_ip_range(cls, ip_addr):
1260 1260 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1261 1261 return [str(net.network_address), str(net.broadcast_address)]
1262 1262
1263 1263 def __json__(self):
1264 1264 return {
1265 1265 'ip_addr': self.ip_addr,
1266 1266 'ip_range': self._get_ip_range(self.ip_addr),
1267 1267 }
1268 1268
1269 1269 def __unicode__(self):
1270 1270 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1271 1271 self.user_id, self.ip_addr)
1272 1272
1273 1273
1274 1274 class UserSshKeys(Base, BaseModel):
1275 1275 __tablename__ = 'user_ssh_keys'
1276 1276 __table_args__ = (
1277 1277 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1278 1278
1279 1279 UniqueConstraint('ssh_key_fingerprint'),
1280 1280
1281 1281 base_table_args
1282 1282 )
1283 1283 __mapper_args__ = {}
1284 1284
1285 1285 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1286 1286 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1287 1287 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1288 1288
1289 1289 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1290 1290
1291 1291 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1292 1292 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1293 1293 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1294 1294
1295 1295 user = relationship('User', lazy='joined')
1296 1296
1297 1297 def __json__(self):
1298 1298 data = {
1299 1299 'ssh_fingerprint': self.ssh_key_fingerprint,
1300 1300 'description': self.description,
1301 1301 'created_on': self.created_on
1302 1302 }
1303 1303 return data
1304 1304
1305 1305 def get_api_data(self):
1306 1306 data = self.__json__()
1307 1307 return data
1308 1308
1309 1309
1310 1310 class UserLog(Base, BaseModel):
1311 1311 __tablename__ = 'user_logs'
1312 1312 __table_args__ = (
1313 1313 base_table_args,
1314 1314 )
1315 1315
1316 1316 VERSION_1 = 'v1'
1317 1317 VERSION_2 = 'v2'
1318 1318 VERSIONS = [VERSION_1, VERSION_2]
1319 1319
1320 1320 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1321 1321 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1322 1322 username = Column("username", String(255), nullable=True, unique=None, default=None)
1323 1323 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1324 1324 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1325 1325 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1326 1326 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1327 1327 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1328 1328
1329 1329 version = Column("version", String(255), nullable=True, default=VERSION_1)
1330 1330 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1331 1331 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1332 1332
1333 1333 def __unicode__(self):
1334 1334 return u"<%s('id:%s:%s')>" % (
1335 1335 self.__class__.__name__, self.repository_name, self.action)
1336 1336
1337 1337 def __json__(self):
1338 1338 return {
1339 1339 'user_id': self.user_id,
1340 1340 'username': self.username,
1341 1341 'repository_id': self.repository_id,
1342 1342 'repository_name': self.repository_name,
1343 1343 'user_ip': self.user_ip,
1344 1344 'action_date': self.action_date,
1345 1345 'action': self.action,
1346 1346 }
1347 1347
1348 1348 @hybrid_property
1349 1349 def entry_id(self):
1350 1350 return self.user_log_id
1351 1351
1352 1352 @property
1353 1353 def action_as_day(self):
1354 1354 return datetime.date(*self.action_date.timetuple()[:3])
1355 1355
1356 1356 user = relationship('User')
1357 1357 repository = relationship('Repository', cascade='')
1358 1358
1359 1359
1360 1360 class UserGroup(Base, BaseModel):
1361 1361 __tablename__ = 'users_groups'
1362 1362 __table_args__ = (
1363 1363 base_table_args,
1364 1364 )
1365 1365
1366 1366 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1367 1367 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1368 1368 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1369 1369 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1370 1370 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1371 1371 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1372 1372 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1373 1373 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1374 1374
1375 1375 members = relationship('UserGroupMember', cascade="all, delete-orphan", lazy="joined")
1376 1376 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1377 1377 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1378 1378 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1379 1379 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1380 1380 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1381 1381
1382 1382 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1383 1383 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1384 1384
1385 1385 @classmethod
1386 1386 def _load_group_data(cls, column):
1387 1387 if not column:
1388 1388 return {}
1389 1389
1390 1390 try:
1391 1391 return json.loads(column) or {}
1392 1392 except TypeError:
1393 1393 return {}
1394 1394
1395 1395 @hybrid_property
1396 1396 def description_safe(self):
1397 1397 from rhodecode.lib import helpers as h
1398 1398 return h.escape(self.user_group_description)
1399 1399
1400 1400 @hybrid_property
1401 1401 def group_data(self):
1402 1402 return self._load_group_data(self._group_data)
1403 1403
1404 1404 @group_data.expression
1405 1405 def group_data(self, **kwargs):
1406 1406 return self._group_data
1407 1407
1408 1408 @group_data.setter
1409 1409 def group_data(self, val):
1410 1410 try:
1411 1411 self._group_data = json.dumps(val)
1412 1412 except Exception:
1413 1413 log.error(traceback.format_exc())
1414 1414
1415 1415 @classmethod
1416 1416 def _load_sync(cls, group_data):
1417 1417 if group_data:
1418 1418 return group_data.get('extern_type')
1419 1419
1420 1420 @property
1421 1421 def sync(self):
1422 1422 return self._load_sync(self.group_data)
1423 1423
1424 1424 def __unicode__(self):
1425 1425 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1426 1426 self.users_group_id,
1427 1427 self.users_group_name)
1428 1428
1429 1429 @classmethod
1430 1430 def get_by_group_name(cls, group_name, cache=False,
1431 1431 case_insensitive=False):
1432 1432 if case_insensitive:
1433 1433 q = cls.query().filter(func.lower(cls.users_group_name) ==
1434 1434 func.lower(group_name))
1435 1435
1436 1436 else:
1437 1437 q = cls.query().filter(cls.users_group_name == group_name)
1438 1438 if cache:
1439 1439 q = q.options(
1440 1440 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1441 1441 return q.scalar()
1442 1442
1443 1443 @classmethod
1444 1444 def get(cls, user_group_id, cache=False):
1445 1445 if not user_group_id:
1446 1446 return
1447 1447
1448 1448 user_group = cls.query()
1449 1449 if cache:
1450 1450 user_group = user_group.options(
1451 1451 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1452 1452 return user_group.get(user_group_id)
1453 1453
1454 1454 def permissions(self, with_admins=True, with_owner=True,
1455 1455 expand_from_user_groups=False):
1456 1456 """
1457 1457 Permissions for user groups
1458 1458 """
1459 1459 _admin_perm = 'usergroup.admin'
1460 1460
1461 1461 owner_row = []
1462 1462 if with_owner:
1463 1463 usr = AttributeDict(self.user.get_dict())
1464 1464 usr.owner_row = True
1465 1465 usr.permission = _admin_perm
1466 1466 owner_row.append(usr)
1467 1467
1468 1468 super_admin_ids = []
1469 1469 super_admin_rows = []
1470 1470 if with_admins:
1471 1471 for usr in User.get_all_super_admins():
1472 1472 super_admin_ids.append(usr.user_id)
1473 1473 # if this admin is also owner, don't double the record
1474 1474 if usr.user_id == owner_row[0].user_id:
1475 1475 owner_row[0].admin_row = True
1476 1476 else:
1477 1477 usr = AttributeDict(usr.get_dict())
1478 1478 usr.admin_row = True
1479 1479 usr.permission = _admin_perm
1480 1480 super_admin_rows.append(usr)
1481 1481
1482 1482 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1483 1483 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1484 1484 joinedload(UserUserGroupToPerm.user),
1485 1485 joinedload(UserUserGroupToPerm.permission),)
1486 1486
1487 1487 # get owners and admins and permissions. We do a trick of re-writing
1488 1488 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1489 1489 # has a global reference and changing one object propagates to all
1490 1490 # others. This means if admin is also an owner admin_row that change
1491 1491 # would propagate to both objects
1492 1492 perm_rows = []
1493 1493 for _usr in q.all():
1494 1494 usr = AttributeDict(_usr.user.get_dict())
1495 1495 # if this user is also owner/admin, mark as duplicate record
1496 1496 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1497 1497 usr.duplicate_perm = True
1498 1498 usr.permission = _usr.permission.permission_name
1499 1499 perm_rows.append(usr)
1500 1500
1501 1501 # filter the perm rows by 'default' first and then sort them by
1502 1502 # admin,write,read,none permissions sorted again alphabetically in
1503 1503 # each group
1504 1504 perm_rows = sorted(perm_rows, key=display_user_sort)
1505 1505
1506 1506 user_groups_rows = []
1507 1507 if expand_from_user_groups:
1508 1508 for ug in self.permission_user_groups(with_members=True):
1509 1509 for user_data in ug.members:
1510 1510 user_groups_rows.append(user_data)
1511 1511
1512 1512 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1513 1513
1514 1514 def permission_user_groups(self, with_members=False):
1515 1515 q = UserGroupUserGroupToPerm.query()\
1516 1516 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1517 1517 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1518 1518 joinedload(UserGroupUserGroupToPerm.target_user_group),
1519 1519 joinedload(UserGroupUserGroupToPerm.permission),)
1520 1520
1521 1521 perm_rows = []
1522 1522 for _user_group in q.all():
1523 1523 entry = AttributeDict(_user_group.user_group.get_dict())
1524 1524 entry.permission = _user_group.permission.permission_name
1525 1525 if with_members:
1526 1526 entry.members = [x.user.get_dict()
1527 1527 for x in _user_group.user_group.members]
1528 1528 perm_rows.append(entry)
1529 1529
1530 1530 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1531 1531 return perm_rows
1532 1532
1533 1533 def _get_default_perms(self, user_group, suffix=''):
1534 1534 from rhodecode.model.permission import PermissionModel
1535 1535 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1536 1536
1537 1537 def get_default_perms(self, suffix=''):
1538 1538 return self._get_default_perms(self, suffix)
1539 1539
1540 1540 def get_api_data(self, with_group_members=True, include_secrets=False):
1541 1541 """
1542 1542 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1543 1543 basically forwarded.
1544 1544
1545 1545 """
1546 1546 user_group = self
1547 1547 data = {
1548 1548 'users_group_id': user_group.users_group_id,
1549 1549 'group_name': user_group.users_group_name,
1550 1550 'group_description': user_group.user_group_description,
1551 1551 'active': user_group.users_group_active,
1552 1552 'owner': user_group.user.username,
1553 1553 'sync': user_group.sync,
1554 1554 'owner_email': user_group.user.email,
1555 1555 }
1556 1556
1557 1557 if with_group_members:
1558 1558 users = []
1559 1559 for user in user_group.members:
1560 1560 user = user.user
1561 1561 users.append(user.get_api_data(include_secrets=include_secrets))
1562 1562 data['users'] = users
1563 1563
1564 1564 return data
1565 1565
1566 1566
1567 1567 class UserGroupMember(Base, BaseModel):
1568 1568 __tablename__ = 'users_groups_members'
1569 1569 __table_args__ = (
1570 1570 base_table_args,
1571 1571 )
1572 1572
1573 1573 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1574 1574 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1575 1575 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1576 1576
1577 1577 user = relationship('User', lazy='joined')
1578 1578 users_group = relationship('UserGroup')
1579 1579
1580 1580 def __init__(self, gr_id='', u_id=''):
1581 1581 self.users_group_id = gr_id
1582 1582 self.user_id = u_id
1583 1583
1584 1584
1585 1585 class RepositoryField(Base, BaseModel):
1586 1586 __tablename__ = 'repositories_fields'
1587 1587 __table_args__ = (
1588 1588 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1589 1589 base_table_args,
1590 1590 )
1591 1591
1592 1592 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1593 1593
1594 1594 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1595 1595 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1596 1596 field_key = Column("field_key", String(250))
1597 1597 field_label = Column("field_label", String(1024), nullable=False)
1598 1598 field_value = Column("field_value", String(10000), nullable=False)
1599 1599 field_desc = Column("field_desc", String(1024), nullable=False)
1600 1600 field_type = Column("field_type", String(255), nullable=False, unique=None)
1601 1601 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1602 1602
1603 1603 repository = relationship('Repository')
1604 1604
1605 1605 @property
1606 1606 def field_key_prefixed(self):
1607 1607 return 'ex_%s' % self.field_key
1608 1608
1609 1609 @classmethod
1610 1610 def un_prefix_key(cls, key):
1611 1611 if key.startswith(cls.PREFIX):
1612 1612 return key[len(cls.PREFIX):]
1613 1613 return key
1614 1614
1615 1615 @classmethod
1616 1616 def get_by_key_name(cls, key, repo):
1617 1617 row = cls.query()\
1618 1618 .filter(cls.repository == repo)\
1619 1619 .filter(cls.field_key == key).scalar()
1620 1620 return row
1621 1621
1622 1622
1623 1623 class Repository(Base, BaseModel):
1624 1624 __tablename__ = 'repositories'
1625 1625 __table_args__ = (
1626 1626 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1627 1627 base_table_args,
1628 1628 )
1629 1629 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1630 1630 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1631 1631 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1632 1632
1633 1633 STATE_CREATED = 'repo_state_created'
1634 1634 STATE_PENDING = 'repo_state_pending'
1635 1635 STATE_ERROR = 'repo_state_error'
1636 1636
1637 1637 LOCK_AUTOMATIC = 'lock_auto'
1638 1638 LOCK_API = 'lock_api'
1639 1639 LOCK_WEB = 'lock_web'
1640 1640 LOCK_PULL = 'lock_pull'
1641 1641
1642 1642 NAME_SEP = URL_SEP
1643 1643
1644 1644 repo_id = Column(
1645 1645 "repo_id", Integer(), nullable=False, unique=True, default=None,
1646 1646 primary_key=True)
1647 1647 _repo_name = Column(
1648 1648 "repo_name", Text(), nullable=False, default=None)
1649 1649 _repo_name_hash = Column(
1650 1650 "repo_name_hash", String(255), nullable=False, unique=True)
1651 1651 repo_state = Column("repo_state", String(255), nullable=True)
1652 1652
1653 1653 clone_uri = Column(
1654 1654 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1655 1655 default=None)
1656 1656 push_uri = Column(
1657 1657 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1658 1658 default=None)
1659 1659 repo_type = Column(
1660 1660 "repo_type", String(255), nullable=False, unique=False, default=None)
1661 1661 user_id = Column(
1662 1662 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1663 1663 unique=False, default=None)
1664 1664 private = Column(
1665 1665 "private", Boolean(), nullable=True, unique=None, default=None)
1666 1666 archived = Column(
1667 1667 "archived", Boolean(), nullable=True, unique=None, default=None)
1668 1668 enable_statistics = Column(
1669 1669 "statistics", Boolean(), nullable=True, unique=None, default=True)
1670 1670 enable_downloads = Column(
1671 1671 "downloads", Boolean(), nullable=True, unique=None, default=True)
1672 1672 description = Column(
1673 1673 "description", String(10000), nullable=True, unique=None, default=None)
1674 1674 created_on = Column(
1675 1675 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1676 1676 default=datetime.datetime.now)
1677 1677 updated_on = Column(
1678 1678 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1679 1679 default=datetime.datetime.now)
1680 1680 _landing_revision = Column(
1681 1681 "landing_revision", String(255), nullable=False, unique=False,
1682 1682 default=None)
1683 1683 enable_locking = Column(
1684 1684 "enable_locking", Boolean(), nullable=False, unique=None,
1685 1685 default=False)
1686 1686 _locked = Column(
1687 1687 "locked", String(255), nullable=True, unique=False, default=None)
1688 1688 _changeset_cache = Column(
1689 1689 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1690 1690
1691 1691 fork_id = Column(
1692 1692 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1693 1693 nullable=True, unique=False, default=None)
1694 1694 group_id = Column(
1695 1695 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1696 1696 unique=False, default=None)
1697 1697
1698 1698 user = relationship('User', lazy='joined')
1699 1699 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1700 1700 group = relationship('RepoGroup', lazy='joined')
1701 1701 repo_to_perm = relationship(
1702 1702 'UserRepoToPerm', cascade='all',
1703 1703 order_by='UserRepoToPerm.repo_to_perm_id')
1704 1704 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1705 1705 stats = relationship('Statistics', cascade='all', uselist=False)
1706 1706
1707 1707 followers = relationship(
1708 1708 'UserFollowing',
1709 1709 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1710 1710 cascade='all')
1711 1711 extra_fields = relationship(
1712 1712 'RepositoryField', cascade="all, delete-orphan")
1713 1713 logs = relationship('UserLog')
1714 1714 comments = relationship(
1715 1715 'ChangesetComment', cascade="all, delete-orphan")
1716 1716 pull_requests_source = relationship(
1717 1717 'PullRequest',
1718 1718 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1719 1719 cascade="all, delete-orphan")
1720 1720 pull_requests_target = relationship(
1721 1721 'PullRequest',
1722 1722 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1723 1723 cascade="all, delete-orphan")
1724 1724 ui = relationship('RepoRhodeCodeUi', cascade="all")
1725 1725 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1726 1726 integrations = relationship('Integration', cascade="all, delete-orphan")
1727 1727
1728 1728 scoped_tokens = relationship('UserApiKeys', cascade="all")
1729 1729
1730 1730 # no cascade, set NULL
1731 1731 artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_id==Repository.repo_id')
1732 1732
1733 1733 def __unicode__(self):
1734 1734 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1735 1735 safe_unicode(self.repo_name))
1736 1736
1737 1737 @hybrid_property
1738 1738 def description_safe(self):
1739 1739 from rhodecode.lib import helpers as h
1740 1740 return h.escape(self.description)
1741 1741
1742 1742 @hybrid_property
1743 1743 def landing_rev(self):
1744 1744 # always should return [rev_type, rev]
1745 1745 if self._landing_revision:
1746 1746 _rev_info = self._landing_revision.split(':')
1747 1747 if len(_rev_info) < 2:
1748 1748 _rev_info.insert(0, 'rev')
1749 1749 return [_rev_info[0], _rev_info[1]]
1750 1750 return [None, None]
1751 1751
1752 1752 @landing_rev.setter
1753 1753 def landing_rev(self, val):
1754 1754 if ':' not in val:
1755 1755 raise ValueError('value must be delimited with `:` and consist '
1756 1756 'of <rev_type>:<rev>, got %s instead' % val)
1757 1757 self._landing_revision = val
1758 1758
1759 1759 @hybrid_property
1760 1760 def locked(self):
1761 1761 if self._locked:
1762 1762 user_id, timelocked, reason = self._locked.split(':')
1763 1763 lock_values = int(user_id), timelocked, reason
1764 1764 else:
1765 1765 lock_values = [None, None, None]
1766 1766 return lock_values
1767 1767
1768 1768 @locked.setter
1769 1769 def locked(self, val):
1770 1770 if val and isinstance(val, (list, tuple)):
1771 1771 self._locked = ':'.join(map(str, val))
1772 1772 else:
1773 1773 self._locked = None
1774 1774
1775 1775 @hybrid_property
1776 1776 def changeset_cache(self):
1777 1777 from rhodecode.lib.vcs.backends.base import EmptyCommit
1778 1778 dummy = EmptyCommit().__json__()
1779 1779 if not self._changeset_cache:
1780 1780 dummy['source_repo_id'] = self.repo_id
1781 1781 return json.loads(json.dumps(dummy))
1782 1782
1783 1783 try:
1784 1784 return json.loads(self._changeset_cache)
1785 1785 except TypeError:
1786 1786 return dummy
1787 1787 except Exception:
1788 1788 log.error(traceback.format_exc())
1789 1789 return dummy
1790 1790
1791 1791 @changeset_cache.setter
1792 1792 def changeset_cache(self, val):
1793 1793 try:
1794 1794 self._changeset_cache = json.dumps(val)
1795 1795 except Exception:
1796 1796 log.error(traceback.format_exc())
1797 1797
1798 1798 @hybrid_property
1799 1799 def repo_name(self):
1800 1800 return self._repo_name
1801 1801
1802 1802 @repo_name.setter
1803 1803 def repo_name(self, value):
1804 1804 self._repo_name = value
1805 1805 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1806 1806
1807 1807 @classmethod
1808 1808 def normalize_repo_name(cls, repo_name):
1809 1809 """
1810 1810 Normalizes os specific repo_name to the format internally stored inside
1811 1811 database using URL_SEP
1812 1812
1813 1813 :param cls:
1814 1814 :param repo_name:
1815 1815 """
1816 1816 return cls.NAME_SEP.join(repo_name.split(os.sep))
1817 1817
1818 1818 @classmethod
1819 1819 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1820 1820 session = Session()
1821 1821 q = session.query(cls).filter(cls.repo_name == repo_name)
1822 1822
1823 1823 if cache:
1824 1824 if identity_cache:
1825 1825 val = cls.identity_cache(session, 'repo_name', repo_name)
1826 1826 if val:
1827 1827 return val
1828 1828 else:
1829 1829 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1830 1830 q = q.options(
1831 1831 FromCache("sql_cache_short", cache_key))
1832 1832
1833 1833 return q.scalar()
1834 1834
1835 1835 @classmethod
1836 1836 def get_by_id_or_repo_name(cls, repoid):
1837 1837 if isinstance(repoid, (int, long)):
1838 1838 try:
1839 1839 repo = cls.get(repoid)
1840 1840 except ValueError:
1841 1841 repo = None
1842 1842 else:
1843 1843 repo = cls.get_by_repo_name(repoid)
1844 1844 return repo
1845 1845
1846 1846 @classmethod
1847 1847 def get_by_full_path(cls, repo_full_path):
1848 1848 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1849 1849 repo_name = cls.normalize_repo_name(repo_name)
1850 1850 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1851 1851
1852 1852 @classmethod
1853 1853 def get_repo_forks(cls, repo_id):
1854 1854 return cls.query().filter(Repository.fork_id == repo_id)
1855 1855
1856 1856 @classmethod
1857 1857 def base_path(cls):
1858 1858 """
1859 1859 Returns base path when all repos are stored
1860 1860
1861 1861 :param cls:
1862 1862 """
1863 1863 q = Session().query(RhodeCodeUi)\
1864 1864 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1865 1865 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1866 1866 return q.one().ui_value
1867 1867
1868 1868 @classmethod
1869 1869 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1870 1870 case_insensitive=True, archived=False):
1871 1871 q = Repository.query()
1872 1872
1873 1873 if not archived:
1874 1874 q = q.filter(Repository.archived.isnot(true()))
1875 1875
1876 1876 if not isinstance(user_id, Optional):
1877 1877 q = q.filter(Repository.user_id == user_id)
1878 1878
1879 1879 if not isinstance(group_id, Optional):
1880 1880 q = q.filter(Repository.group_id == group_id)
1881 1881
1882 1882 if case_insensitive:
1883 1883 q = q.order_by(func.lower(Repository.repo_name))
1884 1884 else:
1885 1885 q = q.order_by(Repository.repo_name)
1886 1886
1887 1887 return q.all()
1888 1888
1889 1889 @property
1890 1890 def repo_uid(self):
1891 1891 return '_{}'.format(self.repo_id)
1892 1892
1893 1893 @property
1894 1894 def forks(self):
1895 1895 """
1896 1896 Return forks of this repo
1897 1897 """
1898 1898 return Repository.get_repo_forks(self.repo_id)
1899 1899
1900 1900 @property
1901 1901 def parent(self):
1902 1902 """
1903 1903 Returns fork parent
1904 1904 """
1905 1905 return self.fork
1906 1906
1907 1907 @property
1908 1908 def just_name(self):
1909 1909 return self.repo_name.split(self.NAME_SEP)[-1]
1910 1910
1911 1911 @property
1912 1912 def groups_with_parents(self):
1913 1913 groups = []
1914 1914 if self.group is None:
1915 1915 return groups
1916 1916
1917 1917 cur_gr = self.group
1918 1918 groups.insert(0, cur_gr)
1919 1919 while 1:
1920 1920 gr = getattr(cur_gr, 'parent_group', None)
1921 1921 cur_gr = cur_gr.parent_group
1922 1922 if gr is None:
1923 1923 break
1924 1924 groups.insert(0, gr)
1925 1925
1926 1926 return groups
1927 1927
1928 1928 @property
1929 1929 def groups_and_repo(self):
1930 1930 return self.groups_with_parents, self
1931 1931
1932 1932 @LazyProperty
1933 1933 def repo_path(self):
1934 1934 """
1935 1935 Returns base full path for that repository means where it actually
1936 1936 exists on a filesystem
1937 1937 """
1938 1938 q = Session().query(RhodeCodeUi).filter(
1939 1939 RhodeCodeUi.ui_key == self.NAME_SEP)
1940 1940 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1941 1941 return q.one().ui_value
1942 1942
1943 1943 @property
1944 1944 def repo_full_path(self):
1945 1945 p = [self.repo_path]
1946 1946 # we need to split the name by / since this is how we store the
1947 1947 # names in the database, but that eventually needs to be converted
1948 1948 # into a valid system path
1949 1949 p += self.repo_name.split(self.NAME_SEP)
1950 1950 return os.path.join(*map(safe_unicode, p))
1951 1951
1952 1952 @property
1953 1953 def cache_keys(self):
1954 1954 """
1955 1955 Returns associated cache keys for that repo
1956 1956 """
1957 1957 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1958 1958 repo_id=self.repo_id)
1959 1959 return CacheKey.query()\
1960 1960 .filter(CacheKey.cache_args == invalidation_namespace)\
1961 1961 .order_by(CacheKey.cache_key)\
1962 1962 .all()
1963 1963
1964 1964 @property
1965 1965 def cached_diffs_relative_dir(self):
1966 1966 """
1967 1967 Return a relative to the repository store path of cached diffs
1968 1968 used for safe display for users, who shouldn't know the absolute store
1969 1969 path
1970 1970 """
1971 1971 return os.path.join(
1972 1972 os.path.dirname(self.repo_name),
1973 1973 self.cached_diffs_dir.split(os.path.sep)[-1])
1974 1974
1975 1975 @property
1976 1976 def cached_diffs_dir(self):
1977 1977 path = self.repo_full_path
1978 1978 return os.path.join(
1979 1979 os.path.dirname(path),
1980 1980 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1981 1981
1982 1982 def cached_diffs(self):
1983 1983 diff_cache_dir = self.cached_diffs_dir
1984 1984 if os.path.isdir(diff_cache_dir):
1985 1985 return os.listdir(diff_cache_dir)
1986 1986 return []
1987 1987
1988 1988 def shadow_repos(self):
1989 1989 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1990 1990 return [
1991 1991 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1992 1992 if x.startswith(shadow_repos_pattern)]
1993 1993
1994 1994 def get_new_name(self, repo_name):
1995 1995 """
1996 1996 returns new full repository name based on assigned group and new new
1997 1997
1998 1998 :param group_name:
1999 1999 """
2000 2000 path_prefix = self.group.full_path_splitted if self.group else []
2001 2001 return self.NAME_SEP.join(path_prefix + [repo_name])
2002 2002
2003 2003 @property
2004 2004 def _config(self):
2005 2005 """
2006 2006 Returns db based config object.
2007 2007 """
2008 2008 from rhodecode.lib.utils import make_db_config
2009 2009 return make_db_config(clear_session=False, repo=self)
2010 2010
2011 2011 def permissions(self, with_admins=True, with_owner=True,
2012 2012 expand_from_user_groups=False):
2013 2013 """
2014 2014 Permissions for repositories
2015 2015 """
2016 2016 _admin_perm = 'repository.admin'
2017 2017
2018 2018 owner_row = []
2019 2019 if with_owner:
2020 2020 usr = AttributeDict(self.user.get_dict())
2021 2021 usr.owner_row = True
2022 2022 usr.permission = _admin_perm
2023 2023 usr.permission_id = None
2024 2024 owner_row.append(usr)
2025 2025
2026 2026 super_admin_ids = []
2027 2027 super_admin_rows = []
2028 2028 if with_admins:
2029 2029 for usr in User.get_all_super_admins():
2030 2030 super_admin_ids.append(usr.user_id)
2031 2031 # if this admin is also owner, don't double the record
2032 2032 if usr.user_id == owner_row[0].user_id:
2033 2033 owner_row[0].admin_row = True
2034 2034 else:
2035 2035 usr = AttributeDict(usr.get_dict())
2036 2036 usr.admin_row = True
2037 2037 usr.permission = _admin_perm
2038 2038 usr.permission_id = None
2039 2039 super_admin_rows.append(usr)
2040 2040
2041 2041 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
2042 2042 q = q.options(joinedload(UserRepoToPerm.repository),
2043 2043 joinedload(UserRepoToPerm.user),
2044 2044 joinedload(UserRepoToPerm.permission),)
2045 2045
2046 2046 # get owners and admins and permissions. We do a trick of re-writing
2047 2047 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2048 2048 # has a global reference and changing one object propagates to all
2049 2049 # others. This means if admin is also an owner admin_row that change
2050 2050 # would propagate to both objects
2051 2051 perm_rows = []
2052 2052 for _usr in q.all():
2053 2053 usr = AttributeDict(_usr.user.get_dict())
2054 2054 # if this user is also owner/admin, mark as duplicate record
2055 2055 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2056 2056 usr.duplicate_perm = True
2057 2057 # also check if this permission is maybe used by branch_permissions
2058 2058 if _usr.branch_perm_entry:
2059 2059 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2060 2060
2061 2061 usr.permission = _usr.permission.permission_name
2062 2062 usr.permission_id = _usr.repo_to_perm_id
2063 2063 perm_rows.append(usr)
2064 2064
2065 2065 # filter the perm rows by 'default' first and then sort them by
2066 2066 # admin,write,read,none permissions sorted again alphabetically in
2067 2067 # each group
2068 2068 perm_rows = sorted(perm_rows, key=display_user_sort)
2069 2069
2070 2070 user_groups_rows = []
2071 2071 if expand_from_user_groups:
2072 2072 for ug in self.permission_user_groups(with_members=True):
2073 2073 for user_data in ug.members:
2074 2074 user_groups_rows.append(user_data)
2075 2075
2076 2076 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2077 2077
2078 2078 def permission_user_groups(self, with_members=True):
2079 2079 q = UserGroupRepoToPerm.query()\
2080 2080 .filter(UserGroupRepoToPerm.repository == self)
2081 2081 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2082 2082 joinedload(UserGroupRepoToPerm.users_group),
2083 2083 joinedload(UserGroupRepoToPerm.permission),)
2084 2084
2085 2085 perm_rows = []
2086 2086 for _user_group in q.all():
2087 2087 entry = AttributeDict(_user_group.users_group.get_dict())
2088 2088 entry.permission = _user_group.permission.permission_name
2089 2089 if with_members:
2090 2090 entry.members = [x.user.get_dict()
2091 2091 for x in _user_group.users_group.members]
2092 2092 perm_rows.append(entry)
2093 2093
2094 2094 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2095 2095 return perm_rows
2096 2096
2097 2097 def get_api_data(self, include_secrets=False):
2098 2098 """
2099 2099 Common function for generating repo api data
2100 2100
2101 2101 :param include_secrets: See :meth:`User.get_api_data`.
2102 2102
2103 2103 """
2104 2104 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2105 2105 # move this methods on models level.
2106 2106 from rhodecode.model.settings import SettingsModel
2107 2107 from rhodecode.model.repo import RepoModel
2108 2108
2109 2109 repo = self
2110 2110 _user_id, _time, _reason = self.locked
2111 2111
2112 2112 data = {
2113 2113 'repo_id': repo.repo_id,
2114 2114 'repo_name': repo.repo_name,
2115 2115 'repo_type': repo.repo_type,
2116 2116 'clone_uri': repo.clone_uri or '',
2117 2117 'push_uri': repo.push_uri or '',
2118 2118 'url': RepoModel().get_url(self),
2119 2119 'private': repo.private,
2120 2120 'created_on': repo.created_on,
2121 2121 'description': repo.description_safe,
2122 2122 'landing_rev': repo.landing_rev,
2123 2123 'owner': repo.user.username,
2124 2124 'fork_of': repo.fork.repo_name if repo.fork else None,
2125 2125 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2126 2126 'enable_statistics': repo.enable_statistics,
2127 2127 'enable_locking': repo.enable_locking,
2128 2128 'enable_downloads': repo.enable_downloads,
2129 2129 'last_changeset': repo.changeset_cache,
2130 2130 'locked_by': User.get(_user_id).get_api_data(
2131 2131 include_secrets=include_secrets) if _user_id else None,
2132 2132 'locked_date': time_to_datetime(_time) if _time else None,
2133 2133 'lock_reason': _reason if _reason else None,
2134 2134 }
2135 2135
2136 2136 # TODO: mikhail: should be per-repo settings here
2137 2137 rc_config = SettingsModel().get_all_settings()
2138 2138 repository_fields = str2bool(
2139 2139 rc_config.get('rhodecode_repository_fields'))
2140 2140 if repository_fields:
2141 2141 for f in self.extra_fields:
2142 2142 data[f.field_key_prefixed] = f.field_value
2143 2143
2144 2144 return data
2145 2145
2146 2146 @classmethod
2147 2147 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2148 2148 if not lock_time:
2149 2149 lock_time = time.time()
2150 2150 if not lock_reason:
2151 2151 lock_reason = cls.LOCK_AUTOMATIC
2152 2152 repo.locked = [user_id, lock_time, lock_reason]
2153 2153 Session().add(repo)
2154 2154 Session().commit()
2155 2155
2156 2156 @classmethod
2157 2157 def unlock(cls, repo):
2158 2158 repo.locked = None
2159 2159 Session().add(repo)
2160 2160 Session().commit()
2161 2161
2162 2162 @classmethod
2163 2163 def getlock(cls, repo):
2164 2164 return repo.locked
2165 2165
2166 2166 def is_user_lock(self, user_id):
2167 2167 if self.lock[0]:
2168 2168 lock_user_id = safe_int(self.lock[0])
2169 2169 user_id = safe_int(user_id)
2170 2170 # both are ints, and they are equal
2171 2171 return all([lock_user_id, user_id]) and lock_user_id == user_id
2172 2172
2173 2173 return False
2174 2174
2175 2175 def get_locking_state(self, action, user_id, only_when_enabled=True):
2176 2176 """
2177 2177 Checks locking on this repository, if locking is enabled and lock is
2178 2178 present returns a tuple of make_lock, locked, locked_by.
2179 2179 make_lock can have 3 states None (do nothing) True, make lock
2180 2180 False release lock, This value is later propagated to hooks, which
2181 2181 do the locking. Think about this as signals passed to hooks what to do.
2182 2182
2183 2183 """
2184 2184 # TODO: johbo: This is part of the business logic and should be moved
2185 2185 # into the RepositoryModel.
2186 2186
2187 2187 if action not in ('push', 'pull'):
2188 2188 raise ValueError("Invalid action value: %s" % repr(action))
2189 2189
2190 2190 # defines if locked error should be thrown to user
2191 2191 currently_locked = False
2192 2192 # defines if new lock should be made, tri-state
2193 2193 make_lock = None
2194 2194 repo = self
2195 2195 user = User.get(user_id)
2196 2196
2197 2197 lock_info = repo.locked
2198 2198
2199 2199 if repo and (repo.enable_locking or not only_when_enabled):
2200 2200 if action == 'push':
2201 2201 # check if it's already locked !, if it is compare users
2202 2202 locked_by_user_id = lock_info[0]
2203 2203 if user.user_id == locked_by_user_id:
2204 2204 log.debug(
2205 2205 'Got `push` action from user %s, now unlocking', user)
2206 2206 # unlock if we have push from user who locked
2207 2207 make_lock = False
2208 2208 else:
2209 2209 # we're not the same user who locked, ban with
2210 2210 # code defined in settings (default is 423 HTTP Locked) !
2211 2211 log.debug('Repo %s is currently locked by %s', repo, user)
2212 2212 currently_locked = True
2213 2213 elif action == 'pull':
2214 2214 # [0] user [1] date
2215 2215 if lock_info[0] and lock_info[1]:
2216 2216 log.debug('Repo %s is currently locked by %s', repo, user)
2217 2217 currently_locked = True
2218 2218 else:
2219 2219 log.debug('Setting lock on repo %s by %s', repo, user)
2220 2220 make_lock = True
2221 2221
2222 2222 else:
2223 2223 log.debug('Repository %s do not have locking enabled', repo)
2224 2224
2225 2225 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2226 2226 make_lock, currently_locked, lock_info)
2227 2227
2228 2228 from rhodecode.lib.auth import HasRepoPermissionAny
2229 2229 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2230 2230 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2231 2231 # if we don't have at least write permission we cannot make a lock
2232 2232 log.debug('lock state reset back to FALSE due to lack '
2233 2233 'of at least read permission')
2234 2234 make_lock = False
2235 2235
2236 2236 return make_lock, currently_locked, lock_info
2237 2237
2238 2238 @property
2239 2239 def last_commit_cache_update_diff(self):
2240 2240 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2241 2241
2242 2242 @property
2243 2243 def last_commit_change(self):
2244 2244 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2245 2245 empty_date = datetime.datetime.fromtimestamp(0)
2246 2246 date_latest = self.changeset_cache.get('date', empty_date)
2247 2247 try:
2248 2248 return parse_datetime(date_latest)
2249 2249 except Exception:
2250 2250 return empty_date
2251 2251
2252 2252 @property
2253 2253 def last_db_change(self):
2254 2254 return self.updated_on
2255 2255
2256 2256 @property
2257 2257 def clone_uri_hidden(self):
2258 2258 clone_uri = self.clone_uri
2259 2259 if clone_uri:
2260 2260 import urlobject
2261 2261 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2262 2262 if url_obj.password:
2263 2263 clone_uri = url_obj.with_password('*****')
2264 2264 return clone_uri
2265 2265
2266 2266 @property
2267 2267 def push_uri_hidden(self):
2268 2268 push_uri = self.push_uri
2269 2269 if push_uri:
2270 2270 import urlobject
2271 2271 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2272 2272 if url_obj.password:
2273 2273 push_uri = url_obj.with_password('*****')
2274 2274 return push_uri
2275 2275
2276 2276 def clone_url(self, **override):
2277 2277 from rhodecode.model.settings import SettingsModel
2278 2278
2279 2279 uri_tmpl = None
2280 2280 if 'with_id' in override:
2281 2281 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2282 2282 del override['with_id']
2283 2283
2284 2284 if 'uri_tmpl' in override:
2285 2285 uri_tmpl = override['uri_tmpl']
2286 2286 del override['uri_tmpl']
2287 2287
2288 2288 ssh = False
2289 2289 if 'ssh' in override:
2290 2290 ssh = True
2291 2291 del override['ssh']
2292 2292
2293 2293 # we didn't override our tmpl from **overrides
2294 2294 request = get_current_request()
2295 2295 if not uri_tmpl:
2296 2296 if hasattr(request, 'call_context') and hasattr(request.call_context, 'rc_config'):
2297 2297 rc_config = request.call_context.rc_config
2298 2298 else:
2299 2299 rc_config = SettingsModel().get_all_settings(cache=True)
2300 2300 if ssh:
2301 2301 uri_tmpl = rc_config.get(
2302 2302 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2303 2303 else:
2304 2304 uri_tmpl = rc_config.get(
2305 2305 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2306 2306
2307 2307 return get_clone_url(request=request,
2308 2308 uri_tmpl=uri_tmpl,
2309 2309 repo_name=self.repo_name,
2310 2310 repo_id=self.repo_id, **override)
2311 2311
2312 2312 def set_state(self, state):
2313 2313 self.repo_state = state
2314 2314 Session().add(self)
2315 2315 #==========================================================================
2316 2316 # SCM PROPERTIES
2317 2317 #==========================================================================
2318 2318
2319 2319 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2320 2320 return get_commit_safe(
2321 2321 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2322 2322
2323 2323 def get_changeset(self, rev=None, pre_load=None):
2324 2324 warnings.warn("Use get_commit", DeprecationWarning)
2325 2325 commit_id = None
2326 2326 commit_idx = None
2327 2327 if isinstance(rev, compat.string_types):
2328 2328 commit_id = rev
2329 2329 else:
2330 2330 commit_idx = rev
2331 2331 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2332 2332 pre_load=pre_load)
2333 2333
2334 2334 def get_landing_commit(self):
2335 2335 """
2336 2336 Returns landing commit, or if that doesn't exist returns the tip
2337 2337 """
2338 2338 _rev_type, _rev = self.landing_rev
2339 2339 commit = self.get_commit(_rev)
2340 2340 if isinstance(commit, EmptyCommit):
2341 2341 return self.get_commit()
2342 2342 return commit
2343 2343
2344 2344 def flush_commit_cache(self):
2345 2345 self.update_commit_cache(cs_cache={'raw_id':'0'})
2346 2346 self.update_commit_cache()
2347 2347
2348 2348 def update_commit_cache(self, cs_cache=None, config=None):
2349 2349 """
2350 2350 Update cache of last commit for repository, keys should be::
2351 2351
2352 2352 source_repo_id
2353 2353 short_id
2354 2354 raw_id
2355 2355 revision
2356 2356 parents
2357 2357 message
2358 2358 date
2359 2359 author
2360 2360 updated_on
2361 2361
2362 2362 """
2363 2363 from rhodecode.lib.vcs.backends.base import BaseChangeset
2364 2364 if cs_cache is None:
2365 2365 # use no-cache version here
2366 2366 scm_repo = self.scm_instance(cache=False, config=config)
2367 2367
2368 2368 empty = scm_repo is None or scm_repo.is_empty()
2369 2369 if not empty:
2370 2370 cs_cache = scm_repo.get_commit(
2371 2371 pre_load=["author", "date", "message", "parents", "branch"])
2372 2372 else:
2373 2373 cs_cache = EmptyCommit()
2374 2374
2375 2375 if isinstance(cs_cache, BaseChangeset):
2376 2376 cs_cache = cs_cache.__json__()
2377 2377
2378 2378 def is_outdated(new_cs_cache):
2379 2379 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2380 2380 new_cs_cache['revision'] != self.changeset_cache['revision']):
2381 2381 return True
2382 2382 return False
2383 2383
2384 2384 # check if we have maybe already latest cached revision
2385 2385 if is_outdated(cs_cache) or not self.changeset_cache:
2386 2386 _default = datetime.datetime.utcnow()
2387 2387 last_change = cs_cache.get('date') or _default
2388 2388 # we check if last update is newer than the new value
2389 2389 # if yes, we use the current timestamp instead. Imagine you get
2390 2390 # old commit pushed 1y ago, we'd set last update 1y to ago.
2391 2391 last_change_timestamp = datetime_to_time(last_change)
2392 2392 current_timestamp = datetime_to_time(last_change)
2393 2393 if last_change_timestamp > current_timestamp:
2394 2394 cs_cache['date'] = _default
2395 2395
2396 2396 cs_cache['updated_on'] = time.time()
2397 2397 self.changeset_cache = cs_cache
2398 2398 self.updated_on = last_change
2399 2399 Session().add(self)
2400 2400 Session().commit()
2401 2401
2402 2402 log.debug('updated repo `%s` with new commit cache %s',
2403 2403 self.repo_name, cs_cache)
2404 2404 else:
2405 2405 cs_cache = self.changeset_cache
2406 2406 cs_cache['updated_on'] = time.time()
2407 2407 self.changeset_cache = cs_cache
2408 2408 Session().add(self)
2409 2409 Session().commit()
2410 2410
2411 2411 log.debug('Skipping update_commit_cache for repo:`%s` '
2412 2412 'commit already with latest changes', self.repo_name)
2413 2413
2414 2414 @property
2415 2415 def tip(self):
2416 2416 return self.get_commit('tip')
2417 2417
2418 2418 @property
2419 2419 def author(self):
2420 2420 return self.tip.author
2421 2421
2422 2422 @property
2423 2423 def last_change(self):
2424 2424 return self.scm_instance().last_change
2425 2425
2426 2426 def get_comments(self, revisions=None):
2427 2427 """
2428 2428 Returns comments for this repository grouped by revisions
2429 2429
2430 2430 :param revisions: filter query by revisions only
2431 2431 """
2432 2432 cmts = ChangesetComment.query()\
2433 2433 .filter(ChangesetComment.repo == self)
2434 2434 if revisions:
2435 2435 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2436 2436 grouped = collections.defaultdict(list)
2437 2437 for cmt in cmts.all():
2438 2438 grouped[cmt.revision].append(cmt)
2439 2439 return grouped
2440 2440
2441 2441 def statuses(self, revisions=None):
2442 2442 """
2443 2443 Returns statuses for this repository
2444 2444
2445 2445 :param revisions: list of revisions to get statuses for
2446 2446 """
2447 2447 statuses = ChangesetStatus.query()\
2448 2448 .filter(ChangesetStatus.repo == self)\
2449 2449 .filter(ChangesetStatus.version == 0)
2450 2450
2451 2451 if revisions:
2452 2452 # Try doing the filtering in chunks to avoid hitting limits
2453 2453 size = 500
2454 2454 status_results = []
2455 2455 for chunk in xrange(0, len(revisions), size):
2456 2456 status_results += statuses.filter(
2457 2457 ChangesetStatus.revision.in_(
2458 2458 revisions[chunk: chunk+size])
2459 2459 ).all()
2460 2460 else:
2461 2461 status_results = statuses.all()
2462 2462
2463 2463 grouped = {}
2464 2464
2465 2465 # maybe we have open new pullrequest without a status?
2466 2466 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2467 2467 status_lbl = ChangesetStatus.get_status_lbl(stat)
2468 2468 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2469 2469 for rev in pr.revisions:
2470 2470 pr_id = pr.pull_request_id
2471 2471 pr_repo = pr.target_repo.repo_name
2472 2472 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2473 2473
2474 2474 for stat in status_results:
2475 2475 pr_id = pr_repo = None
2476 2476 if stat.pull_request:
2477 2477 pr_id = stat.pull_request.pull_request_id
2478 2478 pr_repo = stat.pull_request.target_repo.repo_name
2479 2479 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2480 2480 pr_id, pr_repo]
2481 2481 return grouped
2482 2482
2483 2483 # ==========================================================================
2484 2484 # SCM CACHE INSTANCE
2485 2485 # ==========================================================================
2486 2486
2487 2487 def scm_instance(self, **kwargs):
2488 2488 import rhodecode
2489 2489
2490 2490 # Passing a config will not hit the cache currently only used
2491 2491 # for repo2dbmapper
2492 2492 config = kwargs.pop('config', None)
2493 2493 cache = kwargs.pop('cache', None)
2494 2494 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2495 2495 if vcs_full_cache is not None:
2496 2496 # allows override global config
2497 2497 full_cache = vcs_full_cache
2498 2498 else:
2499 2499 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2500 2500 # if cache is NOT defined use default global, else we have a full
2501 2501 # control over cache behaviour
2502 2502 if cache is None and full_cache and not config:
2503 2503 log.debug('Initializing pure cached instance for %s', self.repo_path)
2504 2504 return self._get_instance_cached()
2505 2505
2506 2506 # cache here is sent to the "vcs server"
2507 2507 return self._get_instance(cache=bool(cache), config=config)
2508 2508
2509 2509 def _get_instance_cached(self):
2510 2510 from rhodecode.lib import rc_cache
2511 2511
2512 2512 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2513 2513 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2514 2514 repo_id=self.repo_id)
2515 2515 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2516 2516
2517 2517 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2518 2518 def get_instance_cached(repo_id, context_id, _cache_state_uid):
2519 2519 return self._get_instance(repo_state_uid=_cache_state_uid)
2520 2520
2521 2521 # we must use thread scoped cache here,
2522 2522 # because each thread of gevent needs it's own not shared connection and cache
2523 2523 # we also alter `args` so the cache key is individual for every green thread.
2524 2524 inv_context_manager = rc_cache.InvalidationContext(
2525 2525 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2526 2526 thread_scoped=True)
2527 2527 with inv_context_manager as invalidation_context:
2528 2528 cache_state_uid = invalidation_context.cache_data['cache_state_uid']
2529 2529 args = (self.repo_id, inv_context_manager.cache_key, cache_state_uid)
2530 2530
2531 2531 # re-compute and store cache if we get invalidate signal
2532 2532 if invalidation_context.should_invalidate():
2533 2533 instance = get_instance_cached.refresh(*args)
2534 2534 else:
2535 2535 instance = get_instance_cached(*args)
2536 2536
2537 2537 log.debug('Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2538 2538 return instance
2539 2539
2540 2540 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2541 2541 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2542 2542 self.repo_type, self.repo_path, cache)
2543 2543 config = config or self._config
2544 2544 custom_wire = {
2545 2545 'cache': cache, # controls the vcs.remote cache
2546 2546 'repo_state_uid': repo_state_uid
2547 2547 }
2548 2548 repo = get_vcs_instance(
2549 2549 repo_path=safe_str(self.repo_full_path),
2550 2550 config=config,
2551 2551 with_wire=custom_wire,
2552 2552 create=False,
2553 2553 _vcs_alias=self.repo_type)
2554 2554 if repo is not None:
2555 2555 repo.count() # cache rebuild
2556 2556 return repo
2557 2557
2558 2558 def get_shadow_repository_path(self, workspace_id):
2559 2559 from rhodecode.lib.vcs.backends.base import BaseRepository
2560 2560 shadow_repo_path = BaseRepository._get_shadow_repository_path(
2561 2561 self.repo_full_path, self.repo_id, workspace_id)
2562 2562 return shadow_repo_path
2563 2563
2564 2564 def __json__(self):
2565 2565 return {'landing_rev': self.landing_rev}
2566 2566
2567 2567 def get_dict(self):
2568 2568
2569 2569 # Since we transformed `repo_name` to a hybrid property, we need to
2570 2570 # keep compatibility with the code which uses `repo_name` field.
2571 2571
2572 2572 result = super(Repository, self).get_dict()
2573 2573 result['repo_name'] = result.pop('_repo_name', None)
2574 2574 return result
2575 2575
2576 2576
2577 2577 class RepoGroup(Base, BaseModel):
2578 2578 __tablename__ = 'groups'
2579 2579 __table_args__ = (
2580 2580 UniqueConstraint('group_name', 'group_parent_id'),
2581 2581 base_table_args,
2582 2582 )
2583 2583 __mapper_args__ = {'order_by': 'group_name'}
2584 2584
2585 2585 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2586 2586
2587 2587 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2588 2588 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2589 2589 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2590 2590 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2591 2591 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2592 2592 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2593 2593 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2594 2594 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2595 2595 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2596 2596 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2597 2597 _changeset_cache = Column(
2598 2598 "changeset_cache", LargeBinary(), nullable=True) # JSON data
2599 2599
2600 2600 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2601 2601 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2602 2602 parent_group = relationship('RepoGroup', remote_side=group_id)
2603 2603 user = relationship('User')
2604 2604 integrations = relationship('Integration', cascade="all, delete-orphan")
2605 2605
2606 2606 # no cascade, set NULL
2607 2607 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_group_id==RepoGroup.group_id')
2608 2608
2609 2609 def __init__(self, group_name='', parent_group=None):
2610 2610 self.group_name = group_name
2611 2611 self.parent_group = parent_group
2612 2612
2613 2613 def __unicode__(self):
2614 2614 return u"<%s('id:%s:%s')>" % (
2615 2615 self.__class__.__name__, self.group_id, self.group_name)
2616 2616
2617 2617 @hybrid_property
2618 2618 def group_name(self):
2619 2619 return self._group_name
2620 2620
2621 2621 @group_name.setter
2622 2622 def group_name(self, value):
2623 2623 self._group_name = value
2624 2624 self.group_name_hash = self.hash_repo_group_name(value)
2625 2625
2626 2626 @hybrid_property
2627 2627 def changeset_cache(self):
2628 2628 from rhodecode.lib.vcs.backends.base import EmptyCommit
2629 2629 dummy = EmptyCommit().__json__()
2630 2630 if not self._changeset_cache:
2631 2631 dummy['source_repo_id'] = ''
2632 2632 return json.loads(json.dumps(dummy))
2633 2633
2634 2634 try:
2635 2635 return json.loads(self._changeset_cache)
2636 2636 except TypeError:
2637 2637 return dummy
2638 2638 except Exception:
2639 2639 log.error(traceback.format_exc())
2640 2640 return dummy
2641 2641
2642 2642 @changeset_cache.setter
2643 2643 def changeset_cache(self, val):
2644 2644 try:
2645 2645 self._changeset_cache = json.dumps(val)
2646 2646 except Exception:
2647 2647 log.error(traceback.format_exc())
2648 2648
2649 2649 @validates('group_parent_id')
2650 2650 def validate_group_parent_id(self, key, val):
2651 2651 """
2652 2652 Check cycle references for a parent group to self
2653 2653 """
2654 2654 if self.group_id and val:
2655 2655 assert val != self.group_id
2656 2656
2657 2657 return val
2658 2658
2659 2659 @hybrid_property
2660 2660 def description_safe(self):
2661 2661 from rhodecode.lib import helpers as h
2662 2662 return h.escape(self.group_description)
2663 2663
2664 2664 @classmethod
2665 2665 def hash_repo_group_name(cls, repo_group_name):
2666 2666 val = remove_formatting(repo_group_name)
2667 2667 val = safe_str(val).lower()
2668 2668 chars = []
2669 2669 for c in val:
2670 2670 if c not in string.ascii_letters:
2671 2671 c = str(ord(c))
2672 2672 chars.append(c)
2673 2673
2674 2674 return ''.join(chars)
2675 2675
2676 2676 @classmethod
2677 2677 def _generate_choice(cls, repo_group):
2678 2678 from webhelpers2.html import literal as _literal
2679 2679 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2680 2680 return repo_group.group_id, _name(repo_group.full_path_splitted)
2681 2681
2682 2682 @classmethod
2683 2683 def groups_choices(cls, groups=None, show_empty_group=True):
2684 2684 if not groups:
2685 2685 groups = cls.query().all()
2686 2686
2687 2687 repo_groups = []
2688 2688 if show_empty_group:
2689 2689 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2690 2690
2691 2691 repo_groups.extend([cls._generate_choice(x) for x in groups])
2692 2692
2693 2693 repo_groups = sorted(
2694 2694 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2695 2695 return repo_groups
2696 2696
2697 2697 @classmethod
2698 2698 def url_sep(cls):
2699 2699 return URL_SEP
2700 2700
2701 2701 @classmethod
2702 2702 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2703 2703 if case_insensitive:
2704 2704 gr = cls.query().filter(func.lower(cls.group_name)
2705 2705 == func.lower(group_name))
2706 2706 else:
2707 2707 gr = cls.query().filter(cls.group_name == group_name)
2708 2708 if cache:
2709 2709 name_key = _hash_key(group_name)
2710 2710 gr = gr.options(
2711 2711 FromCache("sql_cache_short", "get_group_%s" % name_key))
2712 2712 return gr.scalar()
2713 2713
2714 2714 @classmethod
2715 2715 def get_user_personal_repo_group(cls, user_id):
2716 2716 user = User.get(user_id)
2717 2717 if user.username == User.DEFAULT_USER:
2718 2718 return None
2719 2719
2720 2720 return cls.query()\
2721 2721 .filter(cls.personal == true()) \
2722 2722 .filter(cls.user == user) \
2723 2723 .order_by(cls.group_id.asc()) \
2724 2724 .first()
2725 2725
2726 2726 @classmethod
2727 2727 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2728 2728 case_insensitive=True):
2729 2729 q = RepoGroup.query()
2730 2730
2731 2731 if not isinstance(user_id, Optional):
2732 2732 q = q.filter(RepoGroup.user_id == user_id)
2733 2733
2734 2734 if not isinstance(group_id, Optional):
2735 2735 q = q.filter(RepoGroup.group_parent_id == group_id)
2736 2736
2737 2737 if case_insensitive:
2738 2738 q = q.order_by(func.lower(RepoGroup.group_name))
2739 2739 else:
2740 2740 q = q.order_by(RepoGroup.group_name)
2741 2741 return q.all()
2742 2742
2743 2743 @property
2744 2744 def parents(self, parents_recursion_limit = 10):
2745 2745 groups = []
2746 2746 if self.parent_group is None:
2747 2747 return groups
2748 2748 cur_gr = self.parent_group
2749 2749 groups.insert(0, cur_gr)
2750 2750 cnt = 0
2751 2751 while 1:
2752 2752 cnt += 1
2753 2753 gr = getattr(cur_gr, 'parent_group', None)
2754 2754 cur_gr = cur_gr.parent_group
2755 2755 if gr is None:
2756 2756 break
2757 2757 if cnt == parents_recursion_limit:
2758 2758 # this will prevent accidental infinit loops
2759 2759 log.error('more than %s parents found for group %s, stopping '
2760 2760 'recursive parent fetching', parents_recursion_limit, self)
2761 2761 break
2762 2762
2763 2763 groups.insert(0, gr)
2764 2764 return groups
2765 2765
2766 2766 @property
2767 2767 def last_commit_cache_update_diff(self):
2768 2768 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2769 2769
2770 2770 @property
2771 2771 def last_commit_change(self):
2772 2772 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2773 2773 empty_date = datetime.datetime.fromtimestamp(0)
2774 2774 date_latest = self.changeset_cache.get('date', empty_date)
2775 2775 try:
2776 2776 return parse_datetime(date_latest)
2777 2777 except Exception:
2778 2778 return empty_date
2779 2779
2780 2780 @property
2781 2781 def last_db_change(self):
2782 2782 return self.updated_on
2783 2783
2784 2784 @property
2785 2785 def children(self):
2786 2786 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2787 2787
2788 2788 @property
2789 2789 def name(self):
2790 2790 return self.group_name.split(RepoGroup.url_sep())[-1]
2791 2791
2792 2792 @property
2793 2793 def full_path(self):
2794 2794 return self.group_name
2795 2795
2796 2796 @property
2797 2797 def full_path_splitted(self):
2798 2798 return self.group_name.split(RepoGroup.url_sep())
2799 2799
2800 2800 @property
2801 2801 def repositories(self):
2802 2802 return Repository.query()\
2803 2803 .filter(Repository.group == self)\
2804 2804 .order_by(Repository.repo_name)
2805 2805
2806 2806 @property
2807 2807 def repositories_recursive_count(self):
2808 2808 cnt = self.repositories.count()
2809 2809
2810 2810 def children_count(group):
2811 2811 cnt = 0
2812 2812 for child in group.children:
2813 2813 cnt += child.repositories.count()
2814 2814 cnt += children_count(child)
2815 2815 return cnt
2816 2816
2817 2817 return cnt + children_count(self)
2818 2818
2819 2819 def _recursive_objects(self, include_repos=True, include_groups=True):
2820 2820 all_ = []
2821 2821
2822 2822 def _get_members(root_gr):
2823 2823 if include_repos:
2824 2824 for r in root_gr.repositories:
2825 2825 all_.append(r)
2826 2826 childs = root_gr.children.all()
2827 2827 if childs:
2828 2828 for gr in childs:
2829 2829 if include_groups:
2830 2830 all_.append(gr)
2831 2831 _get_members(gr)
2832 2832
2833 2833 root_group = []
2834 2834 if include_groups:
2835 2835 root_group = [self]
2836 2836
2837 2837 _get_members(self)
2838 2838 return root_group + all_
2839 2839
2840 2840 def recursive_groups_and_repos(self):
2841 2841 """
2842 2842 Recursive return all groups, with repositories in those groups
2843 2843 """
2844 2844 return self._recursive_objects()
2845 2845
2846 2846 def recursive_groups(self):
2847 2847 """
2848 2848 Returns all children groups for this group including children of children
2849 2849 """
2850 2850 return self._recursive_objects(include_repos=False)
2851 2851
2852 2852 def recursive_repos(self):
2853 2853 """
2854 2854 Returns all children repositories for this group
2855 2855 """
2856 2856 return self._recursive_objects(include_groups=False)
2857 2857
2858 2858 def get_new_name(self, group_name):
2859 2859 """
2860 2860 returns new full group name based on parent and new name
2861 2861
2862 2862 :param group_name:
2863 2863 """
2864 2864 path_prefix = (self.parent_group.full_path_splitted if
2865 2865 self.parent_group else [])
2866 2866 return RepoGroup.url_sep().join(path_prefix + [group_name])
2867 2867
2868 2868 def update_commit_cache(self, config=None):
2869 2869 """
2870 2870 Update cache of last changeset for newest repository inside this group, keys should be::
2871 2871
2872 2872 source_repo_id
2873 2873 short_id
2874 2874 raw_id
2875 2875 revision
2876 2876 parents
2877 2877 message
2878 2878 date
2879 2879 author
2880 2880
2881 2881 """
2882 2882 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2883 2883
2884 2884 def repo_groups_and_repos():
2885 2885 all_entries = OrderedDefaultDict(list)
2886 2886
2887 2887 def _get_members(root_gr, pos=0):
2888 2888
2889 2889 for repo in root_gr.repositories:
2890 2890 all_entries[root_gr].append(repo)
2891 2891
2892 2892 # fill in all parent positions
2893 2893 for parent_group in root_gr.parents:
2894 2894 all_entries[parent_group].extend(all_entries[root_gr])
2895 2895
2896 2896 children_groups = root_gr.children.all()
2897 2897 if children_groups:
2898 2898 for cnt, gr in enumerate(children_groups, 1):
2899 2899 _get_members(gr, pos=pos+cnt)
2900 2900
2901 2901 _get_members(root_gr=self)
2902 2902 return all_entries
2903 2903
2904 2904 empty_date = datetime.datetime.fromtimestamp(0)
2905 2905 for repo_group, repos in repo_groups_and_repos().items():
2906 2906
2907 2907 latest_repo_cs_cache = {}
2908 2908 _date_latest = empty_date
2909 2909 for repo in repos:
2910 2910 repo_cs_cache = repo.changeset_cache
2911 2911 date_latest = latest_repo_cs_cache.get('date', empty_date)
2912 2912 date_current = repo_cs_cache.get('date', empty_date)
2913 2913 current_timestamp = datetime_to_time(parse_datetime(date_latest))
2914 2914 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
2915 2915 latest_repo_cs_cache = repo_cs_cache
2916 2916 latest_repo_cs_cache['source_repo_id'] = repo.repo_id
2917 2917 _date_latest = parse_datetime(latest_repo_cs_cache['date'])
2918 2918
2919 2919 latest_repo_cs_cache['updated_on'] = time.time()
2920 2920 repo_group.changeset_cache = latest_repo_cs_cache
2921 2921 repo_group.updated_on = _date_latest
2922 2922 Session().add(repo_group)
2923 2923 Session().commit()
2924 2924
2925 2925 log.debug('updated repo group `%s` with new commit cache %s',
2926 2926 repo_group.group_name, latest_repo_cs_cache)
2927 2927
2928 2928 def permissions(self, with_admins=True, with_owner=True,
2929 2929 expand_from_user_groups=False):
2930 2930 """
2931 2931 Permissions for repository groups
2932 2932 """
2933 2933 _admin_perm = 'group.admin'
2934 2934
2935 2935 owner_row = []
2936 2936 if with_owner:
2937 2937 usr = AttributeDict(self.user.get_dict())
2938 2938 usr.owner_row = True
2939 2939 usr.permission = _admin_perm
2940 2940 owner_row.append(usr)
2941 2941
2942 2942 super_admin_ids = []
2943 2943 super_admin_rows = []
2944 2944 if with_admins:
2945 2945 for usr in User.get_all_super_admins():
2946 2946 super_admin_ids.append(usr.user_id)
2947 2947 # if this admin is also owner, don't double the record
2948 2948 if usr.user_id == owner_row[0].user_id:
2949 2949 owner_row[0].admin_row = True
2950 2950 else:
2951 2951 usr = AttributeDict(usr.get_dict())
2952 2952 usr.admin_row = True
2953 2953 usr.permission = _admin_perm
2954 2954 super_admin_rows.append(usr)
2955 2955
2956 2956 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2957 2957 q = q.options(joinedload(UserRepoGroupToPerm.group),
2958 2958 joinedload(UserRepoGroupToPerm.user),
2959 2959 joinedload(UserRepoGroupToPerm.permission),)
2960 2960
2961 2961 # get owners and admins and permissions. We do a trick of re-writing
2962 2962 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2963 2963 # has a global reference and changing one object propagates to all
2964 2964 # others. This means if admin is also an owner admin_row that change
2965 2965 # would propagate to both objects
2966 2966 perm_rows = []
2967 2967 for _usr in q.all():
2968 2968 usr = AttributeDict(_usr.user.get_dict())
2969 2969 # if this user is also owner/admin, mark as duplicate record
2970 2970 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2971 2971 usr.duplicate_perm = True
2972 2972 usr.permission = _usr.permission.permission_name
2973 2973 perm_rows.append(usr)
2974 2974
2975 2975 # filter the perm rows by 'default' first and then sort them by
2976 2976 # admin,write,read,none permissions sorted again alphabetically in
2977 2977 # each group
2978 2978 perm_rows = sorted(perm_rows, key=display_user_sort)
2979 2979
2980 2980 user_groups_rows = []
2981 2981 if expand_from_user_groups:
2982 2982 for ug in self.permission_user_groups(with_members=True):
2983 2983 for user_data in ug.members:
2984 2984 user_groups_rows.append(user_data)
2985 2985
2986 2986 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2987 2987
2988 2988 def permission_user_groups(self, with_members=False):
2989 2989 q = UserGroupRepoGroupToPerm.query()\
2990 2990 .filter(UserGroupRepoGroupToPerm.group == self)
2991 2991 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2992 2992 joinedload(UserGroupRepoGroupToPerm.users_group),
2993 2993 joinedload(UserGroupRepoGroupToPerm.permission),)
2994 2994
2995 2995 perm_rows = []
2996 2996 for _user_group in q.all():
2997 2997 entry = AttributeDict(_user_group.users_group.get_dict())
2998 2998 entry.permission = _user_group.permission.permission_name
2999 2999 if with_members:
3000 3000 entry.members = [x.user.get_dict()
3001 3001 for x in _user_group.users_group.members]
3002 3002 perm_rows.append(entry)
3003 3003
3004 3004 perm_rows = sorted(perm_rows, key=display_user_group_sort)
3005 3005 return perm_rows
3006 3006
3007 3007 def get_api_data(self):
3008 3008 """
3009 3009 Common function for generating api data
3010 3010
3011 3011 """
3012 3012 group = self
3013 3013 data = {
3014 3014 'group_id': group.group_id,
3015 3015 'group_name': group.group_name,
3016 3016 'group_description': group.description_safe,
3017 3017 'parent_group': group.parent_group.group_name if group.parent_group else None,
3018 3018 'repositories': [x.repo_name for x in group.repositories],
3019 3019 'owner': group.user.username,
3020 3020 }
3021 3021 return data
3022 3022
3023 3023 def get_dict(self):
3024 3024 # Since we transformed `group_name` to a hybrid property, we need to
3025 3025 # keep compatibility with the code which uses `group_name` field.
3026 3026 result = super(RepoGroup, self).get_dict()
3027 3027 result['group_name'] = result.pop('_group_name', None)
3028 3028 return result
3029 3029
3030 3030
3031 3031 class Permission(Base, BaseModel):
3032 3032 __tablename__ = 'permissions'
3033 3033 __table_args__ = (
3034 3034 Index('p_perm_name_idx', 'permission_name'),
3035 3035 base_table_args,
3036 3036 )
3037 3037
3038 3038 PERMS = [
3039 3039 ('hg.admin', _('RhodeCode Super Administrator')),
3040 3040
3041 3041 ('repository.none', _('Repository no access')),
3042 3042 ('repository.read', _('Repository read access')),
3043 3043 ('repository.write', _('Repository write access')),
3044 3044 ('repository.admin', _('Repository admin access')),
3045 3045
3046 3046 ('group.none', _('Repository group no access')),
3047 3047 ('group.read', _('Repository group read access')),
3048 3048 ('group.write', _('Repository group write access')),
3049 3049 ('group.admin', _('Repository group admin access')),
3050 3050
3051 3051 ('usergroup.none', _('User group no access')),
3052 3052 ('usergroup.read', _('User group read access')),
3053 3053 ('usergroup.write', _('User group write access')),
3054 3054 ('usergroup.admin', _('User group admin access')),
3055 3055
3056 3056 ('branch.none', _('Branch no permissions')),
3057 3057 ('branch.merge', _('Branch access by web merge')),
3058 3058 ('branch.push', _('Branch access by push')),
3059 3059 ('branch.push_force', _('Branch access by push with force')),
3060 3060
3061 3061 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
3062 3062 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
3063 3063
3064 3064 ('hg.usergroup.create.false', _('User Group creation disabled')),
3065 3065 ('hg.usergroup.create.true', _('User Group creation enabled')),
3066 3066
3067 3067 ('hg.create.none', _('Repository creation disabled')),
3068 3068 ('hg.create.repository', _('Repository creation enabled')),
3069 3069 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3070 3070 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3071 3071
3072 3072 ('hg.fork.none', _('Repository forking disabled')),
3073 3073 ('hg.fork.repository', _('Repository forking enabled')),
3074 3074
3075 3075 ('hg.register.none', _('Registration disabled')),
3076 3076 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3077 3077 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3078 3078
3079 3079 ('hg.password_reset.enabled', _('Password reset enabled')),
3080 3080 ('hg.password_reset.hidden', _('Password reset hidden')),
3081 3081 ('hg.password_reset.disabled', _('Password reset disabled')),
3082 3082
3083 3083 ('hg.extern_activate.manual', _('Manual activation of external account')),
3084 3084 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3085 3085
3086 3086 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3087 3087 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3088 3088 ]
3089 3089
3090 3090 # definition of system default permissions for DEFAULT user, created on
3091 3091 # system setup
3092 3092 DEFAULT_USER_PERMISSIONS = [
3093 3093 # object perms
3094 3094 'repository.read',
3095 3095 'group.read',
3096 3096 'usergroup.read',
3097 3097 # branch, for backward compat we need same value as before so forced pushed
3098 3098 'branch.push_force',
3099 3099 # global
3100 3100 'hg.create.repository',
3101 3101 'hg.repogroup.create.false',
3102 3102 'hg.usergroup.create.false',
3103 3103 'hg.create.write_on_repogroup.true',
3104 3104 'hg.fork.repository',
3105 3105 'hg.register.manual_activate',
3106 3106 'hg.password_reset.enabled',
3107 3107 'hg.extern_activate.auto',
3108 3108 'hg.inherit_default_perms.true',
3109 3109 ]
3110 3110
3111 3111 # defines which permissions are more important higher the more important
3112 3112 # Weight defines which permissions are more important.
3113 3113 # The higher number the more important.
3114 3114 PERM_WEIGHTS = {
3115 3115 'repository.none': 0,
3116 3116 'repository.read': 1,
3117 3117 'repository.write': 3,
3118 3118 'repository.admin': 4,
3119 3119
3120 3120 'group.none': 0,
3121 3121 'group.read': 1,
3122 3122 'group.write': 3,
3123 3123 'group.admin': 4,
3124 3124
3125 3125 'usergroup.none': 0,
3126 3126 'usergroup.read': 1,
3127 3127 'usergroup.write': 3,
3128 3128 'usergroup.admin': 4,
3129 3129
3130 3130 'branch.none': 0,
3131 3131 'branch.merge': 1,
3132 3132 'branch.push': 3,
3133 3133 'branch.push_force': 4,
3134 3134
3135 3135 'hg.repogroup.create.false': 0,
3136 3136 'hg.repogroup.create.true': 1,
3137 3137
3138 3138 'hg.usergroup.create.false': 0,
3139 3139 'hg.usergroup.create.true': 1,
3140 3140
3141 3141 'hg.fork.none': 0,
3142 3142 'hg.fork.repository': 1,
3143 3143 'hg.create.none': 0,
3144 3144 'hg.create.repository': 1
3145 3145 }
3146 3146
3147 3147 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3148 3148 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3149 3149 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3150 3150
3151 3151 def __unicode__(self):
3152 3152 return u"<%s('%s:%s')>" % (
3153 3153 self.__class__.__name__, self.permission_id, self.permission_name
3154 3154 )
3155 3155
3156 3156 @classmethod
3157 3157 def get_by_key(cls, key):
3158 3158 return cls.query().filter(cls.permission_name == key).scalar()
3159 3159
3160 3160 @classmethod
3161 3161 def get_default_repo_perms(cls, user_id, repo_id=None):
3162 3162 q = Session().query(UserRepoToPerm, Repository, Permission)\
3163 3163 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3164 3164 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3165 3165 .filter(UserRepoToPerm.user_id == user_id)
3166 3166 if repo_id:
3167 3167 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3168 3168 return q.all()
3169 3169
3170 3170 @classmethod
3171 3171 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3172 3172 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3173 3173 .join(
3174 3174 Permission,
3175 3175 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3176 3176 .join(
3177 3177 UserRepoToPerm,
3178 3178 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3179 3179 .filter(UserRepoToPerm.user_id == user_id)
3180 3180
3181 3181 if repo_id:
3182 3182 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3183 3183 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3184 3184
3185 3185 @classmethod
3186 3186 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3187 3187 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3188 3188 .join(
3189 3189 Permission,
3190 3190 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3191 3191 .join(
3192 3192 Repository,
3193 3193 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3194 3194 .join(
3195 3195 UserGroup,
3196 3196 UserGroupRepoToPerm.users_group_id ==
3197 3197 UserGroup.users_group_id)\
3198 3198 .join(
3199 3199 UserGroupMember,
3200 3200 UserGroupRepoToPerm.users_group_id ==
3201 3201 UserGroupMember.users_group_id)\
3202 3202 .filter(
3203 3203 UserGroupMember.user_id == user_id,
3204 3204 UserGroup.users_group_active == true())
3205 3205 if repo_id:
3206 3206 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3207 3207 return q.all()
3208 3208
3209 3209 @classmethod
3210 3210 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3211 3211 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3212 3212 .join(
3213 3213 Permission,
3214 3214 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3215 3215 .join(
3216 3216 UserGroupRepoToPerm,
3217 3217 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3218 3218 .join(
3219 3219 UserGroup,
3220 3220 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3221 3221 .join(
3222 3222 UserGroupMember,
3223 3223 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3224 3224 .filter(
3225 3225 UserGroupMember.user_id == user_id,
3226 3226 UserGroup.users_group_active == true())
3227 3227
3228 3228 if repo_id:
3229 3229 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3230 3230 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3231 3231
3232 3232 @classmethod
3233 3233 def get_default_group_perms(cls, user_id, repo_group_id=None):
3234 3234 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3235 3235 .join(
3236 3236 Permission,
3237 3237 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3238 3238 .join(
3239 3239 RepoGroup,
3240 3240 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3241 3241 .filter(UserRepoGroupToPerm.user_id == user_id)
3242 3242 if repo_group_id:
3243 3243 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3244 3244 return q.all()
3245 3245
3246 3246 @classmethod
3247 3247 def get_default_group_perms_from_user_group(
3248 3248 cls, user_id, repo_group_id=None):
3249 3249 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3250 3250 .join(
3251 3251 Permission,
3252 3252 UserGroupRepoGroupToPerm.permission_id ==
3253 3253 Permission.permission_id)\
3254 3254 .join(
3255 3255 RepoGroup,
3256 3256 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3257 3257 .join(
3258 3258 UserGroup,
3259 3259 UserGroupRepoGroupToPerm.users_group_id ==
3260 3260 UserGroup.users_group_id)\
3261 3261 .join(
3262 3262 UserGroupMember,
3263 3263 UserGroupRepoGroupToPerm.users_group_id ==
3264 3264 UserGroupMember.users_group_id)\
3265 3265 .filter(
3266 3266 UserGroupMember.user_id == user_id,
3267 3267 UserGroup.users_group_active == true())
3268 3268 if repo_group_id:
3269 3269 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3270 3270 return q.all()
3271 3271
3272 3272 @classmethod
3273 3273 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3274 3274 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3275 3275 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3276 3276 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3277 3277 .filter(UserUserGroupToPerm.user_id == user_id)
3278 3278 if user_group_id:
3279 3279 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3280 3280 return q.all()
3281 3281
3282 3282 @classmethod
3283 3283 def get_default_user_group_perms_from_user_group(
3284 3284 cls, user_id, user_group_id=None):
3285 3285 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3286 3286 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3287 3287 .join(
3288 3288 Permission,
3289 3289 UserGroupUserGroupToPerm.permission_id ==
3290 3290 Permission.permission_id)\
3291 3291 .join(
3292 3292 TargetUserGroup,
3293 3293 UserGroupUserGroupToPerm.target_user_group_id ==
3294 3294 TargetUserGroup.users_group_id)\
3295 3295 .join(
3296 3296 UserGroup,
3297 3297 UserGroupUserGroupToPerm.user_group_id ==
3298 3298 UserGroup.users_group_id)\
3299 3299 .join(
3300 3300 UserGroupMember,
3301 3301 UserGroupUserGroupToPerm.user_group_id ==
3302 3302 UserGroupMember.users_group_id)\
3303 3303 .filter(
3304 3304 UserGroupMember.user_id == user_id,
3305 3305 UserGroup.users_group_active == true())
3306 3306 if user_group_id:
3307 3307 q = q.filter(
3308 3308 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3309 3309
3310 3310 return q.all()
3311 3311
3312 3312
3313 3313 class UserRepoToPerm(Base, BaseModel):
3314 3314 __tablename__ = 'repo_to_perm'
3315 3315 __table_args__ = (
3316 3316 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3317 3317 base_table_args
3318 3318 )
3319 3319
3320 3320 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3321 3321 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3322 3322 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3323 3323 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3324 3324
3325 3325 user = relationship('User')
3326 3326 repository = relationship('Repository')
3327 3327 permission = relationship('Permission')
3328 3328
3329 3329 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete-orphan", lazy='joined')
3330 3330
3331 3331 @classmethod
3332 3332 def create(cls, user, repository, permission):
3333 3333 n = cls()
3334 3334 n.user = user
3335 3335 n.repository = repository
3336 3336 n.permission = permission
3337 3337 Session().add(n)
3338 3338 return n
3339 3339
3340 3340 def __unicode__(self):
3341 3341 return u'<%s => %s >' % (self.user, self.repository)
3342 3342
3343 3343
3344 3344 class UserUserGroupToPerm(Base, BaseModel):
3345 3345 __tablename__ = 'user_user_group_to_perm'
3346 3346 __table_args__ = (
3347 3347 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3348 3348 base_table_args
3349 3349 )
3350 3350
3351 3351 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3352 3352 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3353 3353 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3354 3354 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3355 3355
3356 3356 user = relationship('User')
3357 3357 user_group = relationship('UserGroup')
3358 3358 permission = relationship('Permission')
3359 3359
3360 3360 @classmethod
3361 3361 def create(cls, user, user_group, permission):
3362 3362 n = cls()
3363 3363 n.user = user
3364 3364 n.user_group = user_group
3365 3365 n.permission = permission
3366 3366 Session().add(n)
3367 3367 return n
3368 3368
3369 3369 def __unicode__(self):
3370 3370 return u'<%s => %s >' % (self.user, self.user_group)
3371 3371
3372 3372
3373 3373 class UserToPerm(Base, BaseModel):
3374 3374 __tablename__ = 'user_to_perm'
3375 3375 __table_args__ = (
3376 3376 UniqueConstraint('user_id', 'permission_id'),
3377 3377 base_table_args
3378 3378 )
3379 3379
3380 3380 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3381 3381 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3382 3382 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3383 3383
3384 3384 user = relationship('User')
3385 3385 permission = relationship('Permission', lazy='joined')
3386 3386
3387 3387 def __unicode__(self):
3388 3388 return u'<%s => %s >' % (self.user, self.permission)
3389 3389
3390 3390
3391 3391 class UserGroupRepoToPerm(Base, BaseModel):
3392 3392 __tablename__ = 'users_group_repo_to_perm'
3393 3393 __table_args__ = (
3394 3394 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3395 3395 base_table_args
3396 3396 )
3397 3397
3398 3398 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3399 3399 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3400 3400 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3401 3401 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3402 3402
3403 3403 users_group = relationship('UserGroup')
3404 3404 permission = relationship('Permission')
3405 3405 repository = relationship('Repository')
3406 3406 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3407 3407
3408 3408 @classmethod
3409 3409 def create(cls, users_group, repository, permission):
3410 3410 n = cls()
3411 3411 n.users_group = users_group
3412 3412 n.repository = repository
3413 3413 n.permission = permission
3414 3414 Session().add(n)
3415 3415 return n
3416 3416
3417 3417 def __unicode__(self):
3418 3418 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3419 3419
3420 3420
3421 3421 class UserGroupUserGroupToPerm(Base, BaseModel):
3422 3422 __tablename__ = 'user_group_user_group_to_perm'
3423 3423 __table_args__ = (
3424 3424 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3425 3425 CheckConstraint('target_user_group_id != user_group_id'),
3426 3426 base_table_args
3427 3427 )
3428 3428
3429 3429 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)
3430 3430 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3431 3431 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3432 3432 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3433 3433
3434 3434 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3435 3435 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3436 3436 permission = relationship('Permission')
3437 3437
3438 3438 @classmethod
3439 3439 def create(cls, target_user_group, user_group, permission):
3440 3440 n = cls()
3441 3441 n.target_user_group = target_user_group
3442 3442 n.user_group = user_group
3443 3443 n.permission = permission
3444 3444 Session().add(n)
3445 3445 return n
3446 3446
3447 3447 def __unicode__(self):
3448 3448 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3449 3449
3450 3450
3451 3451 class UserGroupToPerm(Base, BaseModel):
3452 3452 __tablename__ = 'users_group_to_perm'
3453 3453 __table_args__ = (
3454 3454 UniqueConstraint('users_group_id', 'permission_id',),
3455 3455 base_table_args
3456 3456 )
3457 3457
3458 3458 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3459 3459 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3460 3460 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3461 3461
3462 3462 users_group = relationship('UserGroup')
3463 3463 permission = relationship('Permission')
3464 3464
3465 3465
3466 3466 class UserRepoGroupToPerm(Base, BaseModel):
3467 3467 __tablename__ = 'user_repo_group_to_perm'
3468 3468 __table_args__ = (
3469 3469 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3470 3470 base_table_args
3471 3471 )
3472 3472
3473 3473 group_to_perm_id = Column("group_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 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3476 3476 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3477 3477
3478 3478 user = relationship('User')
3479 3479 group = relationship('RepoGroup')
3480 3480 permission = relationship('Permission')
3481 3481
3482 3482 @classmethod
3483 3483 def create(cls, user, repository_group, permission):
3484 3484 n = cls()
3485 3485 n.user = user
3486 3486 n.group = repository_group
3487 3487 n.permission = permission
3488 3488 Session().add(n)
3489 3489 return n
3490 3490
3491 3491
3492 3492 class UserGroupRepoGroupToPerm(Base, BaseModel):
3493 3493 __tablename__ = 'users_group_repo_group_to_perm'
3494 3494 __table_args__ = (
3495 3495 UniqueConstraint('users_group_id', 'group_id'),
3496 3496 base_table_args
3497 3497 )
3498 3498
3499 3499 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)
3500 3500 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3501 3501 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3502 3502 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3503 3503
3504 3504 users_group = relationship('UserGroup')
3505 3505 permission = relationship('Permission')
3506 3506 group = relationship('RepoGroup')
3507 3507
3508 3508 @classmethod
3509 3509 def create(cls, user_group, repository_group, permission):
3510 3510 n = cls()
3511 3511 n.users_group = user_group
3512 3512 n.group = repository_group
3513 3513 n.permission = permission
3514 3514 Session().add(n)
3515 3515 return n
3516 3516
3517 3517 def __unicode__(self):
3518 3518 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3519 3519
3520 3520
3521 3521 class Statistics(Base, BaseModel):
3522 3522 __tablename__ = 'statistics'
3523 3523 __table_args__ = (
3524 3524 base_table_args
3525 3525 )
3526 3526
3527 3527 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3528 3528 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3529 3529 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3530 3530 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3531 3531 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3532 3532 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3533 3533
3534 3534 repository = relationship('Repository', single_parent=True)
3535 3535
3536 3536
3537 3537 class UserFollowing(Base, BaseModel):
3538 3538 __tablename__ = 'user_followings'
3539 3539 __table_args__ = (
3540 3540 UniqueConstraint('user_id', 'follows_repository_id'),
3541 3541 UniqueConstraint('user_id', 'follows_user_id'),
3542 3542 base_table_args
3543 3543 )
3544 3544
3545 3545 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3546 3546 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3547 3547 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3548 3548 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3549 3549 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3550 3550
3551 3551 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3552 3552
3553 3553 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3554 3554 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3555 3555
3556 3556 @classmethod
3557 3557 def get_repo_followers(cls, repo_id):
3558 3558 return cls.query().filter(cls.follows_repo_id == repo_id)
3559 3559
3560 3560
3561 3561 class CacheKey(Base, BaseModel):
3562 3562 __tablename__ = 'cache_invalidation'
3563 3563 __table_args__ = (
3564 3564 UniqueConstraint('cache_key'),
3565 3565 Index('key_idx', 'cache_key'),
3566 3566 base_table_args,
3567 3567 )
3568 3568
3569 3569 CACHE_TYPE_FEED = 'FEED'
3570 3570
3571 3571 # namespaces used to register process/thread aware caches
3572 3572 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3573 3573 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3574 3574
3575 3575 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3576 3576 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3577 3577 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3578 3578 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3579 3579 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3580 3580
3581 3581 def __init__(self, cache_key, cache_args='', cache_state_uid=None):
3582 3582 self.cache_key = cache_key
3583 3583 self.cache_args = cache_args
3584 3584 self.cache_active = False
3585 3585 # first key should be same for all entries, since all workers should share it
3586 3586 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid()
3587 3587
3588 3588 def __unicode__(self):
3589 3589 return u"<%s('%s:%s[%s]')>" % (
3590 3590 self.__class__.__name__,
3591 3591 self.cache_id, self.cache_key, self.cache_active)
3592 3592
3593 3593 def _cache_key_partition(self):
3594 3594 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3595 3595 return prefix, repo_name, suffix
3596 3596
3597 3597 def get_prefix(self):
3598 3598 """
3599 3599 Try to extract prefix from existing cache key. The key could consist
3600 3600 of prefix, repo_name, suffix
3601 3601 """
3602 3602 # this returns prefix, repo_name, suffix
3603 3603 return self._cache_key_partition()[0]
3604 3604
3605 3605 def get_suffix(self):
3606 3606 """
3607 3607 get suffix that might have been used in _get_cache_key to
3608 3608 generate self.cache_key. Only used for informational purposes
3609 3609 in repo_edit.mako.
3610 3610 """
3611 3611 # prefix, repo_name, suffix
3612 3612 return self._cache_key_partition()[2]
3613 3613
3614 3614 @classmethod
3615 3615 def generate_new_state_uid(cls, based_on=None):
3616 3616 if based_on:
3617 3617 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3618 3618 else:
3619 3619 return str(uuid.uuid4())
3620 3620
3621 3621 @classmethod
3622 3622 def delete_all_cache(cls):
3623 3623 """
3624 3624 Delete all cache keys from database.
3625 3625 Should only be run when all instances are down and all entries
3626 3626 thus stale.
3627 3627 """
3628 3628 cls.query().delete()
3629 3629 Session().commit()
3630 3630
3631 3631 @classmethod
3632 3632 def set_invalidate(cls, cache_uid, delete=False):
3633 3633 """
3634 3634 Mark all caches of a repo as invalid in the database.
3635 3635 """
3636 3636
3637 3637 try:
3638 3638 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3639 3639 if delete:
3640 3640 qry.delete()
3641 3641 log.debug('cache objects deleted for cache args %s',
3642 3642 safe_str(cache_uid))
3643 3643 else:
3644 3644 qry.update({"cache_active": False,
3645 3645 "cache_state_uid": cls.generate_new_state_uid()})
3646 3646 log.debug('cache objects marked as invalid for cache args %s',
3647 3647 safe_str(cache_uid))
3648 3648
3649 3649 Session().commit()
3650 3650 except Exception:
3651 3651 log.exception(
3652 3652 'Cache key invalidation failed for cache args %s',
3653 3653 safe_str(cache_uid))
3654 3654 Session().rollback()
3655 3655
3656 3656 @classmethod
3657 3657 def get_active_cache(cls, cache_key):
3658 3658 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3659 3659 if inv_obj:
3660 3660 return inv_obj
3661 3661 return None
3662 3662
3663 3663 @classmethod
3664 3664 def get_namespace_map(cls, namespace):
3665 3665 return {
3666 3666 x.cache_key: x
3667 3667 for x in cls.query().filter(cls.cache_args == namespace)}
3668 3668
3669 3669
3670 3670 class ChangesetComment(Base, BaseModel):
3671 3671 __tablename__ = 'changeset_comments'
3672 3672 __table_args__ = (
3673 3673 Index('cc_revision_idx', 'revision'),
3674 3674 base_table_args,
3675 3675 )
3676 3676
3677 3677 COMMENT_OUTDATED = u'comment_outdated'
3678 3678 COMMENT_TYPE_NOTE = u'note'
3679 3679 COMMENT_TYPE_TODO = u'todo'
3680 3680 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3681 3681
3682 3682 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3683 3683 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3684 3684 revision = Column('revision', String(40), nullable=True)
3685 3685 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3686 3686 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3687 3687 line_no = Column('line_no', Unicode(10), nullable=True)
3688 3688 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3689 3689 f_path = Column('f_path', Unicode(1000), nullable=True)
3690 3690 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3691 3691 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3692 3692 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3693 3693 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3694 3694 renderer = Column('renderer', Unicode(64), nullable=True)
3695 3695 display_state = Column('display_state', Unicode(128), nullable=True)
3696 3696
3697 3697 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3698 3698 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3699 3699
3700 3700 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3701 3701 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3702 3702
3703 3703 author = relationship('User', lazy='joined')
3704 3704 repo = relationship('Repository')
3705 3705 status_change = relationship('ChangesetStatus', cascade="all, delete-orphan", lazy='joined')
3706 3706 pull_request = relationship('PullRequest', lazy='joined')
3707 3707 pull_request_version = relationship('PullRequestVersion')
3708 3708
3709 3709 @classmethod
3710 3710 def get_users(cls, revision=None, pull_request_id=None):
3711 3711 """
3712 3712 Returns user associated with this ChangesetComment. ie those
3713 3713 who actually commented
3714 3714
3715 3715 :param cls:
3716 3716 :param revision:
3717 3717 """
3718 3718 q = Session().query(User)\
3719 3719 .join(ChangesetComment.author)
3720 3720 if revision:
3721 3721 q = q.filter(cls.revision == revision)
3722 3722 elif pull_request_id:
3723 3723 q = q.filter(cls.pull_request_id == pull_request_id)
3724 3724 return q.all()
3725 3725
3726 3726 @classmethod
3727 3727 def get_index_from_version(cls, pr_version, versions):
3728 3728 num_versions = [x.pull_request_version_id for x in versions]
3729 3729 try:
3730 3730 return num_versions.index(pr_version) +1
3731 3731 except (IndexError, ValueError):
3732 3732 return
3733 3733
3734 3734 @property
3735 3735 def outdated(self):
3736 3736 return self.display_state == self.COMMENT_OUTDATED
3737 3737
3738 3738 def outdated_at_version(self, version):
3739 3739 """
3740 3740 Checks if comment is outdated for given pull request version
3741 3741 """
3742 3742 return self.outdated and self.pull_request_version_id != version
3743 3743
3744 3744 def older_than_version(self, version):
3745 3745 """
3746 3746 Checks if comment is made from previous version than given
3747 3747 """
3748 3748 if version is None:
3749 3749 return self.pull_request_version_id is not None
3750 3750
3751 3751 return self.pull_request_version_id < version
3752 3752
3753 3753 @property
3754 3754 def resolved(self):
3755 3755 return self.resolved_by[0] if self.resolved_by else None
3756 3756
3757 3757 @property
3758 3758 def is_todo(self):
3759 3759 return self.comment_type == self.COMMENT_TYPE_TODO
3760 3760
3761 3761 @property
3762 3762 def is_inline(self):
3763 3763 return self.line_no and self.f_path
3764 3764
3765 3765 def get_index_version(self, versions):
3766 3766 return self.get_index_from_version(
3767 3767 self.pull_request_version_id, versions)
3768 3768
3769 3769 def __repr__(self):
3770 3770 if self.comment_id:
3771 3771 return '<DB:Comment #%s>' % self.comment_id
3772 3772 else:
3773 3773 return '<DB:Comment at %#x>' % id(self)
3774 3774
3775 3775 def get_api_data(self):
3776 3776 comment = self
3777 3777 data = {
3778 3778 'comment_id': comment.comment_id,
3779 3779 'comment_type': comment.comment_type,
3780 3780 'comment_text': comment.text,
3781 3781 'comment_status': comment.status_change,
3782 3782 'comment_f_path': comment.f_path,
3783 3783 'comment_lineno': comment.line_no,
3784 3784 'comment_author': comment.author,
3785 3785 'comment_created_on': comment.created_on,
3786 3786 'comment_resolved_by': self.resolved
3787 3787 }
3788 3788 return data
3789 3789
3790 3790 def __json__(self):
3791 3791 data = dict()
3792 3792 data.update(self.get_api_data())
3793 3793 return data
3794 3794
3795 3795
3796 3796 class ChangesetStatus(Base, BaseModel):
3797 3797 __tablename__ = 'changeset_statuses'
3798 3798 __table_args__ = (
3799 3799 Index('cs_revision_idx', 'revision'),
3800 3800 Index('cs_version_idx', 'version'),
3801 3801 UniqueConstraint('repo_id', 'revision', 'version'),
3802 3802 base_table_args
3803 3803 )
3804 3804
3805 3805 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3806 3806 STATUS_APPROVED = 'approved'
3807 3807 STATUS_REJECTED = 'rejected'
3808 3808 STATUS_UNDER_REVIEW = 'under_review'
3809 3809
3810 3810 STATUSES = [
3811 3811 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3812 3812 (STATUS_APPROVED, _("Approved")),
3813 3813 (STATUS_REJECTED, _("Rejected")),
3814 3814 (STATUS_UNDER_REVIEW, _("Under Review")),
3815 3815 ]
3816 3816
3817 3817 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3818 3818 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3819 3819 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3820 3820 revision = Column('revision', String(40), nullable=False)
3821 3821 status = Column('status', String(128), nullable=False, default=DEFAULT)
3822 3822 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3823 3823 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3824 3824 version = Column('version', Integer(), nullable=False, default=0)
3825 3825 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3826 3826
3827 3827 author = relationship('User', lazy='joined')
3828 3828 repo = relationship('Repository')
3829 3829 comment = relationship('ChangesetComment', lazy='joined')
3830 3830 pull_request = relationship('PullRequest', lazy='joined')
3831 3831
3832 3832 def __unicode__(self):
3833 3833 return u"<%s('%s[v%s]:%s')>" % (
3834 3834 self.__class__.__name__,
3835 3835 self.status, self.version, self.author
3836 3836 )
3837 3837
3838 3838 @classmethod
3839 3839 def get_status_lbl(cls, value):
3840 3840 return dict(cls.STATUSES).get(value)
3841 3841
3842 3842 @property
3843 3843 def status_lbl(self):
3844 3844 return ChangesetStatus.get_status_lbl(self.status)
3845 3845
3846 3846 def get_api_data(self):
3847 3847 status = self
3848 3848 data = {
3849 3849 'status_id': status.changeset_status_id,
3850 3850 'status': status.status,
3851 3851 }
3852 3852 return data
3853 3853
3854 3854 def __json__(self):
3855 3855 data = dict()
3856 3856 data.update(self.get_api_data())
3857 3857 return data
3858 3858
3859 3859
3860 3860 class _SetState(object):
3861 3861 """
3862 3862 Context processor allowing changing state for sensitive operation such as
3863 3863 pull request update or merge
3864 3864 """
3865 3865
3866 3866 def __init__(self, pull_request, pr_state, back_state=None):
3867 3867 self._pr = pull_request
3868 3868 self._org_state = back_state or pull_request.pull_request_state
3869 3869 self._pr_state = pr_state
3870 3870 self._current_state = None
3871 3871
3872 3872 def __enter__(self):
3873 3873 log.debug('StateLock: entering set state context, setting state to: `%s`',
3874 3874 self._pr_state)
3875 3875 self.set_pr_state(self._pr_state)
3876 3876 return self
3877 3877
3878 3878 def __exit__(self, exc_type, exc_val, exc_tb):
3879 3879 if exc_val is not None:
3880 3880 log.error(traceback.format_exc(exc_tb))
3881 3881 return None
3882 3882
3883 3883 self.set_pr_state(self._org_state)
3884 3884 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3885 3885 self._org_state)
3886 3886 @property
3887 3887 def state(self):
3888 3888 return self._current_state
3889 3889
3890 3890 def set_pr_state(self, pr_state):
3891 3891 try:
3892 3892 self._pr.pull_request_state = pr_state
3893 3893 Session().add(self._pr)
3894 3894 Session().commit()
3895 3895 self._current_state = pr_state
3896 3896 except Exception:
3897 3897 log.exception('Failed to set PullRequest %s state to %s', self._pr, pr_state)
3898 3898 raise
3899 3899
3900 3900
3901 3901 class _PullRequestBase(BaseModel):
3902 3902 """
3903 3903 Common attributes of pull request and version entries.
3904 3904 """
3905 3905
3906 3906 # .status values
3907 3907 STATUS_NEW = u'new'
3908 3908 STATUS_OPEN = u'open'
3909 3909 STATUS_CLOSED = u'closed'
3910 3910
3911 3911 # available states
3912 3912 STATE_CREATING = u'creating'
3913 3913 STATE_UPDATING = u'updating'
3914 3914 STATE_MERGING = u'merging'
3915 3915 STATE_CREATED = u'created'
3916 3916
3917 3917 title = Column('title', Unicode(255), nullable=True)
3918 3918 description = Column(
3919 3919 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3920 3920 nullable=True)
3921 3921 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3922 3922
3923 3923 # new/open/closed status of pull request (not approve/reject/etc)
3924 3924 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3925 3925 created_on = Column(
3926 3926 'created_on', DateTime(timezone=False), nullable=False,
3927 3927 default=datetime.datetime.now)
3928 3928 updated_on = Column(
3929 3929 'updated_on', DateTime(timezone=False), nullable=False,
3930 3930 default=datetime.datetime.now)
3931 3931
3932 3932 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3933 3933
3934 3934 @declared_attr
3935 3935 def user_id(cls):
3936 3936 return Column(
3937 3937 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3938 3938 unique=None)
3939 3939
3940 3940 # 500 revisions max
3941 3941 _revisions = Column(
3942 3942 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3943 3943
3944 3944 @declared_attr
3945 3945 def source_repo_id(cls):
3946 3946 # TODO: dan: rename column to source_repo_id
3947 3947 return Column(
3948 3948 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3949 3949 nullable=False)
3950 3950
3951 3951 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3952 3952
3953 3953 @hybrid_property
3954 3954 def source_ref(self):
3955 3955 return self._source_ref
3956 3956
3957 3957 @source_ref.setter
3958 3958 def source_ref(self, val):
3959 3959 parts = (val or '').split(':')
3960 3960 if len(parts) != 3:
3961 3961 raise ValueError(
3962 3962 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3963 3963 self._source_ref = safe_unicode(val)
3964 3964
3965 3965 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3966 3966
3967 3967 @hybrid_property
3968 3968 def target_ref(self):
3969 3969 return self._target_ref
3970 3970
3971 3971 @target_ref.setter
3972 3972 def target_ref(self, val):
3973 3973 parts = (val or '').split(':')
3974 3974 if len(parts) != 3:
3975 3975 raise ValueError(
3976 3976 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3977 3977 self._target_ref = safe_unicode(val)
3978 3978
3979 3979 @declared_attr
3980 3980 def target_repo_id(cls):
3981 3981 # TODO: dan: rename column to target_repo_id
3982 3982 return Column(
3983 3983 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3984 3984 nullable=False)
3985 3985
3986 3986 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3987 3987
3988 3988 # TODO: dan: rename column to last_merge_source_rev
3989 3989 _last_merge_source_rev = Column(
3990 3990 'last_merge_org_rev', String(40), nullable=True)
3991 3991 # TODO: dan: rename column to last_merge_target_rev
3992 3992 _last_merge_target_rev = Column(
3993 3993 'last_merge_other_rev', String(40), nullable=True)
3994 3994 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3995 3995 merge_rev = Column('merge_rev', String(40), nullable=True)
3996 3996
3997 3997 reviewer_data = Column(
3998 3998 'reviewer_data_json', MutationObj.as_mutable(
3999 3999 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4000 4000
4001 4001 @property
4002 4002 def reviewer_data_json(self):
4003 4003 return json.dumps(self.reviewer_data)
4004 4004
4005 4005 @property
4006 4006 def work_in_progress(self):
4007 4007 """checks if pull request is work in progress by checking the title"""
4008 4008 title = self.title.upper()
4009 4009 if re.match(r'^(\[WIP\]\s*|WIP:\s*|WIP\s+)', title):
4010 4010 return True
4011 4011 return False
4012 4012
4013 4013 @hybrid_property
4014 4014 def description_safe(self):
4015 4015 from rhodecode.lib import helpers as h
4016 4016 return h.escape(self.description)
4017 4017
4018 4018 @hybrid_property
4019 4019 def revisions(self):
4020 4020 return self._revisions.split(':') if self._revisions else []
4021 4021
4022 4022 @revisions.setter
4023 4023 def revisions(self, val):
4024 4024 self._revisions = u':'.join(val)
4025 4025
4026 4026 @hybrid_property
4027 4027 def last_merge_status(self):
4028 4028 return safe_int(self._last_merge_status)
4029 4029
4030 4030 @last_merge_status.setter
4031 4031 def last_merge_status(self, val):
4032 4032 self._last_merge_status = val
4033 4033
4034 4034 @declared_attr
4035 4035 def author(cls):
4036 4036 return relationship('User', lazy='joined')
4037 4037
4038 4038 @declared_attr
4039 4039 def source_repo(cls):
4040 4040 return relationship(
4041 4041 'Repository',
4042 4042 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
4043 4043
4044 4044 @property
4045 4045 def source_ref_parts(self):
4046 4046 return self.unicode_to_reference(self.source_ref)
4047 4047
4048 4048 @declared_attr
4049 4049 def target_repo(cls):
4050 4050 return relationship(
4051 4051 'Repository',
4052 4052 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
4053 4053
4054 4054 @property
4055 4055 def target_ref_parts(self):
4056 4056 return self.unicode_to_reference(self.target_ref)
4057 4057
4058 4058 @property
4059 4059 def shadow_merge_ref(self):
4060 4060 return self.unicode_to_reference(self._shadow_merge_ref)
4061 4061
4062 4062 @shadow_merge_ref.setter
4063 4063 def shadow_merge_ref(self, ref):
4064 4064 self._shadow_merge_ref = self.reference_to_unicode(ref)
4065 4065
4066 4066 @staticmethod
4067 4067 def unicode_to_reference(raw):
4068 4068 """
4069 4069 Convert a unicode (or string) to a reference object.
4070 4070 If unicode evaluates to False it returns None.
4071 4071 """
4072 4072 if raw:
4073 4073 refs = raw.split(':')
4074 4074 return Reference(*refs)
4075 4075 else:
4076 4076 return None
4077 4077
4078 4078 @staticmethod
4079 4079 def reference_to_unicode(ref):
4080 4080 """
4081 4081 Convert a reference object to unicode.
4082 4082 If reference is None it returns None.
4083 4083 """
4084 4084 if ref:
4085 4085 return u':'.join(ref)
4086 4086 else:
4087 4087 return None
4088 4088
4089 4089 def get_api_data(self, with_merge_state=True):
4090 4090 from rhodecode.model.pull_request import PullRequestModel
4091 4091
4092 4092 pull_request = self
4093 4093 if with_merge_state:
4094 4094 merge_status = PullRequestModel().merge_status(pull_request)
4095 4095 merge_state = {
4096 4096 'status': merge_status[0],
4097 4097 'message': safe_unicode(merge_status[1]),
4098 4098 }
4099 4099 else:
4100 4100 merge_state = {'status': 'not_available',
4101 4101 'message': 'not_available'}
4102 4102
4103 4103 merge_data = {
4104 4104 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4105 4105 'reference': (
4106 4106 pull_request.shadow_merge_ref._asdict()
4107 4107 if pull_request.shadow_merge_ref else None),
4108 4108 }
4109 4109
4110 4110 data = {
4111 4111 'pull_request_id': pull_request.pull_request_id,
4112 4112 'url': PullRequestModel().get_url(pull_request),
4113 4113 'title': pull_request.title,
4114 4114 'description': pull_request.description,
4115 4115 'status': pull_request.status,
4116 4116 'state': pull_request.pull_request_state,
4117 4117 'created_on': pull_request.created_on,
4118 4118 'updated_on': pull_request.updated_on,
4119 4119 'commit_ids': pull_request.revisions,
4120 4120 'review_status': pull_request.calculated_review_status(),
4121 4121 'mergeable': merge_state,
4122 4122 'source': {
4123 4123 'clone_url': pull_request.source_repo.clone_url(),
4124 4124 'repository': pull_request.source_repo.repo_name,
4125 4125 'reference': {
4126 4126 'name': pull_request.source_ref_parts.name,
4127 4127 'type': pull_request.source_ref_parts.type,
4128 4128 'commit_id': pull_request.source_ref_parts.commit_id,
4129 4129 },
4130 4130 },
4131 4131 'target': {
4132 4132 'clone_url': pull_request.target_repo.clone_url(),
4133 4133 'repository': pull_request.target_repo.repo_name,
4134 4134 'reference': {
4135 4135 'name': pull_request.target_ref_parts.name,
4136 4136 'type': pull_request.target_ref_parts.type,
4137 4137 'commit_id': pull_request.target_ref_parts.commit_id,
4138 4138 },
4139 4139 },
4140 4140 'merge': merge_data,
4141 4141 'author': pull_request.author.get_api_data(include_secrets=False,
4142 4142 details='basic'),
4143 4143 'reviewers': [
4144 4144 {
4145 4145 'user': reviewer.get_api_data(include_secrets=False,
4146 4146 details='basic'),
4147 4147 'reasons': reasons,
4148 4148 'review_status': st[0][1].status if st else 'not_reviewed',
4149 4149 }
4150 4150 for obj, reviewer, reasons, mandatory, st in
4151 4151 pull_request.reviewers_statuses()
4152 4152 ]
4153 4153 }
4154 4154
4155 4155 return data
4156 4156
4157 4157 def set_state(self, pull_request_state, final_state=None):
4158 4158 """
4159 4159 # goes from initial state to updating to initial state.
4160 4160 # initial state can be changed by specifying back_state=
4161 4161 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4162 4162 pull_request.merge()
4163 4163
4164 4164 :param pull_request_state:
4165 4165 :param final_state:
4166 4166
4167 4167 """
4168 4168
4169 4169 return _SetState(self, pull_request_state, back_state=final_state)
4170 4170
4171 4171
4172 4172 class PullRequest(Base, _PullRequestBase):
4173 4173 __tablename__ = 'pull_requests'
4174 4174 __table_args__ = (
4175 4175 base_table_args,
4176 4176 )
4177 4177
4178 4178 pull_request_id = Column(
4179 4179 'pull_request_id', Integer(), nullable=False, primary_key=True)
4180 4180
4181 4181 def __repr__(self):
4182 4182 if self.pull_request_id:
4183 4183 return '<DB:PullRequest #%s>' % self.pull_request_id
4184 4184 else:
4185 4185 return '<DB:PullRequest at %#x>' % id(self)
4186 4186
4187 4187 reviewers = relationship('PullRequestReviewers', cascade="all, delete-orphan")
4188 4188 statuses = relationship('ChangesetStatus', cascade="all, delete-orphan")
4189 4189 comments = relationship('ChangesetComment', cascade="all, delete-orphan")
4190 4190 versions = relationship('PullRequestVersion', cascade="all, delete-orphan",
4191 4191 lazy='dynamic')
4192 4192
4193 4193 @classmethod
4194 4194 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4195 4195 internal_methods=None):
4196 4196
4197 4197 class PullRequestDisplay(object):
4198 4198 """
4199 4199 Special object wrapper for showing PullRequest data via Versions
4200 4200 It mimics PR object as close as possible. This is read only object
4201 4201 just for display
4202 4202 """
4203 4203
4204 4204 def __init__(self, attrs, internal=None):
4205 4205 self.attrs = attrs
4206 4206 # internal have priority over the given ones via attrs
4207 4207 self.internal = internal or ['versions']
4208 4208
4209 4209 def __getattr__(self, item):
4210 4210 if item in self.internal:
4211 4211 return getattr(self, item)
4212 4212 try:
4213 4213 return self.attrs[item]
4214 4214 except KeyError:
4215 4215 raise AttributeError(
4216 4216 '%s object has no attribute %s' % (self, item))
4217 4217
4218 4218 def __repr__(self):
4219 4219 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
4220 4220
4221 4221 def versions(self):
4222 4222 return pull_request_obj.versions.order_by(
4223 4223 PullRequestVersion.pull_request_version_id).all()
4224 4224
4225 4225 def is_closed(self):
4226 4226 return pull_request_obj.is_closed()
4227 4227
4228 def is_state_changing(self):
4229 return pull_request_obj.is_state_changing()
4230
4228 4231 @property
4229 4232 def pull_request_version_id(self):
4230 4233 return getattr(pull_request_obj, 'pull_request_version_id', None)
4231 4234
4232 4235 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4233 4236
4234 4237 attrs.author = StrictAttributeDict(
4235 4238 pull_request_obj.author.get_api_data())
4236 4239 if pull_request_obj.target_repo:
4237 4240 attrs.target_repo = StrictAttributeDict(
4238 4241 pull_request_obj.target_repo.get_api_data())
4239 4242 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4240 4243
4241 4244 if pull_request_obj.source_repo:
4242 4245 attrs.source_repo = StrictAttributeDict(
4243 4246 pull_request_obj.source_repo.get_api_data())
4244 4247 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4245 4248
4246 4249 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4247 4250 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4248 4251 attrs.revisions = pull_request_obj.revisions
4249 4252
4250 4253 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4251 4254 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4252 4255 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4253 4256
4254 4257 return PullRequestDisplay(attrs, internal=internal_methods)
4255 4258
4256 4259 def is_closed(self):
4257 4260 return self.status == self.STATUS_CLOSED
4258 4261
4262 def is_state_changing(self):
4263 return self.pull_request_state != PullRequest.STATE_CREATED
4264
4259 4265 def __json__(self):
4260 4266 return {
4261 4267 'revisions': self.revisions,
4262 4268 }
4263 4269
4264 4270 def calculated_review_status(self):
4265 4271 from rhodecode.model.changeset_status import ChangesetStatusModel
4266 4272 return ChangesetStatusModel().calculated_review_status(self)
4267 4273
4268 4274 def reviewers_statuses(self):
4269 4275 from rhodecode.model.changeset_status import ChangesetStatusModel
4270 4276 return ChangesetStatusModel().reviewers_statuses(self)
4271 4277
4272 4278 @property
4273 4279 def workspace_id(self):
4274 4280 from rhodecode.model.pull_request import PullRequestModel
4275 4281 return PullRequestModel()._workspace_id(self)
4276 4282
4277 4283 def get_shadow_repo(self):
4278 4284 workspace_id = self.workspace_id
4279 4285 shadow_repository_path = self.target_repo.get_shadow_repository_path(workspace_id)
4280 4286 if os.path.isdir(shadow_repository_path):
4281 4287 vcs_obj = self.target_repo.scm_instance()
4282 4288 return vcs_obj.get_shadow_instance(shadow_repository_path)
4283 4289
4284 4290
4285 4291 class PullRequestVersion(Base, _PullRequestBase):
4286 4292 __tablename__ = 'pull_request_versions'
4287 4293 __table_args__ = (
4288 4294 base_table_args,
4289 4295 )
4290 4296
4291 4297 pull_request_version_id = Column(
4292 4298 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
4293 4299 pull_request_id = Column(
4294 4300 'pull_request_id', Integer(),
4295 4301 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4296 4302 pull_request = relationship('PullRequest')
4297 4303
4298 4304 def __repr__(self):
4299 4305 if self.pull_request_version_id:
4300 4306 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
4301 4307 else:
4302 4308 return '<DB:PullRequestVersion at %#x>' % id(self)
4303 4309
4304 4310 @property
4305 4311 def reviewers(self):
4306 4312 return self.pull_request.reviewers
4307 4313
4308 4314 @property
4309 4315 def versions(self):
4310 4316 return self.pull_request.versions
4311 4317
4312 4318 def is_closed(self):
4313 4319 # calculate from original
4314 4320 return self.pull_request.status == self.STATUS_CLOSED
4315 4321
4322 def is_state_changing(self):
4323 return self.pull_request.pull_request_state != PullRequest.STATE_CREATED
4324
4316 4325 def calculated_review_status(self):
4317 4326 return self.pull_request.calculated_review_status()
4318 4327
4319 4328 def reviewers_statuses(self):
4320 4329 return self.pull_request.reviewers_statuses()
4321 4330
4322 4331
4323 4332 class PullRequestReviewers(Base, BaseModel):
4324 4333 __tablename__ = 'pull_request_reviewers'
4325 4334 __table_args__ = (
4326 4335 base_table_args,
4327 4336 )
4328 4337
4329 4338 @hybrid_property
4330 4339 def reasons(self):
4331 4340 if not self._reasons:
4332 4341 return []
4333 4342 return self._reasons
4334 4343
4335 4344 @reasons.setter
4336 4345 def reasons(self, val):
4337 4346 val = val or []
4338 4347 if any(not isinstance(x, compat.string_types) for x in val):
4339 4348 raise Exception('invalid reasons type, must be list of strings')
4340 4349 self._reasons = val
4341 4350
4342 4351 pull_requests_reviewers_id = Column(
4343 4352 'pull_requests_reviewers_id', Integer(), nullable=False,
4344 4353 primary_key=True)
4345 4354 pull_request_id = Column(
4346 4355 "pull_request_id", Integer(),
4347 4356 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4348 4357 user_id = Column(
4349 4358 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4350 4359 _reasons = Column(
4351 4360 'reason', MutationList.as_mutable(
4352 4361 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4353 4362
4354 4363 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4355 4364 user = relationship('User')
4356 4365 pull_request = relationship('PullRequest')
4357 4366
4358 4367 rule_data = Column(
4359 4368 'rule_data_json',
4360 4369 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4361 4370
4362 4371 def rule_user_group_data(self):
4363 4372 """
4364 4373 Returns the voting user group rule data for this reviewer
4365 4374 """
4366 4375
4367 4376 if self.rule_data and 'vote_rule' in self.rule_data:
4368 4377 user_group_data = {}
4369 4378 if 'rule_user_group_entry_id' in self.rule_data:
4370 4379 # means a group with voting rules !
4371 4380 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4372 4381 user_group_data['name'] = self.rule_data['rule_name']
4373 4382 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4374 4383
4375 4384 return user_group_data
4376 4385
4377 4386 def __unicode__(self):
4378 4387 return u"<%s('id:%s')>" % (self.__class__.__name__,
4379 4388 self.pull_requests_reviewers_id)
4380 4389
4381 4390
4382 4391 class Notification(Base, BaseModel):
4383 4392 __tablename__ = 'notifications'
4384 4393 __table_args__ = (
4385 4394 Index('notification_type_idx', 'type'),
4386 4395 base_table_args,
4387 4396 )
4388 4397
4389 4398 TYPE_CHANGESET_COMMENT = u'cs_comment'
4390 4399 TYPE_MESSAGE = u'message'
4391 4400 TYPE_MENTION = u'mention'
4392 4401 TYPE_REGISTRATION = u'registration'
4393 4402 TYPE_PULL_REQUEST = u'pull_request'
4394 4403 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4395 4404
4396 4405 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4397 4406 subject = Column('subject', Unicode(512), nullable=True)
4398 4407 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4399 4408 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4400 4409 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4401 4410 type_ = Column('type', Unicode(255))
4402 4411
4403 4412 created_by_user = relationship('User')
4404 4413 notifications_to_users = relationship('UserNotification', lazy='joined',
4405 4414 cascade="all, delete-orphan")
4406 4415
4407 4416 @property
4408 4417 def recipients(self):
4409 4418 return [x.user for x in UserNotification.query()\
4410 4419 .filter(UserNotification.notification == self)\
4411 4420 .order_by(UserNotification.user_id.asc()).all()]
4412 4421
4413 4422 @classmethod
4414 4423 def create(cls, created_by, subject, body, recipients, type_=None):
4415 4424 if type_ is None:
4416 4425 type_ = Notification.TYPE_MESSAGE
4417 4426
4418 4427 notification = cls()
4419 4428 notification.created_by_user = created_by
4420 4429 notification.subject = subject
4421 4430 notification.body = body
4422 4431 notification.type_ = type_
4423 4432 notification.created_on = datetime.datetime.now()
4424 4433
4425 4434 # For each recipient link the created notification to his account
4426 4435 for u in recipients:
4427 4436 assoc = UserNotification()
4428 4437 assoc.user_id = u.user_id
4429 4438 assoc.notification = notification
4430 4439
4431 4440 # if created_by is inside recipients mark his notification
4432 4441 # as read
4433 4442 if u.user_id == created_by.user_id:
4434 4443 assoc.read = True
4435 4444 Session().add(assoc)
4436 4445
4437 4446 Session().add(notification)
4438 4447
4439 4448 return notification
4440 4449
4441 4450
4442 4451 class UserNotification(Base, BaseModel):
4443 4452 __tablename__ = 'user_to_notification'
4444 4453 __table_args__ = (
4445 4454 UniqueConstraint('user_id', 'notification_id'),
4446 4455 base_table_args
4447 4456 )
4448 4457
4449 4458 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4450 4459 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4451 4460 read = Column('read', Boolean, default=False)
4452 4461 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4453 4462
4454 4463 user = relationship('User', lazy="joined")
4455 4464 notification = relationship('Notification', lazy="joined",
4456 4465 order_by=lambda: Notification.created_on.desc(),)
4457 4466
4458 4467 def mark_as_read(self):
4459 4468 self.read = True
4460 4469 Session().add(self)
4461 4470
4462 4471
4463 4472 class Gist(Base, BaseModel):
4464 4473 __tablename__ = 'gists'
4465 4474 __table_args__ = (
4466 4475 Index('g_gist_access_id_idx', 'gist_access_id'),
4467 4476 Index('g_created_on_idx', 'created_on'),
4468 4477 base_table_args
4469 4478 )
4470 4479
4471 4480 GIST_PUBLIC = u'public'
4472 4481 GIST_PRIVATE = u'private'
4473 4482 DEFAULT_FILENAME = u'gistfile1.txt'
4474 4483
4475 4484 ACL_LEVEL_PUBLIC = u'acl_public'
4476 4485 ACL_LEVEL_PRIVATE = u'acl_private'
4477 4486
4478 4487 gist_id = Column('gist_id', Integer(), primary_key=True)
4479 4488 gist_access_id = Column('gist_access_id', Unicode(250))
4480 4489 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4481 4490 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4482 4491 gist_expires = Column('gist_expires', Float(53), nullable=False)
4483 4492 gist_type = Column('gist_type', Unicode(128), nullable=False)
4484 4493 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4485 4494 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4486 4495 acl_level = Column('acl_level', Unicode(128), nullable=True)
4487 4496
4488 4497 owner = relationship('User')
4489 4498
4490 4499 def __repr__(self):
4491 4500 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4492 4501
4493 4502 @hybrid_property
4494 4503 def description_safe(self):
4495 4504 from rhodecode.lib import helpers as h
4496 4505 return h.escape(self.gist_description)
4497 4506
4498 4507 @classmethod
4499 4508 def get_or_404(cls, id_):
4500 4509 from pyramid.httpexceptions import HTTPNotFound
4501 4510
4502 4511 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4503 4512 if not res:
4504 4513 raise HTTPNotFound()
4505 4514 return res
4506 4515
4507 4516 @classmethod
4508 4517 def get_by_access_id(cls, gist_access_id):
4509 4518 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4510 4519
4511 4520 def gist_url(self):
4512 4521 from rhodecode.model.gist import GistModel
4513 4522 return GistModel().get_url(self)
4514 4523
4515 4524 @classmethod
4516 4525 def base_path(cls):
4517 4526 """
4518 4527 Returns base path when all gists are stored
4519 4528
4520 4529 :param cls:
4521 4530 """
4522 4531 from rhodecode.model.gist import GIST_STORE_LOC
4523 4532 q = Session().query(RhodeCodeUi)\
4524 4533 .filter(RhodeCodeUi.ui_key == URL_SEP)
4525 4534 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4526 4535 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4527 4536
4528 4537 def get_api_data(self):
4529 4538 """
4530 4539 Common function for generating gist related data for API
4531 4540 """
4532 4541 gist = self
4533 4542 data = {
4534 4543 'gist_id': gist.gist_id,
4535 4544 'type': gist.gist_type,
4536 4545 'access_id': gist.gist_access_id,
4537 4546 'description': gist.gist_description,
4538 4547 'url': gist.gist_url(),
4539 4548 'expires': gist.gist_expires,
4540 4549 'created_on': gist.created_on,
4541 4550 'modified_at': gist.modified_at,
4542 4551 'content': None,
4543 4552 'acl_level': gist.acl_level,
4544 4553 }
4545 4554 return data
4546 4555
4547 4556 def __json__(self):
4548 4557 data = dict(
4549 4558 )
4550 4559 data.update(self.get_api_data())
4551 4560 return data
4552 4561 # SCM functions
4553 4562
4554 4563 def scm_instance(self, **kwargs):
4555 4564 """
4556 4565 Get an instance of VCS Repository
4557 4566
4558 4567 :param kwargs:
4559 4568 """
4560 4569 from rhodecode.model.gist import GistModel
4561 4570 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4562 4571 return get_vcs_instance(
4563 4572 repo_path=safe_str(full_repo_path), create=False,
4564 4573 _vcs_alias=GistModel.vcs_backend)
4565 4574
4566 4575
4567 4576 class ExternalIdentity(Base, BaseModel):
4568 4577 __tablename__ = 'external_identities'
4569 4578 __table_args__ = (
4570 4579 Index('local_user_id_idx', 'local_user_id'),
4571 4580 Index('external_id_idx', 'external_id'),
4572 4581 base_table_args
4573 4582 )
4574 4583
4575 4584 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4576 4585 external_username = Column('external_username', Unicode(1024), default=u'')
4577 4586 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4578 4587 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4579 4588 access_token = Column('access_token', String(1024), default=u'')
4580 4589 alt_token = Column('alt_token', String(1024), default=u'')
4581 4590 token_secret = Column('token_secret', String(1024), default=u'')
4582 4591
4583 4592 @classmethod
4584 4593 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4585 4594 """
4586 4595 Returns ExternalIdentity instance based on search params
4587 4596
4588 4597 :param external_id:
4589 4598 :param provider_name:
4590 4599 :return: ExternalIdentity
4591 4600 """
4592 4601 query = cls.query()
4593 4602 query = query.filter(cls.external_id == external_id)
4594 4603 query = query.filter(cls.provider_name == provider_name)
4595 4604 if local_user_id:
4596 4605 query = query.filter(cls.local_user_id == local_user_id)
4597 4606 return query.first()
4598 4607
4599 4608 @classmethod
4600 4609 def user_by_external_id_and_provider(cls, external_id, provider_name):
4601 4610 """
4602 4611 Returns User instance based on search params
4603 4612
4604 4613 :param external_id:
4605 4614 :param provider_name:
4606 4615 :return: User
4607 4616 """
4608 4617 query = User.query()
4609 4618 query = query.filter(cls.external_id == external_id)
4610 4619 query = query.filter(cls.provider_name == provider_name)
4611 4620 query = query.filter(User.user_id == cls.local_user_id)
4612 4621 return query.first()
4613 4622
4614 4623 @classmethod
4615 4624 def by_local_user_id(cls, local_user_id):
4616 4625 """
4617 4626 Returns all tokens for user
4618 4627
4619 4628 :param local_user_id:
4620 4629 :return: ExternalIdentity
4621 4630 """
4622 4631 query = cls.query()
4623 4632 query = query.filter(cls.local_user_id == local_user_id)
4624 4633 return query
4625 4634
4626 4635 @classmethod
4627 4636 def load_provider_plugin(cls, plugin_id):
4628 4637 from rhodecode.authentication.base import loadplugin
4629 4638 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4630 4639 auth_plugin = loadplugin(_plugin_id)
4631 4640 return auth_plugin
4632 4641
4633 4642
4634 4643 class Integration(Base, BaseModel):
4635 4644 __tablename__ = 'integrations'
4636 4645 __table_args__ = (
4637 4646 base_table_args
4638 4647 )
4639 4648
4640 4649 integration_id = Column('integration_id', Integer(), primary_key=True)
4641 4650 integration_type = Column('integration_type', String(255))
4642 4651 enabled = Column('enabled', Boolean(), nullable=False)
4643 4652 name = Column('name', String(255), nullable=False)
4644 4653 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4645 4654 default=False)
4646 4655
4647 4656 settings = Column(
4648 4657 'settings_json', MutationObj.as_mutable(
4649 4658 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4650 4659 repo_id = Column(
4651 4660 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4652 4661 nullable=True, unique=None, default=None)
4653 4662 repo = relationship('Repository', lazy='joined')
4654 4663
4655 4664 repo_group_id = Column(
4656 4665 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4657 4666 nullable=True, unique=None, default=None)
4658 4667 repo_group = relationship('RepoGroup', lazy='joined')
4659 4668
4660 4669 @property
4661 4670 def scope(self):
4662 4671 if self.repo:
4663 4672 return repr(self.repo)
4664 4673 if self.repo_group:
4665 4674 if self.child_repos_only:
4666 4675 return repr(self.repo_group) + ' (child repos only)'
4667 4676 else:
4668 4677 return repr(self.repo_group) + ' (recursive)'
4669 4678 if self.child_repos_only:
4670 4679 return 'root_repos'
4671 4680 return 'global'
4672 4681
4673 4682 def __repr__(self):
4674 4683 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4675 4684
4676 4685
4677 4686 class RepoReviewRuleUser(Base, BaseModel):
4678 4687 __tablename__ = 'repo_review_rules_users'
4679 4688 __table_args__ = (
4680 4689 base_table_args
4681 4690 )
4682 4691
4683 4692 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4684 4693 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4685 4694 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4686 4695 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4687 4696 user = relationship('User')
4688 4697
4689 4698 def rule_data(self):
4690 4699 return {
4691 4700 'mandatory': self.mandatory
4692 4701 }
4693 4702
4694 4703
4695 4704 class RepoReviewRuleUserGroup(Base, BaseModel):
4696 4705 __tablename__ = 'repo_review_rules_users_groups'
4697 4706 __table_args__ = (
4698 4707 base_table_args
4699 4708 )
4700 4709
4701 4710 VOTE_RULE_ALL = -1
4702 4711
4703 4712 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4704 4713 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4705 4714 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4706 4715 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4707 4716 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4708 4717 users_group = relationship('UserGroup')
4709 4718
4710 4719 def rule_data(self):
4711 4720 return {
4712 4721 'mandatory': self.mandatory,
4713 4722 'vote_rule': self.vote_rule
4714 4723 }
4715 4724
4716 4725 @property
4717 4726 def vote_rule_label(self):
4718 4727 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4719 4728 return 'all must vote'
4720 4729 else:
4721 4730 return 'min. vote {}'.format(self.vote_rule)
4722 4731
4723 4732
4724 4733 class RepoReviewRule(Base, BaseModel):
4725 4734 __tablename__ = 'repo_review_rules'
4726 4735 __table_args__ = (
4727 4736 base_table_args
4728 4737 )
4729 4738
4730 4739 repo_review_rule_id = Column(
4731 4740 'repo_review_rule_id', Integer(), primary_key=True)
4732 4741 repo_id = Column(
4733 4742 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4734 4743 repo = relationship('Repository', backref='review_rules')
4735 4744
4736 4745 review_rule_name = Column('review_rule_name', String(255))
4737 4746 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4738 4747 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4739 4748 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4740 4749
4741 4750 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4742 4751 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4743 4752 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4744 4753 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4745 4754
4746 4755 rule_users = relationship('RepoReviewRuleUser')
4747 4756 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4748 4757
4749 4758 def _validate_pattern(self, value):
4750 4759 re.compile('^' + glob2re(value) + '$')
4751 4760
4752 4761 @hybrid_property
4753 4762 def source_branch_pattern(self):
4754 4763 return self._branch_pattern or '*'
4755 4764
4756 4765 @source_branch_pattern.setter
4757 4766 def source_branch_pattern(self, value):
4758 4767 self._validate_pattern(value)
4759 4768 self._branch_pattern = value or '*'
4760 4769
4761 4770 @hybrid_property
4762 4771 def target_branch_pattern(self):
4763 4772 return self._target_branch_pattern or '*'
4764 4773
4765 4774 @target_branch_pattern.setter
4766 4775 def target_branch_pattern(self, value):
4767 4776 self._validate_pattern(value)
4768 4777 self._target_branch_pattern = value or '*'
4769 4778
4770 4779 @hybrid_property
4771 4780 def file_pattern(self):
4772 4781 return self._file_pattern or '*'
4773 4782
4774 4783 @file_pattern.setter
4775 4784 def file_pattern(self, value):
4776 4785 self._validate_pattern(value)
4777 4786 self._file_pattern = value or '*'
4778 4787
4779 4788 def matches(self, source_branch, target_branch, files_changed):
4780 4789 """
4781 4790 Check if this review rule matches a branch/files in a pull request
4782 4791
4783 4792 :param source_branch: source branch name for the commit
4784 4793 :param target_branch: target branch name for the commit
4785 4794 :param files_changed: list of file paths changed in the pull request
4786 4795 """
4787 4796
4788 4797 source_branch = source_branch or ''
4789 4798 target_branch = target_branch or ''
4790 4799 files_changed = files_changed or []
4791 4800
4792 4801 branch_matches = True
4793 4802 if source_branch or target_branch:
4794 4803 if self.source_branch_pattern == '*':
4795 4804 source_branch_match = True
4796 4805 else:
4797 4806 if self.source_branch_pattern.startswith('re:'):
4798 4807 source_pattern = self.source_branch_pattern[3:]
4799 4808 else:
4800 4809 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4801 4810 source_branch_regex = re.compile(source_pattern)
4802 4811 source_branch_match = bool(source_branch_regex.search(source_branch))
4803 4812 if self.target_branch_pattern == '*':
4804 4813 target_branch_match = True
4805 4814 else:
4806 4815 if self.target_branch_pattern.startswith('re:'):
4807 4816 target_pattern = self.target_branch_pattern[3:]
4808 4817 else:
4809 4818 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4810 4819 target_branch_regex = re.compile(target_pattern)
4811 4820 target_branch_match = bool(target_branch_regex.search(target_branch))
4812 4821
4813 4822 branch_matches = source_branch_match and target_branch_match
4814 4823
4815 4824 files_matches = True
4816 4825 if self.file_pattern != '*':
4817 4826 files_matches = False
4818 4827 if self.file_pattern.startswith('re:'):
4819 4828 file_pattern = self.file_pattern[3:]
4820 4829 else:
4821 4830 file_pattern = glob2re(self.file_pattern)
4822 4831 file_regex = re.compile(file_pattern)
4823 4832 for filename in files_changed:
4824 4833 if file_regex.search(filename):
4825 4834 files_matches = True
4826 4835 break
4827 4836
4828 4837 return branch_matches and files_matches
4829 4838
4830 4839 @property
4831 4840 def review_users(self):
4832 4841 """ Returns the users which this rule applies to """
4833 4842
4834 4843 users = collections.OrderedDict()
4835 4844
4836 4845 for rule_user in self.rule_users:
4837 4846 if rule_user.user.active:
4838 4847 if rule_user.user not in users:
4839 4848 users[rule_user.user.username] = {
4840 4849 'user': rule_user.user,
4841 4850 'source': 'user',
4842 4851 'source_data': {},
4843 4852 'data': rule_user.rule_data()
4844 4853 }
4845 4854
4846 4855 for rule_user_group in self.rule_user_groups:
4847 4856 source_data = {
4848 4857 'user_group_id': rule_user_group.users_group.users_group_id,
4849 4858 'name': rule_user_group.users_group.users_group_name,
4850 4859 'members': len(rule_user_group.users_group.members)
4851 4860 }
4852 4861 for member in rule_user_group.users_group.members:
4853 4862 if member.user.active:
4854 4863 key = member.user.username
4855 4864 if key in users:
4856 4865 # skip this member as we have him already
4857 4866 # this prevents from override the "first" matched
4858 4867 # users with duplicates in multiple groups
4859 4868 continue
4860 4869
4861 4870 users[key] = {
4862 4871 'user': member.user,
4863 4872 'source': 'user_group',
4864 4873 'source_data': source_data,
4865 4874 'data': rule_user_group.rule_data()
4866 4875 }
4867 4876
4868 4877 return users
4869 4878
4870 4879 def user_group_vote_rule(self, user_id):
4871 4880
4872 4881 rules = []
4873 4882 if not self.rule_user_groups:
4874 4883 return rules
4875 4884
4876 4885 for user_group in self.rule_user_groups:
4877 4886 user_group_members = [x.user_id for x in user_group.users_group.members]
4878 4887 if user_id in user_group_members:
4879 4888 rules.append(user_group)
4880 4889 return rules
4881 4890
4882 4891 def __repr__(self):
4883 4892 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4884 4893 self.repo_review_rule_id, self.repo)
4885 4894
4886 4895
4887 4896 class ScheduleEntry(Base, BaseModel):
4888 4897 __tablename__ = 'schedule_entries'
4889 4898 __table_args__ = (
4890 4899 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4891 4900 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4892 4901 base_table_args,
4893 4902 )
4894 4903
4895 4904 schedule_types = ['crontab', 'timedelta', 'integer']
4896 4905 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4897 4906
4898 4907 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4899 4908 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4900 4909 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4901 4910
4902 4911 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4903 4912 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4904 4913
4905 4914 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4906 4915 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4907 4916
4908 4917 # task
4909 4918 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4910 4919 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4911 4920 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4912 4921 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4913 4922
4914 4923 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4915 4924 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4916 4925
4917 4926 @hybrid_property
4918 4927 def schedule_type(self):
4919 4928 return self._schedule_type
4920 4929
4921 4930 @schedule_type.setter
4922 4931 def schedule_type(self, val):
4923 4932 if val not in self.schedule_types:
4924 4933 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4925 4934 val, self.schedule_type))
4926 4935
4927 4936 self._schedule_type = val
4928 4937
4929 4938 @classmethod
4930 4939 def get_uid(cls, obj):
4931 4940 args = obj.task_args
4932 4941 kwargs = obj.task_kwargs
4933 4942 if isinstance(args, JsonRaw):
4934 4943 try:
4935 4944 args = json.loads(args)
4936 4945 except ValueError:
4937 4946 args = tuple()
4938 4947
4939 4948 if isinstance(kwargs, JsonRaw):
4940 4949 try:
4941 4950 kwargs = json.loads(kwargs)
4942 4951 except ValueError:
4943 4952 kwargs = dict()
4944 4953
4945 4954 dot_notation = obj.task_dot_notation
4946 4955 val = '.'.join(map(safe_str, [
4947 4956 sorted(dot_notation), args, sorted(kwargs.items())]))
4948 4957 return hashlib.sha1(val).hexdigest()
4949 4958
4950 4959 @classmethod
4951 4960 def get_by_schedule_name(cls, schedule_name):
4952 4961 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4953 4962
4954 4963 @classmethod
4955 4964 def get_by_schedule_id(cls, schedule_id):
4956 4965 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4957 4966
4958 4967 @property
4959 4968 def task(self):
4960 4969 return self.task_dot_notation
4961 4970
4962 4971 @property
4963 4972 def schedule(self):
4964 4973 from rhodecode.lib.celerylib.utils import raw_2_schedule
4965 4974 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4966 4975 return schedule
4967 4976
4968 4977 @property
4969 4978 def args(self):
4970 4979 try:
4971 4980 return list(self.task_args or [])
4972 4981 except ValueError:
4973 4982 return list()
4974 4983
4975 4984 @property
4976 4985 def kwargs(self):
4977 4986 try:
4978 4987 return dict(self.task_kwargs or {})
4979 4988 except ValueError:
4980 4989 return dict()
4981 4990
4982 4991 def _as_raw(self, val):
4983 4992 if hasattr(val, 'de_coerce'):
4984 4993 val = val.de_coerce()
4985 4994 if val:
4986 4995 val = json.dumps(val)
4987 4996
4988 4997 return val
4989 4998
4990 4999 @property
4991 5000 def schedule_definition_raw(self):
4992 5001 return self._as_raw(self.schedule_definition)
4993 5002
4994 5003 @property
4995 5004 def args_raw(self):
4996 5005 return self._as_raw(self.task_args)
4997 5006
4998 5007 @property
4999 5008 def kwargs_raw(self):
5000 5009 return self._as_raw(self.task_kwargs)
5001 5010
5002 5011 def __repr__(self):
5003 5012 return '<DB:ScheduleEntry({}:{})>'.format(
5004 5013 self.schedule_entry_id, self.schedule_name)
5005 5014
5006 5015
5007 5016 @event.listens_for(ScheduleEntry, 'before_update')
5008 5017 def update_task_uid(mapper, connection, target):
5009 5018 target.task_uid = ScheduleEntry.get_uid(target)
5010 5019
5011 5020
5012 5021 @event.listens_for(ScheduleEntry, 'before_insert')
5013 5022 def set_task_uid(mapper, connection, target):
5014 5023 target.task_uid = ScheduleEntry.get_uid(target)
5015 5024
5016 5025
5017 5026 class _BaseBranchPerms(BaseModel):
5018 5027 @classmethod
5019 5028 def compute_hash(cls, value):
5020 5029 return sha1_safe(value)
5021 5030
5022 5031 @hybrid_property
5023 5032 def branch_pattern(self):
5024 5033 return self._branch_pattern or '*'
5025 5034
5026 5035 @hybrid_property
5027 5036 def branch_hash(self):
5028 5037 return self._branch_hash
5029 5038
5030 5039 def _validate_glob(self, value):
5031 5040 re.compile('^' + glob2re(value) + '$')
5032 5041
5033 5042 @branch_pattern.setter
5034 5043 def branch_pattern(self, value):
5035 5044 self._validate_glob(value)
5036 5045 self._branch_pattern = value or '*'
5037 5046 # set the Hash when setting the branch pattern
5038 5047 self._branch_hash = self.compute_hash(self._branch_pattern)
5039 5048
5040 5049 def matches(self, branch):
5041 5050 """
5042 5051 Check if this the branch matches entry
5043 5052
5044 5053 :param branch: branch name for the commit
5045 5054 """
5046 5055
5047 5056 branch = branch or ''
5048 5057
5049 5058 branch_matches = True
5050 5059 if branch:
5051 5060 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
5052 5061 branch_matches = bool(branch_regex.search(branch))
5053 5062
5054 5063 return branch_matches
5055 5064
5056 5065
5057 5066 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
5058 5067 __tablename__ = 'user_to_repo_branch_permissions'
5059 5068 __table_args__ = (
5060 5069 base_table_args
5061 5070 )
5062 5071
5063 5072 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5064 5073
5065 5074 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5066 5075 repo = relationship('Repository', backref='user_branch_perms')
5067 5076
5068 5077 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5069 5078 permission = relationship('Permission')
5070 5079
5071 5080 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
5072 5081 user_repo_to_perm = relationship('UserRepoToPerm')
5073 5082
5074 5083 rule_order = Column('rule_order', Integer(), nullable=False)
5075 5084 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5076 5085 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5077 5086
5078 5087 def __unicode__(self):
5079 5088 return u'<UserBranchPermission(%s => %r)>' % (
5080 5089 self.user_repo_to_perm, self.branch_pattern)
5081 5090
5082 5091
5083 5092 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
5084 5093 __tablename__ = 'user_group_to_repo_branch_permissions'
5085 5094 __table_args__ = (
5086 5095 base_table_args
5087 5096 )
5088 5097
5089 5098 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5090 5099
5091 5100 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5092 5101 repo = relationship('Repository', backref='user_group_branch_perms')
5093 5102
5094 5103 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5095 5104 permission = relationship('Permission')
5096 5105
5097 5106 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)
5098 5107 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
5099 5108
5100 5109 rule_order = Column('rule_order', Integer(), nullable=False)
5101 5110 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5102 5111 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5103 5112
5104 5113 def __unicode__(self):
5105 5114 return u'<UserBranchPermission(%s => %r)>' % (
5106 5115 self.user_group_repo_to_perm, self.branch_pattern)
5107 5116
5108 5117
5109 5118 class UserBookmark(Base, BaseModel):
5110 5119 __tablename__ = 'user_bookmarks'
5111 5120 __table_args__ = (
5112 5121 UniqueConstraint('user_id', 'bookmark_repo_id'),
5113 5122 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5114 5123 UniqueConstraint('user_id', 'bookmark_position'),
5115 5124 base_table_args
5116 5125 )
5117 5126
5118 5127 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5119 5128 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5120 5129 position = Column("bookmark_position", Integer(), nullable=False)
5121 5130 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5122 5131 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5123 5132 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5124 5133
5125 5134 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5126 5135 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5127 5136
5128 5137 user = relationship("User")
5129 5138
5130 5139 repository = relationship("Repository")
5131 5140 repository_group = relationship("RepoGroup")
5132 5141
5133 5142 @classmethod
5134 5143 def get_by_position_for_user(cls, position, user_id):
5135 5144 return cls.query() \
5136 5145 .filter(UserBookmark.user_id == user_id) \
5137 5146 .filter(UserBookmark.position == position).scalar()
5138 5147
5139 5148 @classmethod
5140 5149 def get_bookmarks_for_user(cls, user_id):
5141 5150 return cls.query() \
5142 5151 .filter(UserBookmark.user_id == user_id) \
5143 5152 .options(joinedload(UserBookmark.repository)) \
5144 5153 .options(joinedload(UserBookmark.repository_group)) \
5145 5154 .order_by(UserBookmark.position.asc()) \
5146 5155 .all()
5147 5156
5148 5157 def __unicode__(self):
5149 5158 return u'<UserBookmark(%s @ %r)>' % (self.position, self.redirect_url)
5150 5159
5151 5160
5152 5161 class FileStore(Base, BaseModel):
5153 5162 __tablename__ = 'file_store'
5154 5163 __table_args__ = (
5155 5164 base_table_args
5156 5165 )
5157 5166
5158 5167 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5159 5168 file_uid = Column('file_uid', String(1024), nullable=False)
5160 5169 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5161 5170 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5162 5171 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5163 5172
5164 5173 # sha256 hash
5165 5174 file_hash = Column('file_hash', String(512), nullable=False)
5166 5175 file_size = Column('file_size', BigInteger(), nullable=False)
5167 5176
5168 5177 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5169 5178 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5170 5179 accessed_count = Column('accessed_count', Integer(), default=0)
5171 5180
5172 5181 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5173 5182
5174 5183 # if repo/repo_group reference is set, check for permissions
5175 5184 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5176 5185
5177 5186 # hidden defines an attachment that should be hidden from showing in artifact listing
5178 5187 hidden = Column('hidden', Boolean(), nullable=False, default=False)
5179 5188
5180 5189 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5181 5190 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
5182 5191
5183 5192 file_metadata = relationship('FileStoreMetadata', lazy='joined')
5184 5193
5185 5194 # scope limited to user, which requester have access to
5186 5195 scope_user_id = Column(
5187 5196 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5188 5197 nullable=True, unique=None, default=None)
5189 5198 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
5190 5199
5191 5200 # scope limited to user group, which requester have access to
5192 5201 scope_user_group_id = Column(
5193 5202 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5194 5203 nullable=True, unique=None, default=None)
5195 5204 user_group = relationship('UserGroup', lazy='joined')
5196 5205
5197 5206 # scope limited to repo, which requester have access to
5198 5207 scope_repo_id = Column(
5199 5208 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5200 5209 nullable=True, unique=None, default=None)
5201 5210 repo = relationship('Repository', lazy='joined')
5202 5211
5203 5212 # scope limited to repo group, which requester have access to
5204 5213 scope_repo_group_id = Column(
5205 5214 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5206 5215 nullable=True, unique=None, default=None)
5207 5216 repo_group = relationship('RepoGroup', lazy='joined')
5208 5217
5209 5218 @classmethod
5210 5219 def get_by_store_uid(cls, file_store_uid):
5211 5220 return FileStore.query().filter(FileStore.file_uid == file_store_uid).scalar()
5212 5221
5213 5222 @classmethod
5214 5223 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5215 5224 file_description='', enabled=True, hidden=False, check_acl=True,
5216 5225 user_id=None, scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5217 5226
5218 5227 store_entry = FileStore()
5219 5228 store_entry.file_uid = file_uid
5220 5229 store_entry.file_display_name = file_display_name
5221 5230 store_entry.file_org_name = filename
5222 5231 store_entry.file_size = file_size
5223 5232 store_entry.file_hash = file_hash
5224 5233 store_entry.file_description = file_description
5225 5234
5226 5235 store_entry.check_acl = check_acl
5227 5236 store_entry.enabled = enabled
5228 5237 store_entry.hidden = hidden
5229 5238
5230 5239 store_entry.user_id = user_id
5231 5240 store_entry.scope_user_id = scope_user_id
5232 5241 store_entry.scope_repo_id = scope_repo_id
5233 5242 store_entry.scope_repo_group_id = scope_repo_group_id
5234 5243
5235 5244 return store_entry
5236 5245
5237 5246 @classmethod
5238 5247 def store_metadata(cls, file_store_id, args, commit=True):
5239 5248 file_store = FileStore.get(file_store_id)
5240 5249 if file_store is None:
5241 5250 return
5242 5251
5243 5252 for section, key, value, value_type in args:
5244 5253 has_key = FileStoreMetadata().query() \
5245 5254 .filter(FileStoreMetadata.file_store_id == file_store.file_store_id) \
5246 5255 .filter(FileStoreMetadata.file_store_meta_section == section) \
5247 5256 .filter(FileStoreMetadata.file_store_meta_key == key) \
5248 5257 .scalar()
5249 5258 if has_key:
5250 5259 msg = 'key `{}` already defined under section `{}` for this file.'\
5251 5260 .format(key, section)
5252 5261 raise ArtifactMetadataDuplicate(msg, err_section=section, err_key=key)
5253 5262
5254 5263 # NOTE(marcink): raises ArtifactMetadataBadValueType
5255 5264 FileStoreMetadata.valid_value_type(value_type)
5256 5265
5257 5266 meta_entry = FileStoreMetadata()
5258 5267 meta_entry.file_store = file_store
5259 5268 meta_entry.file_store_meta_section = section
5260 5269 meta_entry.file_store_meta_key = key
5261 5270 meta_entry.file_store_meta_value_type = value_type
5262 5271 meta_entry.file_store_meta_value = value
5263 5272
5264 5273 Session().add(meta_entry)
5265 5274
5266 5275 try:
5267 5276 if commit:
5268 5277 Session().commit()
5269 5278 except IntegrityError:
5270 5279 Session().rollback()
5271 5280 raise ArtifactMetadataDuplicate('Duplicate section/key found for this file.')
5272 5281
5273 5282 @classmethod
5274 5283 def bump_access_counter(cls, file_uid, commit=True):
5275 5284 FileStore().query()\
5276 5285 .filter(FileStore.file_uid == file_uid)\
5277 5286 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5278 5287 FileStore.accessed_on: datetime.datetime.now()})
5279 5288 if commit:
5280 5289 Session().commit()
5281 5290
5282 5291 def __json__(self):
5283 5292 data = {
5284 5293 'filename': self.file_display_name,
5285 5294 'filename_org': self.file_org_name,
5286 5295 'file_uid': self.file_uid,
5287 5296 'description': self.file_description,
5288 5297 'hidden': self.hidden,
5289 5298 'size': self.file_size,
5290 5299 'created_on': self.created_on,
5291 5300 'uploaded_by': self.upload_user.get_api_data(details='basic'),
5292 5301 'downloaded_times': self.accessed_count,
5293 5302 'sha256': self.file_hash,
5294 5303 'metadata': self.file_metadata,
5295 5304 }
5296 5305
5297 5306 return data
5298 5307
5299 5308 def __repr__(self):
5300 5309 return '<FileStore({})>'.format(self.file_store_id)
5301 5310
5302 5311
5303 5312 class FileStoreMetadata(Base, BaseModel):
5304 5313 __tablename__ = 'file_store_metadata'
5305 5314 __table_args__ = (
5306 5315 UniqueConstraint('file_store_id', 'file_store_meta_section_hash', 'file_store_meta_key_hash'),
5307 5316 Index('file_store_meta_section_idx', 'file_store_meta_section', mysql_length=255),
5308 5317 Index('file_store_meta_key_idx', 'file_store_meta_key', mysql_length=255),
5309 5318 base_table_args
5310 5319 )
5311 5320 SETTINGS_TYPES = {
5312 5321 'str': safe_str,
5313 5322 'int': safe_int,
5314 5323 'unicode': safe_unicode,
5315 5324 'bool': str2bool,
5316 5325 'list': functools.partial(aslist, sep=',')
5317 5326 }
5318 5327
5319 5328 file_store_meta_id = Column(
5320 5329 "file_store_meta_id", Integer(), nullable=False, unique=True, default=None,
5321 5330 primary_key=True)
5322 5331 _file_store_meta_section = Column(
5323 5332 "file_store_meta_section", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5324 5333 nullable=True, unique=None, default=None)
5325 5334 _file_store_meta_section_hash = Column(
5326 5335 "file_store_meta_section_hash", String(255),
5327 5336 nullable=True, unique=None, default=None)
5328 5337 _file_store_meta_key = Column(
5329 5338 "file_store_meta_key", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5330 5339 nullable=True, unique=None, default=None)
5331 5340 _file_store_meta_key_hash = Column(
5332 5341 "file_store_meta_key_hash", String(255), nullable=True, unique=None, default=None)
5333 5342 _file_store_meta_value = Column(
5334 5343 "file_store_meta_value", UnicodeText().with_variant(UnicodeText(20480), 'mysql'),
5335 5344 nullable=True, unique=None, default=None)
5336 5345 _file_store_meta_value_type = Column(
5337 5346 "file_store_meta_value_type", String(255), nullable=True, unique=None,
5338 5347 default='unicode')
5339 5348
5340 5349 file_store_id = Column(
5341 5350 'file_store_id', Integer(), ForeignKey('file_store.file_store_id'),
5342 5351 nullable=True, unique=None, default=None)
5343 5352
5344 5353 file_store = relationship('FileStore', lazy='joined')
5345 5354
5346 5355 @classmethod
5347 5356 def valid_value_type(cls, value):
5348 5357 if value.split('.')[0] not in cls.SETTINGS_TYPES:
5349 5358 raise ArtifactMetadataBadValueType(
5350 5359 'value_type must be one of %s got %s' % (cls.SETTINGS_TYPES.keys(), value))
5351 5360
5352 5361 @hybrid_property
5353 5362 def file_store_meta_section(self):
5354 5363 return self._file_store_meta_section
5355 5364
5356 5365 @file_store_meta_section.setter
5357 5366 def file_store_meta_section(self, value):
5358 5367 self._file_store_meta_section = value
5359 5368 self._file_store_meta_section_hash = _hash_key(value)
5360 5369
5361 5370 @hybrid_property
5362 5371 def file_store_meta_key(self):
5363 5372 return self._file_store_meta_key
5364 5373
5365 5374 @file_store_meta_key.setter
5366 5375 def file_store_meta_key(self, value):
5367 5376 self._file_store_meta_key = value
5368 5377 self._file_store_meta_key_hash = _hash_key(value)
5369 5378
5370 5379 @hybrid_property
5371 5380 def file_store_meta_value(self):
5372 5381 val = self._file_store_meta_value
5373 5382
5374 5383 if self._file_store_meta_value_type:
5375 5384 # e.g unicode.encrypted == unicode
5376 5385 _type = self._file_store_meta_value_type.split('.')[0]
5377 5386 # decode the encrypted value if it's encrypted field type
5378 5387 if '.encrypted' in self._file_store_meta_value_type:
5379 5388 cipher = EncryptedTextValue()
5380 5389 val = safe_unicode(cipher.process_result_value(val, None))
5381 5390 # do final type conversion
5382 5391 converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
5383 5392 val = converter(val)
5384 5393
5385 5394 return val
5386 5395
5387 5396 @file_store_meta_value.setter
5388 5397 def file_store_meta_value(self, val):
5389 5398 val = safe_unicode(val)
5390 5399 # encode the encrypted value
5391 5400 if '.encrypted' in self.file_store_meta_value_type:
5392 5401 cipher = EncryptedTextValue()
5393 5402 val = safe_unicode(cipher.process_bind_param(val, None))
5394 5403 self._file_store_meta_value = val
5395 5404
5396 5405 @hybrid_property
5397 5406 def file_store_meta_value_type(self):
5398 5407 return self._file_store_meta_value_type
5399 5408
5400 5409 @file_store_meta_value_type.setter
5401 5410 def file_store_meta_value_type(self, val):
5402 5411 # e.g unicode.encrypted
5403 5412 self.valid_value_type(val)
5404 5413 self._file_store_meta_value_type = val
5405 5414
5406 5415 def __json__(self):
5407 5416 data = {
5408 5417 'artifact': self.file_store.file_uid,
5409 5418 'section': self.file_store_meta_section,
5410 5419 'key': self.file_store_meta_key,
5411 5420 'value': self.file_store_meta_value,
5412 5421 }
5413 5422
5414 5423 return data
5415 5424
5416 5425 def __repr__(self):
5417 5426 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.file_store_meta_section,
5418 5427 self.file_store_meta_key, self.file_store_meta_value)
5419 5428
5420 5429
5421 5430 class DbMigrateVersion(Base, BaseModel):
5422 5431 __tablename__ = 'db_migrate_version'
5423 5432 __table_args__ = (
5424 5433 base_table_args,
5425 5434 )
5426 5435
5427 5436 repository_id = Column('repository_id', String(250), primary_key=True)
5428 5437 repository_path = Column('repository_path', Text)
5429 5438 version = Column('version', Integer)
5430 5439
5431 5440 @classmethod
5432 5441 def set_version(cls, version):
5433 5442 """
5434 5443 Helper for forcing a different version, usually for debugging purposes via ishell.
5435 5444 """
5436 5445 ver = DbMigrateVersion.query().first()
5437 5446 ver.version = version
5438 5447 Session().commit()
5439 5448
5440 5449
5441 5450 class DbSession(Base, BaseModel):
5442 5451 __tablename__ = 'db_session'
5443 5452 __table_args__ = (
5444 5453 base_table_args,
5445 5454 )
5446 5455
5447 5456 def __repr__(self):
5448 5457 return '<DB:DbSession({})>'.format(self.id)
5449 5458
5450 5459 id = Column('id', Integer())
5451 5460 namespace = Column('namespace', String(255), primary_key=True)
5452 5461 accessed = Column('accessed', DateTime, nullable=False)
5453 5462 created = Column('created', DateTime, nullable=False)
5454 5463 data = Column('data', PickleType, nullable=False)
@@ -1,2925 +1,2937 b''
1 1 //Primary CSS
2 2
3 3 //--- IMPORTS ------------------//
4 4
5 5 @import 'helpers';
6 6 @import 'mixins';
7 7 @import 'rcicons';
8 8 @import 'variables';
9 9 @import 'bootstrap-variables';
10 10 @import 'form-bootstrap';
11 11 @import 'codemirror';
12 12 @import 'legacy_code_styles';
13 13 @import 'readme-box';
14 14 @import 'progress-bar';
15 15
16 16 @import 'type';
17 17 @import 'alerts';
18 18 @import 'buttons';
19 19 @import 'tags';
20 20 @import 'code-block';
21 21 @import 'examples';
22 22 @import 'login';
23 23 @import 'main-content';
24 24 @import 'select2';
25 25 @import 'comments';
26 26 @import 'panels-bootstrap';
27 27 @import 'panels';
28 28 @import 'deform';
29 29 @import 'tooltips';
30 30
31 31 //--- BASE ------------------//
32 32 .noscript-error {
33 33 top: 0;
34 34 left: 0;
35 35 width: 100%;
36 36 z-index: 101;
37 37 text-align: center;
38 38 font-size: 120%;
39 39 color: white;
40 40 background-color: @alert2;
41 41 padding: 5px 0 5px 0;
42 42 font-weight: @text-semibold-weight;
43 43 font-family: @text-semibold;
44 44 }
45 45
46 46 html {
47 47 display: table;
48 48 height: 100%;
49 49 width: 100%;
50 50 }
51 51
52 52 body {
53 53 display: table-cell;
54 54 width: 100%;
55 55 }
56 56
57 57 //--- LAYOUT ------------------//
58 58
59 59 .hidden{
60 60 display: none !important;
61 61 }
62 62
63 63 .box{
64 64 float: left;
65 65 width: 100%;
66 66 }
67 67
68 68 .browser-header {
69 69 clear: both;
70 70 }
71 71 .main {
72 72 clear: both;
73 73 padding:0 0 @pagepadding;
74 74 height: auto;
75 75
76 76 &:after { //clearfix
77 77 content:"";
78 78 clear:both;
79 79 width:100%;
80 80 display:block;
81 81 }
82 82 }
83 83
84 84 .action-link{
85 85 margin-left: @padding;
86 86 padding-left: @padding;
87 87 border-left: @border-thickness solid @border-default-color;
88 88 }
89 89
90 90 input + .action-link, .action-link.first{
91 91 border-left: none;
92 92 }
93 93
94 94 .action-link.last{
95 95 margin-right: @padding;
96 96 padding-right: @padding;
97 97 }
98 98
99 99 .action-link.active,
100 100 .action-link.active a{
101 101 color: @grey4;
102 102 }
103 103
104 104 .action-link.disabled {
105 105 color: @grey4;
106 106 cursor: inherit;
107 107 }
108 108
109 109
110 110 .clipboard-action {
111 111 cursor: pointer;
112 112 margin-left: 5px;
113 113
114 114 &:not(.no-grey) {
115 115
116 116 &:hover {
117 117 color: @grey2;
118 118 }
119 119 color: @grey4;
120 120 }
121 121 }
122 122
123 123 ul.simple-list{
124 124 list-style: none;
125 125 margin: 0;
126 126 padding: 0;
127 127 }
128 128
129 129 .main-content {
130 130 padding-bottom: @pagepadding;
131 131 }
132 132
133 133 .wide-mode-wrapper {
134 134 max-width:4000px !important;
135 135 }
136 136
137 137 .wrapper {
138 138 position: relative;
139 139 max-width: @wrapper-maxwidth;
140 140 margin: 0 auto;
141 141 }
142 142
143 143 #content {
144 144 clear: both;
145 145 padding: 0 @contentpadding;
146 146 }
147 147
148 148 .advanced-settings-fields{
149 149 input{
150 150 margin-left: @textmargin;
151 151 margin-right: @padding/2;
152 152 }
153 153 }
154 154
155 155 .cs_files_title {
156 156 margin: @pagepadding 0 0;
157 157 }
158 158
159 159 input.inline[type="file"] {
160 160 display: inline;
161 161 }
162 162
163 163 .error_page {
164 164 margin: 10% auto;
165 165
166 166 h1 {
167 167 color: @grey2;
168 168 }
169 169
170 170 .alert {
171 171 margin: @padding 0;
172 172 }
173 173
174 174 .error-branding {
175 175 color: @grey4;
176 176 font-weight: @text-semibold-weight;
177 177 font-family: @text-semibold;
178 178 }
179 179
180 180 .error_message {
181 181 font-family: @text-regular;
182 182 }
183 183
184 184 .sidebar {
185 185 min-height: 275px;
186 186 margin: 0;
187 187 padding: 0 0 @sidebarpadding @sidebarpadding;
188 188 border: none;
189 189 }
190 190
191 191 .main-content {
192 192 position: relative;
193 193 margin: 0 @sidebarpadding @sidebarpadding;
194 194 padding: 0 0 0 @sidebarpadding;
195 195 border-left: @border-thickness solid @grey5;
196 196
197 197 @media (max-width:767px) {
198 198 clear: both;
199 199 width: 100%;
200 200 margin: 0;
201 201 border: none;
202 202 }
203 203 }
204 204
205 205 .inner-column {
206 206 float: left;
207 207 width: 29.75%;
208 208 min-height: 150px;
209 209 margin: @sidebarpadding 2% 0 0;
210 210 padding: 0 2% 0 0;
211 211 border-right: @border-thickness solid @grey5;
212 212
213 213 @media (max-width:767px) {
214 214 clear: both;
215 215 width: 100%;
216 216 border: none;
217 217 }
218 218
219 219 ul {
220 220 padding-left: 1.25em;
221 221 }
222 222
223 223 &:last-child {
224 224 margin: @sidebarpadding 0 0;
225 225 border: none;
226 226 }
227 227
228 228 h4 {
229 229 margin: 0 0 @padding;
230 230 font-weight: @text-semibold-weight;
231 231 font-family: @text-semibold;
232 232 }
233 233 }
234 234 }
235 235 .error-page-logo {
236 236 width: 130px;
237 237 height: 160px;
238 238 }
239 239
240 240 // HEADER
241 241 .header {
242 242
243 243 // TODO: johbo: Fix login pages, so that they work without a min-height
244 244 // for the header and then remove the min-height. I chose a smaller value
245 245 // intentionally here to avoid rendering issues in the main navigation.
246 246 min-height: 49px;
247 247 min-width: 1024px;
248 248
249 249 position: relative;
250 250 vertical-align: bottom;
251 251 padding: 0 @header-padding;
252 252 background-color: @grey1;
253 253 color: @grey5;
254 254
255 255 .title {
256 256 overflow: visible;
257 257 }
258 258
259 259 &:before,
260 260 &:after {
261 261 content: "";
262 262 clear: both;
263 263 width: 100%;
264 264 }
265 265
266 266 // TODO: johbo: Avoids breaking "Repositories" chooser
267 267 .select2-container .select2-choice .select2-arrow {
268 268 display: none;
269 269 }
270 270 }
271 271
272 272 #header-inner {
273 273 &.title {
274 274 margin: 0;
275 275 }
276 276 &:before,
277 277 &:after {
278 278 content: "";
279 279 clear: both;
280 280 }
281 281 }
282 282
283 283 // Gists
284 284 #files_data {
285 285 clear: both; //for firefox
286 286 padding-top: 10px;
287 287 }
288 288
289 289 #gistid {
290 290 margin-right: @padding;
291 291 }
292 292
293 293 // Global Settings Editor
294 294 .textarea.editor {
295 295 float: left;
296 296 position: relative;
297 297 max-width: @texteditor-width;
298 298
299 299 select {
300 300 position: absolute;
301 301 top:10px;
302 302 right:0;
303 303 }
304 304
305 305 .CodeMirror {
306 306 margin: 0;
307 307 }
308 308
309 309 .help-block {
310 310 margin: 0 0 @padding;
311 311 padding:.5em;
312 312 background-color: @grey6;
313 313 &.pre-formatting {
314 314 white-space: pre;
315 315 }
316 316 }
317 317 }
318 318
319 319 ul.auth_plugins {
320 320 margin: @padding 0 @padding @legend-width;
321 321 padding: 0;
322 322
323 323 li {
324 324 margin-bottom: @padding;
325 325 line-height: 1em;
326 326 list-style-type: none;
327 327
328 328 .auth_buttons .btn {
329 329 margin-right: @padding;
330 330 }
331 331
332 332 }
333 333 }
334 334
335 335
336 336 // My Account PR list
337 337
338 338 #show_closed {
339 339 margin: 0 1em 0 0;
340 340 }
341 341
342 342 #pull_request_list_table {
343 343 .closed {
344 344 background-color: @grey6;
345 345 }
346 346
347 347 .state-creating,
348 348 .state-updating,
349 349 .state-merging
350 350 {
351 351 background-color: @grey6;
352 352 }
353 353
354 354 .td-status {
355 355 padding-left: .5em;
356 356 }
357 357 .log-container .truncate {
358 358 height: 2.75em;
359 359 white-space: pre-line;
360 360 }
361 361 table.rctable .user {
362 362 padding-left: 0;
363 363 }
364 364 table.rctable {
365 365 td.td-description,
366 366 .rc-user {
367 367 min-width: auto;
368 368 }
369 369 }
370 370 }
371 371
372 372 // Pull Requests
373 373
374 374 .pullrequests_section_head {
375 375 display: block;
376 376 clear: both;
377 377 margin: @padding 0;
378 378 font-weight: @text-bold-weight;
379 379 font-family: @text-bold;
380 380 }
381 381
382 382 .pr-origininfo, .pr-targetinfo {
383 383 position: relative;
384 384
385 385 .tag {
386 386 display: inline-block;
387 387 margin: 0 1em .5em 0;
388 388 }
389 389
390 390 .clone-url {
391 391 display: inline-block;
392 392 margin: 0 0 .5em 0;
393 393 padding: 0;
394 394 line-height: 1.2em;
395 395 }
396 396 }
397 397
398 398 .pr-mergeinfo {
399 399 min-width: 95% !important;
400 400 padding: 0 !important;
401 401 border: 0;
402 402 }
403 403 .pr-mergeinfo-copy {
404 404 padding: 0 0;
405 405 }
406 406
407 407 .pr-pullinfo {
408 408 min-width: 95% !important;
409 409 padding: 0 !important;
410 410 border: 0;
411 411 }
412 412 .pr-pullinfo-copy {
413 413 padding: 0 0;
414 414 }
415 415
416 416
417 #pr-title-input {
418 width: 72%;
417 .pr-title-input {
418 width: 80%;
419 419 font-size: 1em;
420 margin: 0;
421 padding: 0 0 0 @padding/4;
420 margin: 0 0 4px 0;
421 padding: 0;
422 422 line-height: 1.7em;
423 423 color: @text-color;
424 424 letter-spacing: .02em;
425 425 font-weight: @text-bold-weight;
426 426 font-family: @text-bold;
427
428 &:hover {
429 box-shadow: none;
430 }
431 }
432
433 #pr-title {
434 input {
435 border: 1px transparent;
436 color: black;
437 opacity: 1
438 }
427 439 }
428 440
429 441 #pullrequest_title {
430 442 width: 100%;
431 443 box-sizing: border-box;
432 444 }
433 445
434 446 #pr_open_message {
435 447 border: @border-thickness solid #fff;
436 448 border-radius: @border-radius;
437 449 padding: @padding-large-vertical @padding-large-vertical @padding-large-vertical 0;
438 450 text-align: left;
439 451 overflow: hidden;
440 452 }
441 453
442 454 .pr-submit-button {
443 455 float: right;
444 456 margin: 0 0 0 5px;
445 457 }
446 458
447 459 .pr-spacing-container {
448 460 padding: 20px;
449 461 clear: both
450 462 }
451 463
452 464 #pr-description-input {
453 465 margin-bottom: 0;
454 466 }
455 467
456 468 .pr-description-label {
457 469 vertical-align: top;
458 470 }
459 471
460 472 .perms_section_head {
461 473 min-width: 625px;
462 474
463 475 h2 {
464 476 margin-bottom: 0;
465 477 }
466 478
467 479 .label-checkbox {
468 480 float: left;
469 481 }
470 482
471 483 &.field {
472 484 margin: @space 0 @padding;
473 485 }
474 486
475 487 &:first-child.field {
476 488 margin-top: 0;
477 489
478 490 .label {
479 491 margin-top: 0;
480 492 padding-top: 0;
481 493 }
482 494
483 495 .radios {
484 496 padding-top: 0;
485 497 }
486 498 }
487 499
488 500 .radios {
489 501 position: relative;
490 502 width: 505px;
491 503 }
492 504 }
493 505
494 506 //--- MODULES ------------------//
495 507
496 508
497 509 // Server Announcement
498 510 #server-announcement {
499 511 width: 95%;
500 512 margin: @padding auto;
501 513 padding: @padding;
502 514 border-width: 2px;
503 515 border-style: solid;
504 516 .border-radius(2px);
505 517 font-weight: @text-bold-weight;
506 518 font-family: @text-bold;
507 519
508 520 &.info { border-color: @alert4; background-color: @alert4-inner; }
509 521 &.warning { border-color: @alert3; background-color: @alert3-inner; }
510 522 &.error { border-color: @alert2; background-color: @alert2-inner; }
511 523 &.success { border-color: @alert1; background-color: @alert1-inner; }
512 524 &.neutral { border-color: @grey3; background-color: @grey6; }
513 525 }
514 526
515 527 // Fixed Sidebar Column
516 528 .sidebar-col-wrapper {
517 529 padding-left: @sidebar-all-width;
518 530
519 531 .sidebar {
520 532 width: @sidebar-width;
521 533 margin-left: -@sidebar-all-width;
522 534 }
523 535 }
524 536
525 537 .sidebar-col-wrapper.scw-small {
526 538 padding-left: @sidebar-small-all-width;
527 539
528 540 .sidebar {
529 541 width: @sidebar-small-width;
530 542 margin-left: -@sidebar-small-all-width;
531 543 }
532 544 }
533 545
534 546
535 547 // FOOTER
536 548 #footer {
537 549 padding: 0;
538 550 text-align: center;
539 551 vertical-align: middle;
540 552 color: @grey2;
541 553 font-size: 11px;
542 554
543 555 p {
544 556 margin: 0;
545 557 padding: 1em;
546 558 line-height: 1em;
547 559 }
548 560
549 561 .server-instance { //server instance
550 562 display: none;
551 563 }
552 564
553 565 .title {
554 566 float: none;
555 567 margin: 0 auto;
556 568 }
557 569 }
558 570
559 571 button.close {
560 572 padding: 0;
561 573 cursor: pointer;
562 574 background: transparent;
563 575 border: 0;
564 576 .box-shadow(none);
565 577 -webkit-appearance: none;
566 578 }
567 579
568 580 .close {
569 581 float: right;
570 582 font-size: 21px;
571 583 font-family: @text-bootstrap;
572 584 line-height: 1em;
573 585 font-weight: bold;
574 586 color: @grey2;
575 587
576 588 &:hover,
577 589 &:focus {
578 590 color: @grey1;
579 591 text-decoration: none;
580 592 cursor: pointer;
581 593 }
582 594 }
583 595
584 596 // GRID
585 597 .sorting,
586 598 .sorting_desc,
587 599 .sorting_asc {
588 600 cursor: pointer;
589 601 }
590 602 .sorting_desc:after {
591 603 content: "\00A0\25B2";
592 604 font-size: .75em;
593 605 }
594 606 .sorting_asc:after {
595 607 content: "\00A0\25BC";
596 608 font-size: .68em;
597 609 }
598 610
599 611
600 612 .user_auth_tokens {
601 613
602 614 &.truncate {
603 615 white-space: nowrap;
604 616 overflow: hidden;
605 617 text-overflow: ellipsis;
606 618 }
607 619
608 620 .fields .field .input {
609 621 margin: 0;
610 622 }
611 623
612 624 input#description {
613 625 width: 100px;
614 626 margin: 0;
615 627 }
616 628
617 629 .drop-menu {
618 630 // TODO: johbo: Remove this, should work out of the box when
619 631 // having multiple inputs inline
620 632 margin: 0 0 0 5px;
621 633 }
622 634 }
623 635 #user_list_table {
624 636 .closed {
625 637 background-color: @grey6;
626 638 }
627 639 }
628 640
629 641
630 642 input, textarea {
631 643 &.disabled {
632 644 opacity: .5;
633 645 }
634 646
635 647 &:hover {
636 648 border-color: @grey3;
637 649 box-shadow: @button-shadow;
638 650 }
639 651
640 652 &:focus {
641 653 border-color: @rcblue;
642 654 box-shadow: @button-shadow;
643 655 }
644 656 }
645 657
646 658 // remove extra padding in firefox
647 659 input::-moz-focus-inner { border:0; padding:0 }
648 660
649 661 .adjacent input {
650 662 margin-bottom: @padding;
651 663 }
652 664
653 665 .permissions_boxes {
654 666 display: block;
655 667 }
656 668
657 669 //FORMS
658 670
659 671 .medium-inline,
660 672 input#description.medium-inline {
661 673 display: inline;
662 674 width: @medium-inline-input-width;
663 675 min-width: 100px;
664 676 }
665 677
666 678 select {
667 679 //reset
668 680 -webkit-appearance: none;
669 681 -moz-appearance: none;
670 682
671 683 display: inline-block;
672 684 height: 28px;
673 685 width: auto;
674 686 margin: 0 @padding @padding 0;
675 687 padding: 0 18px 0 8px;
676 688 line-height:1em;
677 689 font-size: @basefontsize;
678 690 border: @border-thickness solid @grey5;
679 691 border-radius: @border-radius;
680 692 background:white url("../images/dt-arrow-dn.png") no-repeat 100% 50%;
681 693 color: @grey4;
682 694 box-shadow: @button-shadow;
683 695
684 696 &:after {
685 697 content: "\00A0\25BE";
686 698 }
687 699
688 700 &:focus, &:hover {
689 701 outline: none;
690 702 border-color: @grey4;
691 703 color: @rcdarkblue;
692 704 }
693 705 }
694 706
695 707 option {
696 708 &:focus {
697 709 outline: none;
698 710 }
699 711 }
700 712
701 713 input,
702 714 textarea {
703 715 padding: @input-padding;
704 716 border: @input-border-thickness solid @border-highlight-color;
705 717 .border-radius (@border-radius);
706 718 font-family: @text-light;
707 719 font-size: @basefontsize;
708 720
709 721 &.input-sm {
710 722 padding: 5px;
711 723 }
712 724
713 725 &#description {
714 726 min-width: @input-description-minwidth;
715 727 min-height: 1em;
716 728 padding: 10px;
717 729 }
718 730 }
719 731
720 732 .field-sm {
721 733 input,
722 734 textarea {
723 735 padding: 5px;
724 736 }
725 737 }
726 738
727 739 textarea {
728 740 display: block;
729 741 clear: both;
730 742 width: 100%;
731 743 min-height: 100px;
732 744 margin-bottom: @padding;
733 745 .box-sizing(border-box);
734 746 overflow: auto;
735 747 }
736 748
737 749 label {
738 750 font-family: @text-light;
739 751 }
740 752
741 753 // GRAVATARS
742 754 // centers gravatar on username to the right
743 755
744 756 .gravatar {
745 757 display: inline;
746 758 min-width: 16px;
747 759 min-height: 16px;
748 760 margin: -5px 0;
749 761 padding: 0;
750 762 line-height: 1em;
751 763 box-sizing: content-box;
752 764 border-radius: 50%;
753 765
754 766 &.gravatar-large {
755 767 margin: -0.5em .25em -0.5em 0;
756 768 }
757 769
758 770 & + .user {
759 771 display: inline;
760 772 margin: 0;
761 773 padding: 0 0 0 .17em;
762 774 line-height: 1em;
763 775 }
764 776 }
765 777
766 778 .user-inline-data {
767 779 display: inline-block;
768 780 float: left;
769 781 padding-left: .5em;
770 782 line-height: 1.3em;
771 783 }
772 784
773 785 .rc-user { // gravatar + user wrapper
774 786 float: left;
775 787 position: relative;
776 788 min-width: 100px;
777 789 max-width: 200px;
778 790 min-height: (@gravatar-size + @border-thickness * 2); // account for border
779 791 display: block;
780 792 padding: 0 0 0 (@gravatar-size + @basefontsize/2 + @border-thickness * 2);
781 793
782 794
783 795 .gravatar {
784 796 display: block;
785 797 position: absolute;
786 798 top: 0;
787 799 left: 0;
788 800 min-width: @gravatar-size;
789 801 min-height: @gravatar-size;
790 802 margin: 0;
791 803 }
792 804
793 805 .user {
794 806 display: block;
795 807 max-width: 175px;
796 808 padding-top: 2px;
797 809 overflow: hidden;
798 810 text-overflow: ellipsis;
799 811 }
800 812 }
801 813
802 814 .gist-gravatar,
803 815 .journal_container {
804 816 .gravatar-large {
805 817 margin: 0 .5em -10px 0;
806 818 }
807 819 }
808 820
809 821 .gist-type-fields {
810 822 line-height: 30px;
811 823 height: 30px;
812 824
813 825 .gist-type-fields-wrapper {
814 826 vertical-align: middle;
815 827 display: inline-block;
816 828 line-height: 25px;
817 829 }
818 830 }
819 831
820 832 // ADMIN SETTINGS
821 833
822 834 // Tag Patterns
823 835 .tag_patterns {
824 836 .tag_input {
825 837 margin-bottom: @padding;
826 838 }
827 839 }
828 840
829 841 .locked_input {
830 842 position: relative;
831 843
832 844 input {
833 845 display: inline;
834 846 margin: 3px 5px 0px 0px;
835 847 }
836 848
837 849 br {
838 850 display: none;
839 851 }
840 852
841 853 .error-message {
842 854 float: left;
843 855 width: 100%;
844 856 }
845 857
846 858 .lock_input_button {
847 859 display: inline;
848 860 }
849 861
850 862 .help-block {
851 863 clear: both;
852 864 }
853 865 }
854 866
855 867 // Notifications
856 868
857 869 .notifications_buttons {
858 870 margin: 0 0 @space 0;
859 871 padding: 0;
860 872
861 873 .btn {
862 874 display: inline-block;
863 875 }
864 876 }
865 877
866 878 .notification-list {
867 879
868 880 div {
869 881 vertical-align: middle;
870 882 }
871 883
872 884 .container {
873 885 display: block;
874 886 margin: 0 0 @padding 0;
875 887 }
876 888
877 889 .delete-notifications {
878 890 margin-left: @padding;
879 891 text-align: right;
880 892 cursor: pointer;
881 893 }
882 894
883 895 .read-notifications {
884 896 margin-left: @padding/2;
885 897 text-align: right;
886 898 width: 35px;
887 899 cursor: pointer;
888 900 }
889 901
890 902 .icon-minus-sign {
891 903 color: @alert2;
892 904 }
893 905
894 906 .icon-ok-sign {
895 907 color: @alert1;
896 908 }
897 909 }
898 910
899 911 .user_settings {
900 912 float: left;
901 913 clear: both;
902 914 display: block;
903 915 width: 100%;
904 916
905 917 .gravatar_box {
906 918 margin-bottom: @padding;
907 919
908 920 &:after {
909 921 content: " ";
910 922 clear: both;
911 923 width: 100%;
912 924 }
913 925 }
914 926
915 927 .fields .field {
916 928 clear: both;
917 929 }
918 930 }
919 931
920 932 .advanced_settings {
921 933 margin-bottom: @space;
922 934
923 935 .help-block {
924 936 margin-left: 0;
925 937 }
926 938
927 939 button + .help-block {
928 940 margin-top: @padding;
929 941 }
930 942 }
931 943
932 944 // admin settings radio buttons and labels
933 945 .label-2 {
934 946 float: left;
935 947 width: @label2-width;
936 948
937 949 label {
938 950 color: @grey1;
939 951 }
940 952 }
941 953 .checkboxes {
942 954 float: left;
943 955 width: @checkboxes-width;
944 956 margin-bottom: @padding;
945 957
946 958 .checkbox {
947 959 width: 100%;
948 960
949 961 label {
950 962 margin: 0;
951 963 padding: 0;
952 964 }
953 965 }
954 966
955 967 .checkbox + .checkbox {
956 968 display: inline-block;
957 969 }
958 970
959 971 label {
960 972 margin-right: 1em;
961 973 }
962 974 }
963 975
964 976 // CHANGELOG
965 977 .container_header {
966 978 float: left;
967 979 display: block;
968 980 width: 100%;
969 981 margin: @padding 0 @padding;
970 982
971 983 #filter_changelog {
972 984 float: left;
973 985 margin-right: @padding;
974 986 }
975 987
976 988 .breadcrumbs_light {
977 989 display: inline-block;
978 990 }
979 991 }
980 992
981 993 .info_box {
982 994 float: right;
983 995 }
984 996
985 997
986 998
987 999 #graph_content{
988 1000
989 1001 // adjust for table headers so that graph renders properly
990 1002 // #graph_nodes padding - table cell padding
991 1003 padding-top: (@space - (@basefontsize * 2.4));
992 1004
993 1005 &.graph_full_width {
994 1006 width: 100%;
995 1007 max-width: 100%;
996 1008 }
997 1009 }
998 1010
999 1011 #graph {
1000 1012
1001 1013 .pagination-left {
1002 1014 float: left;
1003 1015 clear: both;
1004 1016 }
1005 1017
1006 1018 .log-container {
1007 1019 max-width: 345px;
1008 1020
1009 1021 .message{
1010 1022 max-width: 340px;
1011 1023 }
1012 1024 }
1013 1025
1014 1026 .graph-col-wrapper {
1015 1027
1016 1028 #graph_nodes {
1017 1029 width: 100px;
1018 1030 position: absolute;
1019 1031 left: 70px;
1020 1032 z-index: -1;
1021 1033 }
1022 1034 }
1023 1035
1024 1036 .load-more-commits {
1025 1037 text-align: center;
1026 1038 }
1027 1039 .load-more-commits:hover {
1028 1040 background-color: @grey7;
1029 1041 }
1030 1042 .load-more-commits {
1031 1043 a {
1032 1044 display: block;
1033 1045 }
1034 1046 }
1035 1047 }
1036 1048
1037 1049 .obsolete-toggle {
1038 1050 line-height: 30px;
1039 1051 margin-left: -15px;
1040 1052 }
1041 1053
1042 1054 #rev_range_container, #rev_range_clear, #rev_range_more {
1043 1055 margin-top: -5px;
1044 1056 margin-bottom: -5px;
1045 1057 }
1046 1058
1047 1059 #filter_changelog {
1048 1060 float: left;
1049 1061 }
1050 1062
1051 1063
1052 1064 //--- THEME ------------------//
1053 1065
1054 1066 #logo {
1055 1067 float: left;
1056 1068 margin: 9px 0 0 0;
1057 1069
1058 1070 .header {
1059 1071 background-color: transparent;
1060 1072 }
1061 1073
1062 1074 a {
1063 1075 display: inline-block;
1064 1076 }
1065 1077
1066 1078 img {
1067 1079 height:30px;
1068 1080 }
1069 1081 }
1070 1082
1071 1083 .logo-wrapper {
1072 1084 float:left;
1073 1085 }
1074 1086
1075 1087 .branding {
1076 1088 float: left;
1077 1089 padding: 9px 2px;
1078 1090 line-height: 1em;
1079 1091 font-size: @navigation-fontsize;
1080 1092
1081 1093 a {
1082 1094 color: @grey5
1083 1095 }
1084 1096 @media screen and (max-width: 1200px) {
1085 1097 display: none;
1086 1098 }
1087 1099 }
1088 1100
1089 1101 img {
1090 1102 border: none;
1091 1103 outline: none;
1092 1104 }
1093 1105 user-profile-header
1094 1106 label {
1095 1107
1096 1108 input[type="checkbox"] {
1097 1109 margin-right: 1em;
1098 1110 }
1099 1111 input[type="radio"] {
1100 1112 margin-right: 1em;
1101 1113 }
1102 1114 }
1103 1115
1104 1116 .review-status {
1105 1117 &.under_review {
1106 1118 color: @alert3;
1107 1119 }
1108 1120 &.approved {
1109 1121 color: @alert1;
1110 1122 }
1111 1123 &.rejected,
1112 1124 &.forced_closed{
1113 1125 color: @alert2;
1114 1126 }
1115 1127 &.not_reviewed {
1116 1128 color: @grey5;
1117 1129 }
1118 1130 }
1119 1131
1120 1132 .review-status-under_review {
1121 1133 color: @alert3;
1122 1134 }
1123 1135 .status-tag-under_review {
1124 1136 border-color: @alert3;
1125 1137 }
1126 1138
1127 1139 .review-status-approved {
1128 1140 color: @alert1;
1129 1141 }
1130 1142 .status-tag-approved {
1131 1143 border-color: @alert1;
1132 1144 }
1133 1145
1134 1146 .review-status-rejected,
1135 1147 .review-status-forced_closed {
1136 1148 color: @alert2;
1137 1149 }
1138 1150 .status-tag-rejected,
1139 1151 .status-tag-forced_closed {
1140 1152 border-color: @alert2;
1141 1153 }
1142 1154
1143 1155 .review-status-not_reviewed {
1144 1156 color: @grey5;
1145 1157 }
1146 1158 .status-tag-not_reviewed {
1147 1159 border-color: @grey5;
1148 1160 }
1149 1161
1150 1162 .test_pattern_preview {
1151 1163 margin: @space 0;
1152 1164
1153 1165 p {
1154 1166 margin-bottom: 0;
1155 1167 border-bottom: @border-thickness solid @border-default-color;
1156 1168 color: @grey3;
1157 1169 }
1158 1170
1159 1171 .btn {
1160 1172 margin-bottom: @padding;
1161 1173 }
1162 1174 }
1163 1175 #test_pattern_result {
1164 1176 display: none;
1165 1177 &:extend(pre);
1166 1178 padding: .9em;
1167 1179 color: @grey3;
1168 1180 background-color: @grey7;
1169 1181 border-right: @border-thickness solid @border-default-color;
1170 1182 border-bottom: @border-thickness solid @border-default-color;
1171 1183 border-left: @border-thickness solid @border-default-color;
1172 1184 }
1173 1185
1174 1186 #repo_vcs_settings {
1175 1187 #inherit_overlay_vcs_default {
1176 1188 display: none;
1177 1189 }
1178 1190 #inherit_overlay_vcs_custom {
1179 1191 display: custom;
1180 1192 }
1181 1193 &.inherited {
1182 1194 #inherit_overlay_vcs_default {
1183 1195 display: block;
1184 1196 }
1185 1197 #inherit_overlay_vcs_custom {
1186 1198 display: none;
1187 1199 }
1188 1200 }
1189 1201 }
1190 1202
1191 1203 .issue-tracker-link {
1192 1204 color: @rcblue;
1193 1205 }
1194 1206
1195 1207 // Issue Tracker Table Show/Hide
1196 1208 #repo_issue_tracker {
1197 1209 #inherit_overlay {
1198 1210 display: none;
1199 1211 }
1200 1212 #custom_overlay {
1201 1213 display: custom;
1202 1214 }
1203 1215 &.inherited {
1204 1216 #inherit_overlay {
1205 1217 display: block;
1206 1218 }
1207 1219 #custom_overlay {
1208 1220 display: none;
1209 1221 }
1210 1222 }
1211 1223 }
1212 1224 table.issuetracker {
1213 1225 &.readonly {
1214 1226 tr, td {
1215 1227 color: @grey3;
1216 1228 }
1217 1229 }
1218 1230 .edit {
1219 1231 display: none;
1220 1232 }
1221 1233 .editopen {
1222 1234 .edit {
1223 1235 display: inline;
1224 1236 }
1225 1237 .entry {
1226 1238 display: none;
1227 1239 }
1228 1240 }
1229 1241 tr td.td-action {
1230 1242 min-width: 117px;
1231 1243 }
1232 1244 td input {
1233 1245 max-width: none;
1234 1246 min-width: 30px;
1235 1247 width: 80%;
1236 1248 }
1237 1249 .issuetracker_pref input {
1238 1250 width: 40%;
1239 1251 }
1240 1252 input.edit_issuetracker_update {
1241 1253 margin-right: 0;
1242 1254 width: auto;
1243 1255 }
1244 1256 }
1245 1257
1246 1258 table.integrations {
1247 1259 .td-icon {
1248 1260 width: 20px;
1249 1261 .integration-icon {
1250 1262 height: 20px;
1251 1263 width: 20px;
1252 1264 }
1253 1265 }
1254 1266 }
1255 1267
1256 1268 .integrations {
1257 1269 a.integration-box {
1258 1270 color: @text-color;
1259 1271 &:hover {
1260 1272 .panel {
1261 1273 background: #fbfbfb;
1262 1274 }
1263 1275 }
1264 1276 .integration-icon {
1265 1277 width: 30px;
1266 1278 height: 30px;
1267 1279 margin-right: 20px;
1268 1280 float: left;
1269 1281 }
1270 1282
1271 1283 .panel-body {
1272 1284 padding: 10px;
1273 1285 }
1274 1286 .panel {
1275 1287 margin-bottom: 10px;
1276 1288 }
1277 1289 h2 {
1278 1290 display: inline-block;
1279 1291 margin: 0;
1280 1292 min-width: 140px;
1281 1293 }
1282 1294 }
1283 1295 a.integration-box.dummy-integration {
1284 1296 color: @grey4
1285 1297 }
1286 1298 }
1287 1299
1288 1300 //Permissions Settings
1289 1301 #add_perm {
1290 1302 margin: 0 0 @padding;
1291 1303 cursor: pointer;
1292 1304 }
1293 1305
1294 1306 .perm_ac {
1295 1307 input {
1296 1308 width: 95%;
1297 1309 }
1298 1310 }
1299 1311
1300 1312 .autocomplete-suggestions {
1301 1313 width: auto !important; // overrides autocomplete.js
1302 1314 min-width: 278px;
1303 1315 margin: 0;
1304 1316 border: @border-thickness solid @grey5;
1305 1317 border-radius: @border-radius;
1306 1318 color: @grey2;
1307 1319 background-color: white;
1308 1320 }
1309 1321
1310 1322 .autocomplete-qfilter-suggestions {
1311 1323 width: auto !important; // overrides autocomplete.js
1312 1324 max-height: 100% !important;
1313 1325 min-width: 376px;
1314 1326 margin: 0;
1315 1327 border: @border-thickness solid @grey5;
1316 1328 color: @grey2;
1317 1329 background-color: white;
1318 1330 }
1319 1331
1320 1332 .autocomplete-selected {
1321 1333 background: #F0F0F0;
1322 1334 }
1323 1335
1324 1336 .ac-container-wrap {
1325 1337 margin: 0;
1326 1338 padding: 8px;
1327 1339 border-bottom: @border-thickness solid @grey5;
1328 1340 list-style-type: none;
1329 1341 cursor: pointer;
1330 1342
1331 1343 &:hover {
1332 1344 background-color: @grey7;
1333 1345 }
1334 1346
1335 1347 img {
1336 1348 height: @gravatar-size;
1337 1349 width: @gravatar-size;
1338 1350 margin-right: 1em;
1339 1351 }
1340 1352
1341 1353 strong {
1342 1354 font-weight: normal;
1343 1355 }
1344 1356 }
1345 1357
1346 1358 // Settings Dropdown
1347 1359 .user-menu .container {
1348 1360 padding: 0 4px;
1349 1361 margin: 0;
1350 1362 }
1351 1363
1352 1364 .user-menu .gravatar {
1353 1365 cursor: pointer;
1354 1366 }
1355 1367
1356 1368 .codeblock {
1357 1369 margin-bottom: @padding;
1358 1370 clear: both;
1359 1371
1360 1372 .stats {
1361 1373 overflow: hidden;
1362 1374 }
1363 1375
1364 1376 .message{
1365 1377 textarea{
1366 1378 margin: 0;
1367 1379 }
1368 1380 }
1369 1381
1370 1382 .code-header {
1371 1383 .stats {
1372 1384 line-height: 2em;
1373 1385
1374 1386 .revision_id {
1375 1387 margin-left: 0;
1376 1388 }
1377 1389 .buttons {
1378 1390 padding-right: 0;
1379 1391 }
1380 1392 }
1381 1393
1382 1394 .item{
1383 1395 margin-right: 0.5em;
1384 1396 }
1385 1397 }
1386 1398
1387 1399 #editor_container {
1388 1400 position: relative;
1389 1401 margin: @padding 10px;
1390 1402 }
1391 1403 }
1392 1404
1393 1405 #file_history_container {
1394 1406 display: none;
1395 1407 }
1396 1408
1397 1409 .file-history-inner {
1398 1410 margin-bottom: 10px;
1399 1411 }
1400 1412
1401 1413 // Pull Requests
1402 1414 .summary-details {
1403 1415 width: 72%;
1404 1416 }
1405 1417 .pr-summary {
1406 1418 border-bottom: @border-thickness solid @grey5;
1407 1419 margin-bottom: @space;
1408 1420 }
1409 1421 .reviewers-title {
1410 1422 width: 25%;
1411 1423 min-width: 200px;
1412 1424 }
1413 1425 .reviewers {
1414 1426 width: 25%;
1415 1427 min-width: 200px;
1416 1428 }
1417 1429 .reviewers ul li {
1418 1430 position: relative;
1419 1431 width: 100%;
1420 1432 padding-bottom: 8px;
1421 1433 list-style-type: none;
1422 1434 }
1423 1435
1424 1436 .reviewer_entry {
1425 1437 min-height: 55px;
1426 1438 }
1427 1439
1428 1440 .reviewers_member {
1429 1441 width: 100%;
1430 1442 overflow: auto;
1431 1443 }
1432 1444 .reviewer_reason {
1433 1445 padding-left: 20px;
1434 1446 line-height: 1.5em;
1435 1447 }
1436 1448 .reviewer_status {
1437 1449 display: inline-block;
1438 1450 width: 25px;
1439 1451 min-width: 25px;
1440 1452 height: 1.2em;
1441 1453 line-height: 1em;
1442 1454 }
1443 1455
1444 1456 .reviewer_name {
1445 1457 display: inline-block;
1446 1458 max-width: 83%;
1447 1459 padding-right: 20px;
1448 1460 vertical-align: middle;
1449 1461 line-height: 1;
1450 1462
1451 1463 .rc-user {
1452 1464 min-width: 0;
1453 1465 margin: -2px 1em 0 0;
1454 1466 }
1455 1467
1456 1468 .reviewer {
1457 1469 float: left;
1458 1470 }
1459 1471 }
1460 1472
1461 1473 .reviewer_member_mandatory {
1462 1474 position: absolute;
1463 1475 left: 15px;
1464 1476 top: 8px;
1465 1477 width: 16px;
1466 1478 font-size: 11px;
1467 1479 margin: 0;
1468 1480 padding: 0;
1469 1481 color: black;
1470 1482 }
1471 1483
1472 1484 .reviewer_member_mandatory_remove,
1473 1485 .reviewer_member_remove {
1474 1486 position: absolute;
1475 1487 right: 0;
1476 1488 top: 0;
1477 1489 width: 16px;
1478 1490 margin-bottom: 10px;
1479 1491 padding: 0;
1480 1492 color: black;
1481 1493 }
1482 1494
1483 1495 .reviewer_member_mandatory_remove {
1484 1496 color: @grey4;
1485 1497 }
1486 1498
1487 1499 .reviewer_member_status {
1488 1500 margin-top: 5px;
1489 1501 }
1490 1502 .pr-summary #summary{
1491 1503 width: 100%;
1492 1504 }
1493 1505 .pr-summary .action_button:hover {
1494 1506 border: 0;
1495 1507 cursor: pointer;
1496 1508 }
1497 1509 .pr-details-title {
1498 1510 padding-bottom: 8px;
1499 1511 border-bottom: @border-thickness solid @grey5;
1500 1512
1501 1513 .action_button.disabled {
1502 1514 color: @grey4;
1503 1515 cursor: inherit;
1504 1516 }
1505 1517 .action_button {
1506 1518 color: @rcblue;
1507 1519 }
1508 1520 }
1509 1521 .pr-details-content {
1510 1522 margin-top: @textmargin;
1511 1523 margin-bottom: @textmargin;
1512 1524 }
1513 1525
1514 1526 .pr-reviewer-rules {
1515 1527 padding: 10px 0px 20px 0px;
1516 1528 }
1517 1529
1518 1530 .group_members {
1519 1531 margin-top: 0;
1520 1532 padding: 0;
1521 1533 list-style: outside none none;
1522 1534
1523 1535 img {
1524 1536 height: @gravatar-size;
1525 1537 width: @gravatar-size;
1526 1538 margin-right: .5em;
1527 1539 margin-left: 3px;
1528 1540 }
1529 1541
1530 1542 .to-delete {
1531 1543 .user {
1532 1544 text-decoration: line-through;
1533 1545 }
1534 1546 }
1535 1547 }
1536 1548
1537 1549 .compare_view_commits_title {
1538 1550 .disabled {
1539 1551 cursor: inherit;
1540 1552 &:hover{
1541 1553 background-color: inherit;
1542 1554 color: inherit;
1543 1555 }
1544 1556 }
1545 1557 }
1546 1558
1547 1559 .subtitle-compare {
1548 1560 margin: -15px 0px 0px 0px;
1549 1561 }
1550 1562
1551 1563 // new entry in group_members
1552 1564 .td-author-new-entry {
1553 1565 background-color: rgba(red(@alert1), green(@alert1), blue(@alert1), 0.3);
1554 1566 }
1555 1567
1556 1568 .usergroup_member_remove {
1557 1569 width: 16px;
1558 1570 margin-bottom: 10px;
1559 1571 padding: 0;
1560 1572 color: black !important;
1561 1573 cursor: pointer;
1562 1574 }
1563 1575
1564 1576 .reviewer_ac .ac-input {
1565 1577 width: 92%;
1566 1578 margin-bottom: 1em;
1567 1579 }
1568 1580
1569 1581 .compare_view_commits tr{
1570 1582 height: 20px;
1571 1583 }
1572 1584 .compare_view_commits td {
1573 1585 vertical-align: top;
1574 1586 padding-top: 10px;
1575 1587 }
1576 1588 .compare_view_commits .author {
1577 1589 margin-left: 5px;
1578 1590 }
1579 1591
1580 1592 .compare_view_commits {
1581 1593 .color-a {
1582 1594 color: @alert1;
1583 1595 }
1584 1596
1585 1597 .color-c {
1586 1598 color: @color3;
1587 1599 }
1588 1600
1589 1601 .color-r {
1590 1602 color: @color5;
1591 1603 }
1592 1604
1593 1605 .color-a-bg {
1594 1606 background-color: @alert1;
1595 1607 }
1596 1608
1597 1609 .color-c-bg {
1598 1610 background-color: @alert3;
1599 1611 }
1600 1612
1601 1613 .color-r-bg {
1602 1614 background-color: @alert2;
1603 1615 }
1604 1616
1605 1617 .color-a-border {
1606 1618 border: 1px solid @alert1;
1607 1619 }
1608 1620
1609 1621 .color-c-border {
1610 1622 border: 1px solid @alert3;
1611 1623 }
1612 1624
1613 1625 .color-r-border {
1614 1626 border: 1px solid @alert2;
1615 1627 }
1616 1628
1617 1629 .commit-change-indicator {
1618 1630 width: 15px;
1619 1631 height: 15px;
1620 1632 position: relative;
1621 1633 left: 15px;
1622 1634 }
1623 1635
1624 1636 .commit-change-content {
1625 1637 text-align: center;
1626 1638 vertical-align: middle;
1627 1639 line-height: 15px;
1628 1640 }
1629 1641 }
1630 1642
1631 1643 .compare_view_filepath {
1632 1644 color: @grey1;
1633 1645 }
1634 1646
1635 1647 .show_more {
1636 1648 display: inline-block;
1637 1649 width: 0;
1638 1650 height: 0;
1639 1651 vertical-align: middle;
1640 1652 content: "";
1641 1653 border: 4px solid;
1642 1654 border-right-color: transparent;
1643 1655 border-bottom-color: transparent;
1644 1656 border-left-color: transparent;
1645 1657 font-size: 0;
1646 1658 }
1647 1659
1648 1660 .journal_more .show_more {
1649 1661 display: inline;
1650 1662
1651 1663 &:after {
1652 1664 content: none;
1653 1665 }
1654 1666 }
1655 1667
1656 1668 .compare_view_commits .collapse_commit:after {
1657 1669 cursor: pointer;
1658 1670 content: "\00A0\25B4";
1659 1671 margin-left: -3px;
1660 1672 font-size: 17px;
1661 1673 color: @grey4;
1662 1674 }
1663 1675
1664 1676 .diff_links {
1665 1677 margin-left: 8px;
1666 1678 }
1667 1679
1668 1680 #pull_request_overview {
1669 1681 div.ancestor {
1670 1682 margin: -33px 0;
1671 1683 }
1672 1684 }
1673 1685
1674 1686 div.ancestor {
1675 1687 line-height: 33px;
1676 1688 }
1677 1689
1678 1690 .cs_icon_td input[type="checkbox"] {
1679 1691 display: none;
1680 1692 }
1681 1693
1682 1694 .cs_icon_td .expand_file_icon:after {
1683 1695 cursor: pointer;
1684 1696 content: "\00A0\25B6";
1685 1697 font-size: 12px;
1686 1698 color: @grey4;
1687 1699 }
1688 1700
1689 1701 .cs_icon_td .collapse_file_icon:after {
1690 1702 cursor: pointer;
1691 1703 content: "\00A0\25BC";
1692 1704 font-size: 12px;
1693 1705 color: @grey4;
1694 1706 }
1695 1707
1696 1708 /*new binary
1697 1709 NEW_FILENODE = 1
1698 1710 DEL_FILENODE = 2
1699 1711 MOD_FILENODE = 3
1700 1712 RENAMED_FILENODE = 4
1701 1713 COPIED_FILENODE = 5
1702 1714 CHMOD_FILENODE = 6
1703 1715 BIN_FILENODE = 7
1704 1716 */
1705 1717 .cs_files_expand {
1706 1718 font-size: @basefontsize + 5px;
1707 1719 line-height: 1.8em;
1708 1720 float: right;
1709 1721 }
1710 1722
1711 1723 .cs_files_expand span{
1712 1724 color: @rcblue;
1713 1725 cursor: pointer;
1714 1726 }
1715 1727 .cs_files {
1716 1728 clear: both;
1717 1729 padding-bottom: @padding;
1718 1730
1719 1731 .cur_cs {
1720 1732 margin: 10px 2px;
1721 1733 font-weight: bold;
1722 1734 }
1723 1735
1724 1736 .node {
1725 1737 float: left;
1726 1738 }
1727 1739
1728 1740 .changes {
1729 1741 float: right;
1730 1742 color: white;
1731 1743 font-size: @basefontsize - 4px;
1732 1744 margin-top: 4px;
1733 1745 opacity: 0.6;
1734 1746 filter: Alpha(opacity=60); /* IE8 and earlier */
1735 1747
1736 1748 .added {
1737 1749 background-color: @alert1;
1738 1750 float: left;
1739 1751 text-align: center;
1740 1752 }
1741 1753
1742 1754 .deleted {
1743 1755 background-color: @alert2;
1744 1756 float: left;
1745 1757 text-align: center;
1746 1758 }
1747 1759
1748 1760 .bin {
1749 1761 background-color: @alert1;
1750 1762 text-align: center;
1751 1763 }
1752 1764
1753 1765 /*new binary*/
1754 1766 .bin.bin1 {
1755 1767 background-color: @alert1;
1756 1768 text-align: center;
1757 1769 }
1758 1770
1759 1771 /*deleted binary*/
1760 1772 .bin.bin2 {
1761 1773 background-color: @alert2;
1762 1774 text-align: center;
1763 1775 }
1764 1776
1765 1777 /*mod binary*/
1766 1778 .bin.bin3 {
1767 1779 background-color: @grey2;
1768 1780 text-align: center;
1769 1781 }
1770 1782
1771 1783 /*rename file*/
1772 1784 .bin.bin4 {
1773 1785 background-color: @alert4;
1774 1786 text-align: center;
1775 1787 }
1776 1788
1777 1789 /*copied file*/
1778 1790 .bin.bin5 {
1779 1791 background-color: @alert4;
1780 1792 text-align: center;
1781 1793 }
1782 1794
1783 1795 /*chmod file*/
1784 1796 .bin.bin6 {
1785 1797 background-color: @grey2;
1786 1798 text-align: center;
1787 1799 }
1788 1800 }
1789 1801 }
1790 1802
1791 1803 .cs_files .cs_added, .cs_files .cs_A,
1792 1804 .cs_files .cs_added, .cs_files .cs_M,
1793 1805 .cs_files .cs_added, .cs_files .cs_D {
1794 1806 height: 16px;
1795 1807 padding-right: 10px;
1796 1808 margin-top: 7px;
1797 1809 text-align: left;
1798 1810 }
1799 1811
1800 1812 .cs_icon_td {
1801 1813 min-width: 16px;
1802 1814 width: 16px;
1803 1815 }
1804 1816
1805 1817 .pull-request-merge {
1806 1818 border: 1px solid @grey5;
1807 1819 padding: 10px 0px 20px;
1808 1820 margin-top: 10px;
1809 1821 margin-bottom: 20px;
1810 1822 }
1811 1823
1812 1824 .pull-request-merge-refresh {
1813 1825 margin: 2px 7px;
1814 1826 a {
1815 1827 color: @grey3;
1816 1828 }
1817 1829 }
1818 1830
1819 1831 .pull-request-merge ul {
1820 1832 padding: 0px 0px;
1821 1833 }
1822 1834
1823 1835 .pull-request-merge li {
1824 1836 list-style-type: none;
1825 1837 }
1826 1838
1827 1839 .pull-request-merge .pull-request-wrap {
1828 1840 height: auto;
1829 1841 padding: 0px 0px;
1830 1842 text-align: right;
1831 1843 }
1832 1844
1833 1845 .pull-request-merge span {
1834 1846 margin-right: 5px;
1835 1847 }
1836 1848
1837 1849 .pull-request-merge-actions {
1838 1850 min-height: 30px;
1839 1851 padding: 0px 0px;
1840 1852 }
1841 1853
1842 1854 .pull-request-merge-info {
1843 1855 padding: 0px 5px 5px 0px;
1844 1856 }
1845 1857
1846 1858 .merge-status {
1847 1859 margin-right: 5px;
1848 1860 }
1849 1861
1850 1862 .merge-message {
1851 1863 font-size: 1.2em
1852 1864 }
1853 1865
1854 1866 .merge-message.success i,
1855 1867 .merge-icon.success i {
1856 1868 color:@alert1;
1857 1869 }
1858 1870
1859 1871 .merge-message.warning i,
1860 1872 .merge-icon.warning i {
1861 1873 color: @alert3;
1862 1874 }
1863 1875
1864 1876 .merge-message.error i,
1865 1877 .merge-icon.error i {
1866 1878 color:@alert2;
1867 1879 }
1868 1880
1869 1881 .pr-versions {
1870 1882 font-size: 1.1em;
1871 1883
1872 1884 table {
1873 1885 padding: 0px 5px;
1874 1886 }
1875 1887
1876 1888 td {
1877 1889 line-height: 15px;
1878 1890 }
1879 1891
1880 1892 .compare-radio-button {
1881 1893 position: relative;
1882 1894 top: -3px;
1883 1895 }
1884 1896 }
1885 1897
1886 1898
1887 1899 #close_pull_request {
1888 1900 margin-right: 0px;
1889 1901 }
1890 1902
1891 1903 .empty_data {
1892 1904 color: @grey4;
1893 1905 }
1894 1906
1895 1907 #changeset_compare_view_content {
1896 1908 clear: both;
1897 1909 width: 100%;
1898 1910 box-sizing: border-box;
1899 1911 .border-radius(@border-radius);
1900 1912
1901 1913 .help-block {
1902 1914 margin: @padding 0;
1903 1915 color: @text-color;
1904 1916 &.pre-formatting {
1905 1917 white-space: pre;
1906 1918 }
1907 1919 }
1908 1920
1909 1921 .empty_data {
1910 1922 margin: @padding 0;
1911 1923 }
1912 1924
1913 1925 .alert {
1914 1926 margin-bottom: @space;
1915 1927 }
1916 1928 }
1917 1929
1918 1930 .table_disp {
1919 1931 .status {
1920 1932 width: auto;
1921 1933 }
1922 1934 }
1923 1935
1924 1936
1925 1937 .creation_in_progress {
1926 1938 color: @grey4
1927 1939 }
1928 1940
1929 1941 .status_box_menu {
1930 1942 margin: 0;
1931 1943 }
1932 1944
1933 1945 .notification-table{
1934 1946 margin-bottom: @space;
1935 1947 display: table;
1936 1948 width: 100%;
1937 1949
1938 1950 .container{
1939 1951 display: table-row;
1940 1952
1941 1953 .notification-header{
1942 1954 border-bottom: @border-thickness solid @border-default-color;
1943 1955 }
1944 1956
1945 1957 .notification-subject{
1946 1958 display: table-cell;
1947 1959 }
1948 1960 }
1949 1961 }
1950 1962
1951 1963 // Notifications
1952 1964 .notification-header{
1953 1965 display: table;
1954 1966 width: 100%;
1955 1967 padding: floor(@basefontsize/2) 0;
1956 1968 line-height: 1em;
1957 1969
1958 1970 .desc, .delete-notifications, .read-notifications{
1959 1971 display: table-cell;
1960 1972 text-align: left;
1961 1973 }
1962 1974
1963 1975 .delete-notifications, .read-notifications{
1964 1976 width: 35px;
1965 1977 min-width: 35px; //fixes when only one button is displayed
1966 1978 }
1967 1979 }
1968 1980
1969 1981 .notification-body {
1970 1982 .markdown-block,
1971 1983 .rst-block {
1972 1984 padding: @padding 0;
1973 1985 }
1974 1986
1975 1987 .notification-subject {
1976 1988 padding: @textmargin 0;
1977 1989 border-bottom: @border-thickness solid @border-default-color;
1978 1990 }
1979 1991 }
1980 1992
1981 1993
1982 1994 .notifications_buttons{
1983 1995 float: right;
1984 1996 }
1985 1997
1986 1998 #notification-status{
1987 1999 display: inline;
1988 2000 }
1989 2001
1990 2002 // Repositories
1991 2003
1992 2004 #summary.fields{
1993 2005 display: table;
1994 2006
1995 2007 .field{
1996 2008 display: table-row;
1997 2009
1998 2010 .label-summary{
1999 2011 display: table-cell;
2000 2012 min-width: @label-summary-minwidth;
2001 2013 padding-top: @padding/2;
2002 2014 padding-bottom: @padding/2;
2003 2015 padding-right: @padding/2;
2004 2016 }
2005 2017
2006 2018 .input{
2007 2019 display: table-cell;
2008 2020 padding: @padding/2;
2009 2021
2010 2022 input{
2011 2023 min-width: 29em;
2012 2024 padding: @padding/4;
2013 2025 }
2014 2026 }
2015 2027 .statistics, .downloads{
2016 2028 .disabled{
2017 2029 color: @grey4;
2018 2030 }
2019 2031 }
2020 2032 }
2021 2033 }
2022 2034
2023 2035 #summary{
2024 2036 width: 70%;
2025 2037 }
2026 2038
2027 2039
2028 2040 // Journal
2029 2041 .journal.title {
2030 2042 h5 {
2031 2043 float: left;
2032 2044 margin: 0;
2033 2045 width: 70%;
2034 2046 }
2035 2047
2036 2048 ul {
2037 2049 float: right;
2038 2050 display: inline-block;
2039 2051 margin: 0;
2040 2052 width: 30%;
2041 2053 text-align: right;
2042 2054
2043 2055 li {
2044 2056 display: inline;
2045 2057 font-size: @journal-fontsize;
2046 2058 line-height: 1em;
2047 2059
2048 2060 list-style-type: none;
2049 2061 }
2050 2062 }
2051 2063 }
2052 2064
2053 2065 .filterexample {
2054 2066 position: absolute;
2055 2067 top: 95px;
2056 2068 left: @contentpadding;
2057 2069 color: @rcblue;
2058 2070 font-size: 11px;
2059 2071 font-family: @text-regular;
2060 2072 cursor: help;
2061 2073
2062 2074 &:hover {
2063 2075 color: @rcdarkblue;
2064 2076 }
2065 2077
2066 2078 @media (max-width:768px) {
2067 2079 position: relative;
2068 2080 top: auto;
2069 2081 left: auto;
2070 2082 display: block;
2071 2083 }
2072 2084 }
2073 2085
2074 2086
2075 2087 #journal{
2076 2088 margin-bottom: @space;
2077 2089
2078 2090 .journal_day{
2079 2091 margin-bottom: @textmargin/2;
2080 2092 padding-bottom: @textmargin/2;
2081 2093 font-size: @journal-fontsize;
2082 2094 border-bottom: @border-thickness solid @border-default-color;
2083 2095 }
2084 2096
2085 2097 .journal_container{
2086 2098 margin-bottom: @space;
2087 2099
2088 2100 .journal_user{
2089 2101 display: inline-block;
2090 2102 }
2091 2103 .journal_action_container{
2092 2104 display: block;
2093 2105 margin-top: @textmargin;
2094 2106
2095 2107 div{
2096 2108 display: inline;
2097 2109 }
2098 2110
2099 2111 div.journal_action_params{
2100 2112 display: block;
2101 2113 }
2102 2114
2103 2115 div.journal_repo:after{
2104 2116 content: "\A";
2105 2117 white-space: pre;
2106 2118 }
2107 2119
2108 2120 div.date{
2109 2121 display: block;
2110 2122 margin-bottom: @textmargin;
2111 2123 }
2112 2124 }
2113 2125 }
2114 2126 }
2115 2127
2116 2128 // Files
2117 2129 .edit-file-title {
2118 2130 font-size: 16px;
2119 2131
2120 2132 .title-heading {
2121 2133 padding: 2px;
2122 2134 }
2123 2135 }
2124 2136
2125 2137 .edit-file-fieldset {
2126 2138 margin: @sidebarpadding 0;
2127 2139
2128 2140 .fieldset {
2129 2141 .left-label {
2130 2142 width: 13%;
2131 2143 }
2132 2144 .right-content {
2133 2145 width: 87%;
2134 2146 max-width: 100%;
2135 2147 }
2136 2148 .filename-label {
2137 2149 margin-top: 13px;
2138 2150 }
2139 2151 .commit-message-label {
2140 2152 margin-top: 4px;
2141 2153 }
2142 2154 .file-upload-input {
2143 2155 input {
2144 2156 display: none;
2145 2157 }
2146 2158 margin-top: 10px;
2147 2159 }
2148 2160 .file-upload-label {
2149 2161 margin-top: 10px;
2150 2162 }
2151 2163 p {
2152 2164 margin-top: 5px;
2153 2165 }
2154 2166
2155 2167 }
2156 2168 .custom-path-link {
2157 2169 margin-left: 5px;
2158 2170 }
2159 2171 #commit {
2160 2172 resize: vertical;
2161 2173 }
2162 2174 }
2163 2175
2164 2176 .delete-file-preview {
2165 2177 max-height: 250px;
2166 2178 }
2167 2179
2168 2180 .new-file,
2169 2181 #filter_activate,
2170 2182 #filter_deactivate {
2171 2183 float: right;
2172 2184 margin: 0 0 0 10px;
2173 2185 }
2174 2186
2175 2187 .file-upload-transaction-wrapper {
2176 2188 margin-top: 57px;
2177 2189 clear: both;
2178 2190 }
2179 2191
2180 2192 .file-upload-transaction-wrapper .error {
2181 2193 color: @color5;
2182 2194 }
2183 2195
2184 2196 .file-upload-transaction {
2185 2197 min-height: 200px;
2186 2198 padding: 54px;
2187 2199 border: 1px solid @grey5;
2188 2200 text-align: center;
2189 2201 clear: both;
2190 2202 }
2191 2203
2192 2204 .file-upload-transaction i {
2193 2205 font-size: 48px
2194 2206 }
2195 2207
2196 2208 h3.files_location{
2197 2209 line-height: 2.4em;
2198 2210 }
2199 2211
2200 2212 .browser-nav {
2201 2213 width: 100%;
2202 2214 display: table;
2203 2215 margin-bottom: 20px;
2204 2216
2205 2217 .info_box {
2206 2218 float: left;
2207 2219 display: inline-table;
2208 2220 height: 2.5em;
2209 2221
2210 2222 .browser-cur-rev, .info_box_elem {
2211 2223 display: table-cell;
2212 2224 vertical-align: middle;
2213 2225 }
2214 2226
2215 2227 .drop-menu {
2216 2228 margin: 0 10px;
2217 2229 }
2218 2230
2219 2231 .info_box_elem {
2220 2232 border-top: @border-thickness solid @grey5;
2221 2233 border-bottom: @border-thickness solid @grey5;
2222 2234 box-shadow: @button-shadow;
2223 2235
2224 2236 #at_rev, a {
2225 2237 padding: 0.6em 0.4em;
2226 2238 margin: 0;
2227 2239 .box-shadow(none);
2228 2240 border: 0;
2229 2241 height: 12px;
2230 2242 color: @grey2;
2231 2243 }
2232 2244
2233 2245 input#at_rev {
2234 2246 max-width: 50px;
2235 2247 text-align: center;
2236 2248 }
2237 2249
2238 2250 &.previous {
2239 2251 border: @border-thickness solid @grey5;
2240 2252 border-top-left-radius: @border-radius;
2241 2253 border-bottom-left-radius: @border-radius;
2242 2254
2243 2255 &:hover {
2244 2256 border-color: @grey4;
2245 2257 }
2246 2258
2247 2259 .disabled {
2248 2260 color: @grey5;
2249 2261 cursor: not-allowed;
2250 2262 opacity: 0.5;
2251 2263 }
2252 2264 }
2253 2265
2254 2266 &.next {
2255 2267 border: @border-thickness solid @grey5;
2256 2268 border-top-right-radius: @border-radius;
2257 2269 border-bottom-right-radius: @border-radius;
2258 2270
2259 2271 &:hover {
2260 2272 border-color: @grey4;
2261 2273 }
2262 2274
2263 2275 .disabled {
2264 2276 color: @grey5;
2265 2277 cursor: not-allowed;
2266 2278 opacity: 0.5;
2267 2279 }
2268 2280 }
2269 2281 }
2270 2282
2271 2283 .browser-cur-rev {
2272 2284
2273 2285 span{
2274 2286 margin: 0;
2275 2287 color: @rcblue;
2276 2288 height: 12px;
2277 2289 display: inline-block;
2278 2290 padding: 0.7em 1em ;
2279 2291 border: @border-thickness solid @rcblue;
2280 2292 margin-right: @padding;
2281 2293 }
2282 2294 }
2283 2295
2284 2296 }
2285 2297
2286 2298 .select-index-number {
2287 2299 margin: 0 0 0 20px;
2288 2300 color: @grey3;
2289 2301 }
2290 2302
2291 2303 .search_activate {
2292 2304 display: table-cell;
2293 2305 vertical-align: middle;
2294 2306
2295 2307 input, label{
2296 2308 margin: 0;
2297 2309 padding: 0;
2298 2310 }
2299 2311
2300 2312 input{
2301 2313 margin-left: @textmargin;
2302 2314 }
2303 2315
2304 2316 }
2305 2317 }
2306 2318
2307 2319 .browser-cur-rev{
2308 2320 margin-bottom: @textmargin;
2309 2321 }
2310 2322
2311 2323 #node_filter_box_loading{
2312 2324 .info_text;
2313 2325 }
2314 2326
2315 2327 .browser-search {
2316 2328 margin: -25px 0px 5px 0px;
2317 2329 }
2318 2330
2319 2331 .files-quick-filter {
2320 2332 float: right;
2321 2333 width: 180px;
2322 2334 position: relative;
2323 2335 }
2324 2336
2325 2337 .files-filter-box {
2326 2338 display: flex;
2327 2339 padding: 0px;
2328 2340 border-radius: 3px;
2329 2341 margin-bottom: 0;
2330 2342
2331 2343 a {
2332 2344 border: none !important;
2333 2345 }
2334 2346
2335 2347 li {
2336 2348 list-style-type: none
2337 2349 }
2338 2350 }
2339 2351
2340 2352 .files-filter-box-path {
2341 2353 line-height: 33px;
2342 2354 padding: 0;
2343 2355 width: 20px;
2344 2356 position: absolute;
2345 2357 z-index: 11;
2346 2358 left: 5px;
2347 2359 }
2348 2360
2349 2361 .files-filter-box-input {
2350 2362 margin-right: 0;
2351 2363
2352 2364 input {
2353 2365 border: 1px solid @white;
2354 2366 padding-left: 25px;
2355 2367 width: 145px;
2356 2368
2357 2369 &:hover {
2358 2370 border-color: @grey6;
2359 2371 }
2360 2372
2361 2373 &:focus {
2362 2374 border-color: @grey5;
2363 2375 }
2364 2376 }
2365 2377 }
2366 2378
2367 2379 .browser-result{
2368 2380 td a{
2369 2381 margin-left: 0.5em;
2370 2382 display: inline-block;
2371 2383
2372 2384 em {
2373 2385 font-weight: @text-bold-weight;
2374 2386 font-family: @text-bold;
2375 2387 }
2376 2388 }
2377 2389 }
2378 2390
2379 2391 .browser-highlight{
2380 2392 background-color: @grey5-alpha;
2381 2393 }
2382 2394
2383 2395
2384 2396 .edit-file-fieldset #location,
2385 2397 .edit-file-fieldset #filename {
2386 2398 display: flex;
2387 2399 width: -moz-available; /* WebKit-based browsers will ignore this. */
2388 2400 width: -webkit-fill-available; /* Mozilla-based browsers will ignore this. */
2389 2401 width: fill-available;
2390 2402 border: 0;
2391 2403 }
2392 2404
2393 2405 .path-items {
2394 2406 display: flex;
2395 2407 padding: 0;
2396 2408 border: 1px solid #eeeeee;
2397 2409 width: 100%;
2398 2410 float: left;
2399 2411
2400 2412 .breadcrumb-path {
2401 2413 line-height: 30px;
2402 2414 padding: 0 4px;
2403 2415 white-space: nowrap;
2404 2416 }
2405 2417
2406 2418 .location-path {
2407 2419 width: -moz-available; /* WebKit-based browsers will ignore this. */
2408 2420 width: -webkit-fill-available; /* Mozilla-based browsers will ignore this. */
2409 2421 width: fill-available;
2410 2422
2411 2423 .file-name-input {
2412 2424 padding: 0.5em 0;
2413 2425 }
2414 2426
2415 2427 }
2416 2428
2417 2429 ul {
2418 2430 display: flex;
2419 2431 margin: 0;
2420 2432 padding: 0;
2421 2433 width: 100%;
2422 2434 }
2423 2435
2424 2436 li {
2425 2437 list-style-type: none;
2426 2438 }
2427 2439
2428 2440 }
2429 2441
2430 2442 .editor-items {
2431 2443 height: 40px;
2432 2444 margin: 10px 0 -17px 10px;
2433 2445
2434 2446 .editor-action {
2435 2447 cursor: pointer;
2436 2448 }
2437 2449
2438 2450 .editor-action.active {
2439 2451 border-bottom: 2px solid #5C5C5C;
2440 2452 }
2441 2453
2442 2454 li {
2443 2455 list-style-type: none;
2444 2456 }
2445 2457 }
2446 2458
2447 2459 .edit-file-fieldset .message textarea {
2448 2460 border: 1px solid #eeeeee;
2449 2461 }
2450 2462
2451 2463 #files_data .codeblock {
2452 2464 background-color: #F5F5F5;
2453 2465 }
2454 2466
2455 2467 #editor_preview {
2456 2468 background: white;
2457 2469 }
2458 2470
2459 2471 .show-editor {
2460 2472 padding: 10px;
2461 2473 background-color: white;
2462 2474
2463 2475 }
2464 2476
2465 2477 .show-preview {
2466 2478 padding: 10px;
2467 2479 background-color: white;
2468 2480 border-left: 1px solid #eeeeee;
2469 2481 }
2470 2482 // quick filter
2471 2483 .grid-quick-filter {
2472 2484 float: right;
2473 2485 position: relative;
2474 2486 }
2475 2487
2476 2488 .grid-filter-box {
2477 2489 display: flex;
2478 2490 padding: 0px;
2479 2491 border-radius: 3px;
2480 2492 margin-bottom: 0;
2481 2493
2482 2494 a {
2483 2495 border: none !important;
2484 2496 }
2485 2497
2486 2498 li {
2487 2499 list-style-type: none
2488 2500 }
2489 2501 }
2490 2502
2491 2503 .grid-filter-box-icon {
2492 2504 line-height: 33px;
2493 2505 padding: 0;
2494 2506 width: 20px;
2495 2507 position: absolute;
2496 2508 z-index: 11;
2497 2509 left: 5px;
2498 2510 }
2499 2511
2500 2512 .grid-filter-box-input {
2501 2513 margin-right: 0;
2502 2514
2503 2515 input {
2504 2516 border: 1px solid @white;
2505 2517 padding-left: 25px;
2506 2518 width: 145px;
2507 2519
2508 2520 &:hover {
2509 2521 border-color: @grey6;
2510 2522 }
2511 2523
2512 2524 &:focus {
2513 2525 border-color: @grey5;
2514 2526 }
2515 2527 }
2516 2528 }
2517 2529
2518 2530
2519 2531
2520 2532 // Search
2521 2533
2522 2534 .search-form{
2523 2535 #q {
2524 2536 width: @search-form-width;
2525 2537 }
2526 2538 .fields{
2527 2539 margin: 0 0 @space;
2528 2540 }
2529 2541
2530 2542 label{
2531 2543 display: inline-block;
2532 2544 margin-right: @textmargin;
2533 2545 padding-top: 0.25em;
2534 2546 }
2535 2547
2536 2548
2537 2549 .results{
2538 2550 clear: both;
2539 2551 margin: 0 0 @padding;
2540 2552 }
2541 2553
2542 2554 .search-tags {
2543 2555 padding: 5px 0;
2544 2556 }
2545 2557 }
2546 2558
2547 2559 div.search-feedback-items {
2548 2560 display: inline-block;
2549 2561 }
2550 2562
2551 2563 div.search-code-body {
2552 2564 background-color: #ffffff; padding: 5px 0 5px 10px;
2553 2565 pre {
2554 2566 .match { background-color: #faffa6;}
2555 2567 .break { display: block; width: 100%; background-color: #DDE7EF; color: #747474; }
2556 2568 }
2557 2569 }
2558 2570
2559 2571 .expand_commit.search {
2560 2572 .show_more.open {
2561 2573 height: auto;
2562 2574 max-height: none;
2563 2575 }
2564 2576 }
2565 2577
2566 2578 .search-results {
2567 2579
2568 2580 h2 {
2569 2581 margin-bottom: 0;
2570 2582 }
2571 2583 .codeblock {
2572 2584 border: none;
2573 2585 background: transparent;
2574 2586 }
2575 2587
2576 2588 .codeblock-header {
2577 2589 border: none;
2578 2590 background: transparent;
2579 2591 }
2580 2592
2581 2593 .code-body {
2582 2594 border: @border-thickness solid @grey6;
2583 2595 .border-radius(@border-radius);
2584 2596 }
2585 2597
2586 2598 .td-commit {
2587 2599 &:extend(pre);
2588 2600 border-bottom: @border-thickness solid @border-default-color;
2589 2601 }
2590 2602
2591 2603 .message {
2592 2604 height: auto;
2593 2605 max-width: 350px;
2594 2606 white-space: normal;
2595 2607 text-overflow: initial;
2596 2608 overflow: visible;
2597 2609
2598 2610 .match { background-color: #faffa6;}
2599 2611 .break { background-color: #DDE7EF; width: 100%; color: #747474; display: block; }
2600 2612 }
2601 2613
2602 2614 .path {
2603 2615 border-bottom: none !important;
2604 2616 border-left: 1px solid @grey6 !important;
2605 2617 border-right: 1px solid @grey6 !important;
2606 2618 }
2607 2619 }
2608 2620
2609 2621 table.rctable td.td-search-results div {
2610 2622 max-width: 100%;
2611 2623 }
2612 2624
2613 2625 #tip-box, .tip-box{
2614 2626 padding: @menupadding/2;
2615 2627 display: block;
2616 2628 border: @border-thickness solid @border-highlight-color;
2617 2629 .border-radius(@border-radius);
2618 2630 background-color: white;
2619 2631 z-index: 99;
2620 2632 white-space: pre-wrap;
2621 2633 }
2622 2634
2623 2635 #linktt {
2624 2636 width: 79px;
2625 2637 }
2626 2638
2627 2639 #help_kb .modal-content{
2628 2640 max-width: 750px;
2629 2641 margin: 10% auto;
2630 2642
2631 2643 table{
2632 2644 td,th{
2633 2645 border-bottom: none;
2634 2646 line-height: 2.5em;
2635 2647 }
2636 2648 th{
2637 2649 padding-bottom: @textmargin/2;
2638 2650 }
2639 2651 td.keys{
2640 2652 text-align: center;
2641 2653 }
2642 2654 }
2643 2655
2644 2656 .block-left{
2645 2657 width: 45%;
2646 2658 margin-right: 5%;
2647 2659 }
2648 2660 .modal-footer{
2649 2661 clear: both;
2650 2662 }
2651 2663 .key.tag{
2652 2664 padding: 0.5em;
2653 2665 background-color: @rcblue;
2654 2666 color: white;
2655 2667 border-color: @rcblue;
2656 2668 .box-shadow(none);
2657 2669 }
2658 2670 }
2659 2671
2660 2672
2661 2673
2662 2674 //--- IMPORTS FOR REFACTORED STYLES ------------------//
2663 2675
2664 2676 @import 'statistics-graph';
2665 2677 @import 'tables';
2666 2678 @import 'forms';
2667 2679 @import 'diff';
2668 2680 @import 'summary';
2669 2681 @import 'navigation';
2670 2682
2671 2683 //--- SHOW/HIDE SECTIONS --//
2672 2684
2673 2685 .btn-collapse {
2674 2686 float: right;
2675 2687 text-align: right;
2676 2688 font-family: @text-light;
2677 2689 font-size: @basefontsize;
2678 2690 cursor: pointer;
2679 2691 border: none;
2680 2692 color: @rcblue;
2681 2693 }
2682 2694
2683 2695 table.rctable,
2684 2696 table.dataTable {
2685 2697 .btn-collapse {
2686 2698 float: right;
2687 2699 text-align: right;
2688 2700 }
2689 2701 }
2690 2702
2691 2703 table.rctable {
2692 2704 &.permissions {
2693 2705
2694 2706 th.td-owner {
2695 2707 padding: 0;
2696 2708 }
2697 2709
2698 2710 th {
2699 2711 font-weight: normal;
2700 2712 padding: 0 5px;
2701 2713 }
2702 2714
2703 2715 }
2704 2716 }
2705 2717
2706 2718
2707 2719 // TODO: johbo: Fix for IE10, this avoids that we see a border
2708 2720 // and padding around checkboxes and radio boxes. Move to the right place,
2709 2721 // or better: Remove this once we did the form refactoring.
2710 2722 input[type=checkbox],
2711 2723 input[type=radio] {
2712 2724 padding: 0;
2713 2725 border: none;
2714 2726 }
2715 2727
2716 2728 .toggle-ajax-spinner{
2717 2729 height: 16px;
2718 2730 width: 16px;
2719 2731 }
2720 2732
2721 2733
2722 2734 .markup-form .clearfix {
2723 2735 .border-radius(@border-radius);
2724 2736 margin: 0px;
2725 2737 }
2726 2738
2727 2739 .markup-form-area {
2728 2740 padding: 8px 12px;
2729 2741 border: 1px solid @grey4;
2730 2742 .border-radius(@border-radius);
2731 2743 }
2732 2744
2733 2745 .markup-form-area-header .nav-links {
2734 2746 display: flex;
2735 2747 flex-flow: row wrap;
2736 2748 -webkit-flex-flow: row wrap;
2737 2749 width: 100%;
2738 2750 }
2739 2751
2740 2752 .markup-form-area-footer {
2741 2753 display: flex;
2742 2754 }
2743 2755
2744 2756 .markup-form-area-footer .toolbar {
2745 2757
2746 2758 }
2747 2759
2748 2760 // markup Form
2749 2761 div.markup-form {
2750 2762 margin-top: 20px;
2751 2763 }
2752 2764
2753 2765 .markup-form strong {
2754 2766 display: block;
2755 2767 margin-bottom: 15px;
2756 2768 }
2757 2769
2758 2770 .markup-form textarea {
2759 2771 width: 100%;
2760 2772 height: 100px;
2761 2773 font-family: @text-monospace;
2762 2774 }
2763 2775
2764 2776 form.markup-form {
2765 2777 margin-top: 10px;
2766 2778 margin-left: 10px;
2767 2779 }
2768 2780
2769 2781 .markup-form .comment-block-ta,
2770 2782 .markup-form .preview-box {
2771 2783 .border-radius(@border-radius);
2772 2784 .box-sizing(border-box);
2773 2785 background-color: white;
2774 2786 }
2775 2787
2776 2788 .markup-form .preview-box.unloaded {
2777 2789 height: 50px;
2778 2790 text-align: center;
2779 2791 padding: 20px;
2780 2792 background-color: white;
2781 2793 }
2782 2794
2783 2795
2784 2796 .dropzone-wrapper {
2785 2797 border: 1px solid @grey5;
2786 2798 padding: 20px;
2787 2799 }
2788 2800
2789 2801 .dropzone,
2790 2802 .dropzone-pure {
2791 2803 border: 2px dashed @grey5;
2792 2804 border-radius: 5px;
2793 2805 background: white;
2794 2806 min-height: 200px;
2795 2807 padding: 54px;
2796 2808
2797 2809 .dz-message {
2798 2810 font-weight: 700;
2799 2811 text-align: center;
2800 2812 margin: 2em 0;
2801 2813 }
2802 2814
2803 2815 }
2804 2816
2805 2817 .dz-preview {
2806 2818 margin: 10px 0 !important;
2807 2819 position: relative;
2808 2820 vertical-align: top;
2809 2821 padding: 10px;
2810 2822 border-bottom: 1px solid @grey5;
2811 2823 }
2812 2824
2813 2825 .dz-filename {
2814 2826 font-weight: 700;
2815 2827 float: left;
2816 2828 }
2817 2829
2818 2830 .dz-sending {
2819 2831 float: right;
2820 2832 }
2821 2833
2822 2834 .dz-response {
2823 2835 clear: both
2824 2836 }
2825 2837
2826 2838 .dz-filename-size {
2827 2839 float: right
2828 2840 }
2829 2841
2830 2842 .dz-error-message {
2831 2843 color: @alert2;
2832 2844 padding-top: 10px;
2833 2845 clear: both;
2834 2846 }
2835 2847
2836 2848
2837 2849 .user-hovercard {
2838 2850 padding: 5px;
2839 2851 }
2840 2852
2841 2853 .user-hovercard-icon {
2842 2854 display: inline;
2843 2855 padding: 0;
2844 2856 box-sizing: content-box;
2845 2857 border-radius: 50%;
2846 2858 float: left;
2847 2859 }
2848 2860
2849 2861 .user-hovercard-name {
2850 2862 float: right;
2851 2863 vertical-align: top;
2852 2864 padding-left: 10px;
2853 2865 min-width: 150px;
2854 2866 }
2855 2867
2856 2868 .user-hovercard-bio {
2857 2869 clear: both;
2858 2870 padding-top: 10px;
2859 2871 }
2860 2872
2861 2873 .user-hovercard-header {
2862 2874 clear: both;
2863 2875 min-height: 10px;
2864 2876 }
2865 2877
2866 2878 .user-hovercard-footer {
2867 2879 clear: both;
2868 2880 min-height: 10px;
2869 2881 }
2870 2882
2871 2883 .user-group-hovercard {
2872 2884 padding: 5px;
2873 2885 }
2874 2886
2875 2887 .user-group-hovercard-icon {
2876 2888 display: inline;
2877 2889 padding: 0;
2878 2890 box-sizing: content-box;
2879 2891 border-radius: 50%;
2880 2892 float: left;
2881 2893 }
2882 2894
2883 2895 .user-group-hovercard-name {
2884 2896 float: left;
2885 2897 vertical-align: top;
2886 2898 padding-left: 10px;
2887 2899 min-width: 150px;
2888 2900 }
2889 2901
2890 2902 .user-group-hovercard-icon i {
2891 2903 border: 1px solid @grey4;
2892 2904 border-radius: 4px;
2893 2905 }
2894 2906
2895 2907 .user-group-hovercard-bio {
2896 2908 clear: both;
2897 2909 padding-top: 10px;
2898 2910 line-height: 1.0em;
2899 2911 }
2900 2912
2901 2913 .user-group-hovercard-header {
2902 2914 clear: both;
2903 2915 min-height: 10px;
2904 2916 }
2905 2917
2906 2918 .user-group-hovercard-footer {
2907 2919 clear: both;
2908 2920 min-height: 10px;
2909 2921 }
2910 2922
2911 2923 .pr-hovercard-header {
2912 2924 clear: both;
2913 2925 display: block;
2914 2926 line-height: 20px;
2915 2927 }
2916 2928
2917 2929 .pr-hovercard-user {
2918 2930 display: flex;
2919 2931 align-items: center;
2920 2932 padding-left: 5px;
2921 2933 }
2922 2934
2923 2935 .pr-hovercard-title {
2924 2936 padding-top: 5px;
2925 2937 } No newline at end of file
@@ -1,154 +1,171 b''
1 1 // tags.less
2 2 // For use in RhodeCode applications;
3 3 // see style guide documentation for guidelines.
4 4
5 5 // TAGS
6 6 .tag,
7 7 .tagtag {
8 8 display: inline-block;
9 9 min-height: 0;
10 10 margin: 0 auto;
11 11 padding: .25em;
12 12 text-align: center;
13 13 font-size: (-1 + @basefontsize); //fit in tables
14 14 line-height: 1.1em;
15 15 border: none;
16 16 box-shadow: @button-shadow;
17 17 .border-radius(@border-radius);
18 18 font-family: @text-regular;
19 19 background-image: none;
20 20 color: @grey4;
21 21 .border ( @border-thickness-tags, @grey5 );
22 22 white-space: nowrap;
23 23 a {
24 24 color: inherit;
25 25
26 26 &:hover {
27 27 color: @grey2;
28 28 }
29 29
30 30 i,
31 31 [class^="icon-"]:before,
32 32 [class*=" icon-"]:before {
33 33 text-decoration: none;
34 34 }
35 35 }
36 36
37 37 &:hover {
38 38 border-color: @grey4;
39 39 }
40 40 }
41 41
42 42 .tag0 { .border ( @border-thickness-tags, @grey4 ); color:@grey4; }
43 43 .tag1 { .border ( @border-thickness-tags, @color1 ); color:@color1; }
44 44 .tag2 { .border ( @border-thickness-tags, @color2 ); color:@color2; }
45 45 .tag3 { .border ( @border-thickness-tags, @color3 ); color:@color3; }
46 46 .tag4 { .border ( @border-thickness-tags, @color4 ); color:@color4; }
47 47 .tag5 { .border ( @border-thickness-tags, @color5 ); color:@color5; }
48 48 .tag6 { .border ( @border-thickness-tags, @color6 ); color:@color6; }
49 49 .tag7 { .border ( @border-thickness-tags, @color7 ); color:@color7; }
50 50 .tag8 { .border ( @border-thickness-tags, @color8 ); color:@color8; }
51 51
52 52
53 53 .tag-gist-public {
54 54 .border (@border-thickness-tags, @color1);
55 55 color: @color1;
56 56 }
57 57
58 58
59 59 .tag-gist-private {
60 60 .border (@border-thickness-tags, @color2);
61 61 color: @color2;
62 62 }
63 63
64 64
65 .tag-merge-state-created {
66 color: @color1;
67 }
68
69 .tag-merge-state-creating {
70 color: @color1;
71 }
72
73 .tag-merge-state-merging {
74 color: @color3;
75 }
76
77 .tag-merge-state-updating {
78 color: @color3;
79 }
80
81
65 82 .metatag-list {
66 83 margin: 0;
67 84 padding: 0;
68 85
69 86 li {
70 87 margin: 0 0 @padding;
71 88 line-height: 1em;
72 89 list-style-type: none;
73 90 }
74 91 }
75 92
76 93 .branchtag, .booktag {
77 94 &:extend(.tag);
78 95
79 96
80 97 a {
81 98 color:inherit;
82 99 }
83 100 }
84 101
85 102 .metatag {
86 103 &:extend(.tag);
87 104 a {
88 105 color:inherit;
89 106 text-decoration: underline;
90 107 }
91 108 }
92 109
93 110 [tag="generic"] { &:extend(.tag0); }
94 111 [tag="label"] { &:extend(.tag0); }
95 112
96 113 [tag="state featured"] { &:extend(.tag1); }
97 114 [tag="state dev"] { &:extend(.tag1); }
98 115 [tag="ref base"] { &:extend(.tag1); }
99 116
100 117 [tag="state stable"] { &:extend(.tag2); }
101 118 [tag="state stale"] { &:extend(.tag2); }
102 119
103 120 [tag="ref requires"] { &:extend(.tag3); }
104 121
105 122 [tag="state dead"] { &:extend(.tag4); }
106 123 [tag="state deprecated"] { &:extend(.tag4); }
107 124
108 125 [tag="ref conflicts"] { &:extend(.tag4); }
109 126
110 127 [tag="license"] { &:extend(.tag6); }
111 128
112 129 [tag="lang"] { &:extend(.tag7); }
113 130 [tag="language"] { &:extend(.tag7); }
114 131 [tag="ref recommends"] { &:extend(.tag7); }
115 132
116 133 [tag="see"] { &:extend(.tag8); }
117 134 [tag="url"] { &:extend(.tag8); }
118 135
119 136
120 137 .perm_overriden {
121 138 text-decoration: line-through;
122 139 opacity: 0.6;
123 140 }
124 141
125 142 .perm_tag {
126 143 &:extend(.tag);
127 144
128 145 &.read {
129 146 &:extend(.tag1);
130 147 }
131 148 &.write {
132 149 &:extend(.tag4);
133 150 }
134 151 &.admin {
135 152 &:extend(.tag5);
136 153 }
137 154 &.merge {
138 155 &:extend(.tag1);
139 156 }
140 157 &.push {
141 158 &:extend(.tag4);
142 159 }
143 160 &.push_force {
144 161 &:extend(.tag5);
145 162 }
146 163 }
147 164
148 165 .phase-draft {
149 166 color: @color3
150 167 }
151 168
152 169 .phase-secret {
153 170 color:@grey3
154 171 }
@@ -1,94 +1,91 b''
1 1 <%namespace name="base" file="/base/base.mako"/>
2 2
3 3 <div class="panel panel-default">
4 4 <div class="panel-body">
5 5 %if c.closed:
6 6 ${h.checkbox('show_closed',checked="checked", label=_('Show Closed Pull Requests'))}
7 7 %else:
8 8 ${h.checkbox('show_closed',label=_('Show Closed Pull Requests'))}
9 9 %endif
10 10 </div>
11 11 </div>
12 12
13 13 <div class="panel panel-default">
14 14 <div class="panel-heading">
15 15 <h3 class="panel-title">${_('Pull Requests You Participate In')}</h3>
16 16 </div>
17 17 <div class="panel-body panel-body-min-height">
18 18 <table id="pull_request_list_table" class="display"></table>
19 19 </div>
20 20 </div>
21 21
22 22 <script type="text/javascript">
23 23 $(document).ready(function() {
24 24
25 25 $('#show_closed').on('click', function(e){
26 26 if($(this).is(":checked")){
27 27 window.location = "${h.route_path('my_account_pullrequests', _query={'pr_show_closed':1})}";
28 28 }
29 29 else{
30 30 window.location = "${h.route_path('my_account_pullrequests')}";
31 31 }
32 32 });
33 33
34 34 var $pullRequestListTable = $('#pull_request_list_table');
35 35
36 36 // participating object list
37 37 $pullRequestListTable.DataTable({
38 38 processing: true,
39 39 serverSide: true,
40 40 ajax: {
41 41 "url": "${h.route_path('my_account_pullrequests_data')}",
42 42 "data": function (d) {
43 43 d.closed = "${c.closed}";
44 44 }
45 45 },
46 46 dom: 'rtp',
47 47 pageLength: ${c.visual.dashboard_items},
48 48 order: [[ 2, "desc" ]],
49 49 columns: [
50 { data: {"_": "target_repo",
51 "sort": "target_repo"}, title: "${_('Target Repo')}", className: "td-targetrepo", orderable: false},
50 52 { data: {"_": "status",
51 53 "sort": "status"}, title: "", className: "td-status", orderable: false},
52 { data: {"_": "target_repo",
53 "sort": "target_repo"}, title: "${_('Target Repo')}", className: "td-targetrepo", orderable: false},
54 54 { data: {"_": "name",
55 55 "sort": "name_raw"}, title: "${_('Id')}", className: "td-componentname", "type": "num" },
56 56 { data: {"_": "title",
57 57 "sort": "title"}, title: "${_('Title')}", className: "td-description" },
58 58 { data: {"_": "author",
59 59 "sort": "author_raw"}, title: "${_('Author')}", className: "td-user", orderable: false },
60 60 { data: {"_": "comments",
61 61 "sort": "comments_raw"}, title: "", className: "td-comments", orderable: false},
62 62 { data: {"_": "updated_on",
63 63 "sort": "updated_on_raw"}, title: "${_('Last Update')}", className: "td-time" }
64 64 ],
65 65 language: {
66 66 paginate: DEFAULT_GRID_PAGINATION,
67 67 sProcessing: _gettext('loading...'),
68 68 emptyTable: _gettext("There are currently no open pull requests requiring your participation.")
69 69 },
70 70 "drawCallback": function( settings, json ) {
71 71 timeagoActivate();
72 72 tooltipActivate();
73 73 },
74 74 "createdRow": function ( row, data, index ) {
75 75 if (data['closed']) {
76 76 $(row).addClass('closed');
77 77 }
78 78 if (data['owned']) {
79 79 $(row).addClass('owned');
80 80 }
81 if (data['state'] !== 'created') {
82 $(row).addClass('state-' + data['state']);
83 }
84 81 }
85 82 });
86 83 $pullRequestListTable.on('xhr.dt', function(e, settings, json, xhr){
87 84 $pullRequestListTable.css('opacity', 1);
88 85 });
89 86
90 87 $pullRequestListTable.on('preXhr.dt', function(e, settings, data){
91 88 $pullRequestListTable.css('opacity', 0.3);
92 89 });
93 90 });
94 91 </script>
@@ -1,474 +1,479 b''
1 1 ## DATA TABLE RE USABLE ELEMENTS
2 2 ## usage:
3 3 ## <%namespace name="dt" file="/data_table/_dt_elements.mako"/>
4 4 <%namespace name="base" file="/base/base.mako"/>
5 5
6 6 <%def name="metatags_help()">
7 7 <table>
8 8 <%
9 9 example_tags = [
10 10 ('state','[stable]'),
11 11 ('state','[stale]'),
12 12 ('state','[featured]'),
13 13 ('state','[dev]'),
14 14 ('state','[dead]'),
15 15 ('state','[deprecated]'),
16 16
17 17 ('label','[personal]'),
18 18 ('generic','[v2.0.0]'),
19 19
20 20 ('lang','[lang =&gt; JavaScript]'),
21 21 ('license','[license =&gt; LicenseName]'),
22 22
23 23 ('ref','[requires =&gt; RepoName]'),
24 24 ('ref','[recommends =&gt; GroupName]'),
25 25 ('ref','[conflicts =&gt; SomeName]'),
26 26 ('ref','[base =&gt; SomeName]'),
27 27 ('url','[url =&gt; [linkName](https://rhodecode.com)]'),
28 28 ('see','[see =&gt; http://rhodecode.com]'),
29 29 ]
30 30 %>
31 31 % for tag_type, tag in example_tags:
32 32 <tr>
33 33 <td>${tag|n}</td>
34 34 <td>${h.style_metatag(tag_type, tag)|n}</td>
35 35 </tr>
36 36 % endfor
37 37 </table>
38 38 </%def>
39 39
40 40 <%def name="render_description(description, stylify_metatags)">
41 41 <%
42 42 tags = []
43 43 if stylify_metatags:
44 44 tags, description = h.extract_metatags(description)
45 45 %>
46 46 % for tag_type, tag in tags:
47 47 ${h.style_metatag(tag_type, tag)|n,trim}
48 48 % endfor
49 49 <code style="white-space: pre-wrap">${description}</code>
50 50 </%def>
51 51
52 52 ## REPOSITORY RENDERERS
53 53 <%def name="quick_menu(repo_name)">
54 54 <i class="icon-more"></i>
55 55 <div class="menu_items_container hidden">
56 56 <ul class="menu_items">
57 57 <li>
58 58 <a title="${_('Summary')}" href="${h.route_path('repo_summary',repo_name=repo_name)}">
59 59 <span>${_('Summary')}</span>
60 60 </a>
61 61 </li>
62 62 <li>
63 63 <a title="${_('Commits')}" href="${h.route_path('repo_commits',repo_name=repo_name)}">
64 64 <span>${_('Commits')}</span>
65 65 </a>
66 66 </li>
67 67 <li>
68 68 <a title="${_('Files')}" href="${h.route_path('repo_files:default_commit',repo_name=repo_name)}">
69 69 <span>${_('Files')}</span>
70 70 </a>
71 71 </li>
72 72 <li>
73 73 <a title="${_('Fork')}" href="${h.route_path('repo_fork_new',repo_name=repo_name)}">
74 74 <span>${_('Fork')}</span>
75 75 </a>
76 76 </li>
77 77 </ul>
78 78 </div>
79 79 </%def>
80 80
81 81 <%def name="repo_name(name,rtype,rstate,private,archived,fork_of,short_name=False,admin=False)">
82 82 <%
83 83 def get_name(name,short_name=short_name):
84 84 if short_name:
85 85 return name.split('/')[-1]
86 86 else:
87 87 return name
88 88 %>
89 89 <div class="${'repo_state_pending' if rstate == 'repo_state_pending' else ''} truncate">
90 90 ##NAME
91 91 <a href="${h.route_path('edit_repo',repo_name=name) if admin else h.route_path('repo_summary',repo_name=name)}">
92 92
93 93 ##TYPE OF REPO
94 94 %if h.is_hg(rtype):
95 95 <span title="${_('Mercurial repository')}"><i class="icon-hg" style="font-size: 14px;"></i></span>
96 96 %elif h.is_git(rtype):
97 97 <span title="${_('Git repository')}"><i class="icon-git" style="font-size: 14px"></i></span>
98 98 %elif h.is_svn(rtype):
99 99 <span title="${_('Subversion repository')}"><i class="icon-svn" style="font-size: 14px"></i></span>
100 100 %endif
101 101
102 102 ##PRIVATE/PUBLIC
103 103 %if private is True and c.visual.show_private_icon:
104 104 <i class="icon-lock" title="${_('Private repository')}"></i>
105 105 %elif private is False and c.visual.show_public_icon:
106 106 <i class="icon-unlock-alt" title="${_('Public repository')}"></i>
107 107 %else:
108 108 <span></span>
109 109 %endif
110 110 ${get_name(name)}
111 111 </a>
112 112 %if fork_of:
113 113 <a href="${h.route_path('repo_summary',repo_name=fork_of.repo_name)}"><i class="icon-code-fork"></i></a>
114 114 %endif
115 115 %if rstate == 'repo_state_pending':
116 116 <span class="creation_in_progress tooltip" title="${_('This repository is being created in a background task')}">
117 117 (${_('creating...')})
118 118 </span>
119 119 %endif
120 120
121 121 </div>
122 122 </%def>
123 123
124 124 <%def name="repo_desc(description, stylify_metatags)">
125 125 <%
126 126 tags, description = h.extract_metatags(description)
127 127 %>
128 128
129 129 <div class="truncate-wrap">
130 130 % if stylify_metatags:
131 131 % for tag_type, tag in tags:
132 132 ${h.style_metatag(tag_type, tag)|n}
133 133 % endfor
134 134 % endif
135 135 ${description}
136 136 </div>
137 137
138 138 </%def>
139 139
140 140 <%def name="last_change(last_change)">
141 141 ${h.age_component(last_change, time_is_local=True)}
142 142 </%def>
143 143
144 144 <%def name="revision(repo_name, rev, commit_id, author, last_msg, commit_date)">
145 145 <div>
146 146 %if rev >= 0:
147 147 <code><a class="tooltip-hovercard" data-hovercard-alt=${h.tooltip(last_msg)} data-hovercard-url="${h.route_path('hovercard_repo_commit', repo_name=repo_name, commit_id=commit_id)}" href="${h.route_path('repo_commit',repo_name=repo_name,commit_id=commit_id)}">${'r{}:{}'.format(rev,h.short_id(commit_id))}</a></code>
148 148 %else:
149 149 ${_('No commits yet')}
150 150 %endif
151 151 </div>
152 152 </%def>
153 153
154 154 <%def name="rss(name)">
155 155 %if c.rhodecode_user.username != h.DEFAULT_USER:
156 156 <a title="${h.tooltip(_('Subscribe to %s rss feed')% name)}" href="${h.route_path('rss_feed_home', repo_name=name, _query=dict(auth_token=c.rhodecode_user.feed_token))}"><i class="icon-rss-sign"></i></a>
157 157 %else:
158 158 <a title="${h.tooltip(_('Subscribe to %s rss feed')% name)}" href="${h.route_path('rss_feed_home', repo_name=name)}"><i class="icon-rss-sign"></i></a>
159 159 %endif
160 160 </%def>
161 161
162 162 <%def name="atom(name)">
163 163 %if c.rhodecode_user.username != h.DEFAULT_USER:
164 164 <a title="${h.tooltip(_('Subscribe to %s atom feed')% name)}" href="${h.route_path('atom_feed_home', repo_name=name, _query=dict(auth_token=c.rhodecode_user.feed_token))}"><i class="icon-rss-sign"></i></a>
165 165 %else:
166 166 <a title="${h.tooltip(_('Subscribe to %s atom feed')% name)}" href="${h.route_path('atom_feed_home', repo_name=name)}"><i class="icon-rss-sign"></i></a>
167 167 %endif
168 168 </%def>
169 169
170 170 <%def name="repo_actions(repo_name, super_user=True)">
171 171 <div>
172 172 <div class="grid_edit">
173 173 <a href="${h.route_path('edit_repo',repo_name=repo_name)}" title="${_('Edit')}">
174 174 Edit
175 175 </a>
176 176 </div>
177 177 <div class="grid_delete">
178 178 ${h.secure_form(h.route_path('edit_repo_advanced_delete', repo_name=repo_name), request=request)}
179 179 ${h.submit('remove_%s' % repo_name,_('Delete'),class_="btn btn-link btn-danger",
180 180 onclick="return confirm('"+_('Confirm to delete this repository: %s') % repo_name+"');")}
181 181 ${h.end_form()}
182 182 </div>
183 183 </div>
184 184 </%def>
185 185
186 186 <%def name="repo_state(repo_state)">
187 187 <div>
188 188 %if repo_state == 'repo_state_pending':
189 189 <div class="tag tag4">${_('Creating')}</div>
190 190 %elif repo_state == 'repo_state_created':
191 191 <div class="tag tag1">${_('Created')}</div>
192 192 %else:
193 193 <div class="tag alert2" title="${h.tooltip(repo_state)}">invalid</div>
194 194 %endif
195 195 </div>
196 196 </%def>
197 197
198 198
199 199 ## REPO GROUP RENDERERS
200 200 <%def name="quick_repo_group_menu(repo_group_name)">
201 201 <i class="icon-more"></i>
202 202 <div class="menu_items_container hidden">
203 203 <ul class="menu_items">
204 204 <li>
205 205 <a href="${h.route_path('repo_group_home', repo_group_name=repo_group_name)}">${_('Summary')}</a>
206 206 </li>
207 207
208 208 </ul>
209 209 </div>
210 210 </%def>
211 211
212 212 <%def name="repo_group_name(repo_group_name, children_groups=None)">
213 213 <div>
214 214 <a href="${h.route_path('repo_group_home', repo_group_name=repo_group_name)}">
215 215 <i class="icon-repo-group" title="${_('Repository group')}" style="font-size: 14px"></i>
216 216 %if children_groups:
217 217 ${h.literal(' &raquo; '.join(children_groups))}
218 218 %else:
219 219 ${repo_group_name}
220 220 %endif
221 221 </a>
222 222 </div>
223 223 </%def>
224 224
225 225 <%def name="repo_group_desc(description, personal, stylify_metatags)">
226 226
227 227 <%
228 228 if stylify_metatags:
229 229 tags, description = h.extract_metatags(description)
230 230 %>
231 231
232 232 <div class="truncate-wrap">
233 233 % if personal:
234 234 <div class="metatag" tag="personal">${_('personal')}</div>
235 235 % endif
236 236
237 237 % if stylify_metatags:
238 238 % for tag_type, tag in tags:
239 239 ${h.style_metatag(tag_type, tag)|n}
240 240 % endfor
241 241 % endif
242 242 ${description}
243 243 </div>
244 244
245 245 </%def>
246 246
247 247 <%def name="repo_group_actions(repo_group_id, repo_group_name, gr_count)">
248 248 <div class="grid_edit">
249 249 <a href="${h.route_path('edit_repo_group',repo_group_name=repo_group_name)}" title="${_('Edit')}">Edit</a>
250 250 </div>
251 251 <div class="grid_delete">
252 252 ${h.secure_form(h.route_path('edit_repo_group_advanced_delete', repo_group_name=repo_group_name), request=request)}
253 253 ${h.submit('remove_%s' % repo_group_name,_('Delete'),class_="btn btn-link btn-danger",
254 254 onclick="return confirm('"+_ungettext('Confirm to delete this group: %s with %s repository','Confirm to delete this group: %s with %s repositories',gr_count) % (repo_group_name, gr_count)+"');")}
255 255 ${h.end_form()}
256 256 </div>
257 257 </%def>
258 258
259 259
260 260 <%def name="user_actions(user_id, username)">
261 261 <div class="grid_edit">
262 262 <a href="${h.route_path('user_edit',user_id=user_id)}" title="${_('Edit')}">
263 263 ${_('Edit')}
264 264 </a>
265 265 </div>
266 266 <div class="grid_delete">
267 267 ${h.secure_form(h.route_path('user_delete', user_id=user_id), request=request)}
268 268 ${h.submit('remove_',_('Delete'),id="remove_user_%s" % user_id, class_="btn btn-link btn-danger",
269 269 onclick="return confirm('"+_('Confirm to delete this user: %s') % username+"');")}
270 270 ${h.end_form()}
271 271 </div>
272 272 </%def>
273 273
274 274 <%def name="user_group_actions(user_group_id, user_group_name)">
275 275 <div class="grid_edit">
276 276 <a href="${h.route_path('edit_user_group', user_group_id=user_group_id)}" title="${_('Edit')}">Edit</a>
277 277 </div>
278 278 <div class="grid_delete">
279 279 ${h.secure_form(h.route_path('user_groups_delete', user_group_id=user_group_id), request=request)}
280 280 ${h.submit('remove_',_('Delete'),id="remove_group_%s" % user_group_id, class_="btn btn-link btn-danger",
281 281 onclick="return confirm('"+_('Confirm to delete this user group: %s') % user_group_name+"');")}
282 282 ${h.end_form()}
283 283 </div>
284 284 </%def>
285 285
286 286
287 287 <%def name="user_name(user_id, username)">
288 288 ${h.link_to(h.person(username, 'username_or_name_or_email'), h.route_path('user_edit', user_id=user_id))}
289 289 </%def>
290 290
291 291 <%def name="user_profile(username)">
292 292 ${base.gravatar_with_user(username, 16, tooltip=True)}
293 293 </%def>
294 294
295 295 <%def name="user_group_name(user_group_name)">
296 296 <div>
297 297 <i class="icon-user-group" title="${_('User group')}"></i>
298 298 ${h.link_to_group(user_group_name)}
299 299 </div>
300 300 </%def>
301 301
302 302
303 303 ## GISTS
304 304
305 305 <%def name="gist_gravatar(full_contact)">
306 306 <div class="gist_gravatar">
307 307 ${base.gravatar(full_contact, 30)}
308 308 </div>
309 309 </%def>
310 310
311 311 <%def name="gist_access_id(gist_access_id, full_contact)">
312 312 <div>
313 313 <b>
314 314 <a href="${h.route_path('gist_show', gist_id=gist_access_id)}">gist: ${gist_access_id}</a>
315 315 </b>
316 316 </div>
317 317 </%def>
318 318
319 319 <%def name="gist_author(full_contact, created_on, expires)">
320 320 ${base.gravatar_with_user(full_contact, 16, tooltip=True)}
321 321 </%def>
322 322
323 323
324 324 <%def name="gist_created(created_on)">
325 325 <div class="created">
326 326 ${h.age_component(created_on, time_is_local=True)}
327 327 </div>
328 328 </%def>
329 329
330 330 <%def name="gist_expires(expires)">
331 331 <div class="created">
332 332 %if expires == -1:
333 333 ${_('never')}
334 334 %else:
335 335 ${h.age_component(h.time_to_utcdatetime(expires))}
336 336 %endif
337 337 </div>
338 338 </%def>
339 339
340 340 <%def name="gist_type(gist_type)">
341 341 %if gist_type == 'public':
342 342 <span class="tag tag-gist-public disabled">${_('Public Gist')}</span>
343 343 %else:
344 344 <span class="tag tag-gist-private disabled">${_('Private Gist')}</span>
345 345 %endif
346 346 </%def>
347 347
348 348 <%def name="gist_description(gist_description)">
349 349 ${gist_description}
350 350 </%def>
351 351
352 352
353 353 ## PULL REQUESTS GRID RENDERERS
354 354
355 355 <%def name="pullrequest_target_repo(repo_name)">
356 356 <div class="truncate">
357 357 ${h.link_to(repo_name,h.route_path('repo_summary',repo_name=repo_name))}
358 358 </div>
359 359 </%def>
360 360
361 361 <%def name="pullrequest_status(status)">
362 362 <i class="icon-circle review-status-${status}"></i>
363 363 </%def>
364 364
365 365 <%def name="pullrequest_title(title, description)">
366 366 ${title}
367 367 </%def>
368 368
369 369 <%def name="pullrequest_comments(comments_nr)">
370 370 <i class="icon-comment"></i> ${comments_nr}
371 371 </%def>
372 372
373 <%def name="pullrequest_name(pull_request_id, is_wip, target_repo_name, short=False)">
373 <%def name="pullrequest_name(pull_request_id, state, is_wip, target_repo_name, short=False)">
374 374 <a href="${h.route_path('pullrequest_show',repo_name=target_repo_name,pull_request_id=pull_request_id)}">
375 % if is_wip:
376 <span class="tag tooltip" title="${_('Work in progress')}">wip</span>
377 % endif
378 375
379 376 % if short:
380 377 !${pull_request_id}
381 378 % else:
382 379 ${_('Pull request !{}').format(pull_request_id)}
383 380 % endif
381
382 % if state not in ['created']:
383 <span class="tag tag-merge-state-${state} tooltip" title="Pull request state is changing">${state}</span>
384 % endif
385
386 % if is_wip:
387 <span class="tag tooltip" title="${_('Work in progress')}">wip</span>
388 % endif
384 389 </a>
385 390 </%def>
386 391
387 392 <%def name="pullrequest_updated_on(updated_on)">
388 393 ${h.age_component(h.time_to_utcdatetime(updated_on))}
389 394 </%def>
390 395
391 396 <%def name="pullrequest_author(full_contact)">
392 397 ${base.gravatar_with_user(full_contact, 16, tooltip=True)}
393 398 </%def>
394 399
395 400
396 401 ## ARTIFACT RENDERERS
397 402 <%def name="repo_artifact_name(repo_name, file_uid, artifact_display_name)">
398 403 <a href="${h.route_path('repo_artifacts_get', repo_name=repo_name, uid=file_uid)}">
399 404 ${artifact_display_name or '_EMPTY_NAME_'}
400 405 </a>
401 406 </%def>
402 407
403 408 <%def name="repo_artifact_uid(repo_name, file_uid)">
404 409 <code>${h.shorter(file_uid, size=24, prefix=True)}</code>
405 410 </%def>
406 411
407 412 <%def name="repo_artifact_sha256(artifact_sha256)">
408 413 <div class="code">${h.shorter(artifact_sha256, 12)}</div>
409 414 </%def>
410 415
411 416 <%def name="repo_artifact_actions(repo_name, file_store_id, file_uid)">
412 417 ## <div class="grid_edit">
413 418 ## <a href="#Edit" title="${_('Edit')}">${_('Edit')}</a>
414 419 ## </div>
415 420 <div class="grid_edit">
416 421 <a href="${h.route_path('repo_artifacts_info', repo_name=repo_name, uid=file_store_id)}" title="${_('Info')}">${_('Info')}</a>
417 422 </div>
418 423 % if h.HasRepoPermissionAny('repository.admin')(c.repo_name):
419 424 <div class="grid_delete">
420 425 ${h.secure_form(h.route_path('repo_artifacts_delete', repo_name=repo_name, uid=file_store_id), request=request)}
421 426 ${h.submit('remove_',_('Delete'),id="remove_artifact_%s" % file_store_id, class_="btn btn-link btn-danger",
422 427 onclick="return confirm('"+_('Confirm to delete this artifact: %s') % file_uid+"');")}
423 428 ${h.end_form()}
424 429 </div>
425 430 % endif
426 431 </%def>
427 432
428 433 <%def name="markup_form(form_id, form_text='', help_text=None)">
429 434
430 435 <div class="markup-form">
431 436 <div class="markup-form-area">
432 437 <div class="markup-form-area-header">
433 438 <ul class="nav-links clearfix">
434 439 <li class="active">
435 440 <a href="#edit-text" tabindex="-1" id="edit-btn_${form_id}">${_('Write')}</a>
436 441 </li>
437 442 <li class="">
438 443 <a href="#preview-text" tabindex="-1" id="preview-btn_${form_id}">${_('Preview')}</a>
439 444 </li>
440 445 </ul>
441 446 </div>
442 447
443 448 <div class="markup-form-area-write" style="display: block;">
444 449 <div id="edit-container_${form_id}">
445 450 <textarea id="${form_id}" name="${form_id}" class="comment-block-ta ac-input">${form_text if form_text else ''}</textarea>
446 451 </div>
447 452 <div id="preview-container_${form_id}" class="clearfix" style="display: none;">
448 453 <div id="preview-box_${form_id}" class="preview-box"></div>
449 454 </div>
450 455 </div>
451 456
452 457 <div class="markup-form-area-footer">
453 458 <div class="toolbar">
454 459 <div class="toolbar-text">
455 460 ${(_('Parsed using %s syntax') % (
456 461 ('<a href="%s">%s</a>' % (h.route_url('%s_help' % c.visual.default_renderer), c.visual.default_renderer.upper())),
457 462 )
458 463 )|n}
459 464 </div>
460 465 </div>
461 466 </div>
462 467 </div>
463 468
464 469 <div class="markup-form-footer">
465 470 % if help_text:
466 471 <span class="help-block">${help_text}</span>
467 472 % endif
468 473 </div>
469 474 </div>
470 475 <script type="text/javascript">
471 476 new MarkupForm('${form_id}');
472 477 </script>
473 478
474 479 </%def>
@@ -1,809 +1,822 b''
1 1 <%inherit file="/base/base.mako"/>
2 2 <%namespace name="base" file="/base/base.mako"/>
3 3 <%namespace name="dt" file="/data_table/_dt_elements.mako"/>
4 4
5 5 <%def name="title()">
6 6 ${_('{} Pull Request !{}').format(c.repo_name, c.pull_request.pull_request_id)}
7 7 %if c.rhodecode_name:
8 8 &middot; ${h.branding(c.rhodecode_name)}
9 9 %endif
10 10 </%def>
11 11
12 12 <%def name="breadcrumbs_links()">
13 <span id="pr-title">
14 ${c.pull_request.title}
15 %if c.pull_request.is_closed():
16 (${_('Closed')})
17 %endif
18 </span>
13 <%
14 pr_title = c.pull_request.title
15 if c.pull_request.is_closed():
16 pr_title = '[{}] {}'.format(_('Closed'), pr_title)
17 %>
18
19 <div id="pr-title">
20 <input class="pr-title-input large disabled" disabled="disabled" name="pullrequest_title" type="text" value="${pr_title}">
21 </div>
19 22 <div id="pr-title-edit" class="input" style="display: none;">
20 ${h.text('pullrequest_title', id_="pr-title-input", class_="large", value=c.pull_request.title)}
23 <input class="pr-title-input large" id="pr-title-input" name="pullrequest_title" type="text" value="${c.pull_request.title}">
21 24 </div>
22 25 </%def>
23 26
24 27 <%def name="menu_bar_nav()">
25 28 ${self.menu_items(active='repositories')}
26 29 </%def>
27 30
28 31 <%def name="menu_bar_subnav()">
29 32 ${self.repo_menu(active='showpullrequest')}
30 33 </%def>
31 34
32 35 <%def name="main()">
33 36
34 37 <script type="text/javascript">
35 38 // TODO: marcink switch this to pyroutes
36 39 AJAX_COMMENT_DELETE_URL = "${h.route_path('pullrequest_comment_delete',repo_name=c.repo_name,pull_request_id=c.pull_request.pull_request_id,comment_id='__COMMENT_ID__')}";
37 40 templateContext.pull_request_data.pull_request_id = ${c.pull_request.pull_request_id};
38 41 </script>
39 42 <div class="box">
40 43
41 44 ${self.breadcrumbs()}
42 45
43 46 <div class="box pr-summary">
44 47
45 48 <div class="summary-details block-left">
46 49 <% summary = lambda n:{False:'summary-short'}.get(n) %>
47 50 <div class="pr-details-title">
48 51 <a href="${h.route_path('pull_requests_global', pull_request_id=c.pull_request.pull_request_id)}">${_('Pull request !{}').format(c.pull_request.pull_request_id)}</a> ${_('From')} ${h.format_date(c.pull_request.created_on)}
49 52 %if c.allowed_to_update:
50 53 <div id="delete_pullrequest" class="pull-right action_button ${'' if c.allowed_to_delete else 'disabled' }" style="clear:inherit;padding: 0">
51 54 % if c.allowed_to_delete:
52 55 ${h.secure_form(h.route_path('pullrequest_delete', repo_name=c.pull_request.target_repo.repo_name, pull_request_id=c.pull_request.pull_request_id), request=request)}
53 56 ${h.submit('remove_%s' % c.pull_request.pull_request_id, _('Delete'),
54 57 class_="btn btn-link btn-danger no-margin",onclick="return confirm('"+_('Confirm to delete this pull request')+"');")}
55 58 ${h.end_form()}
56 59 % else:
57 60 ${_('Delete')}
58 61 % endif
59 62 </div>
60 63 <div id="open_edit_pullrequest" class="pull-right action_button">${_('Edit')}</div>
61 64 <div id="close_edit_pullrequest" class="pull-right action_button" style="display: none;padding: 0">${_('Cancel')}</div>
62 65 %endif
63 66 </div>
64 67
65 68 <div id="summary" class="fields pr-details-content">
66 69 <div class="field">
67 70 <div class="label-summary">
68 71 <label>${_('Source')}:</label>
69 72 </div>
70 73 <div class="input">
71 74 <div class="pr-origininfo">
72 75 ## branch link is only valid if it is a branch
73 76 <span class="tag">
74 77 %if c.pull_request.source_ref_parts.type == 'branch':
75 78 <a href="${h.route_path('repo_commits', repo_name=c.pull_request.source_repo.repo_name, _query=dict(branch=c.pull_request.source_ref_parts.name))}">${c.pull_request.source_ref_parts.type}: ${c.pull_request.source_ref_parts.name}</a>
76 79 %else:
77 80 ${c.pull_request.source_ref_parts.type}: ${c.pull_request.source_ref_parts.name}
78 81 %endif
79 82 </span>
80 83 <span class="clone-url">
81 84 <a href="${h.route_path('repo_summary', repo_name=c.pull_request.source_repo.repo_name)}">${c.pull_request.source_repo.clone_url()}</a>
82 85 </span>
83 86 <br/>
84 87 % if c.ancestor_commit:
85 88 ${_('Common ancestor')}:
86 89 <code><a href="${h.route_path('repo_commit', repo_name=c.target_repo.repo_name, commit_id=c.ancestor_commit.raw_id)}">${h.show_id(c.ancestor_commit)}</a></code>
87 90 % endif
88 91 </div>
89 92 %if h.is_hg(c.pull_request.source_repo):
90 93 <% clone_url = 'hg pull -r {} {}'.format(h.short_id(c.source_ref), c.pull_request.source_repo.clone_url()) %>
91 94 %elif h.is_git(c.pull_request.source_repo):
92 95 <% clone_url = 'git pull {} {}'.format(c.pull_request.source_repo.clone_url(), c.pull_request.source_ref_parts.name) %>
93 96 %endif
94 97
95 98 <div class="">
96 99 <input type="text" class="input-monospace pr-pullinfo" value="${clone_url}" readonly="readonly">
97 100 <i class="tooltip icon-clipboard clipboard-action pull-right pr-pullinfo-copy" data-clipboard-text="${clone_url}" title="${_('Copy the pull url')}"></i>
98 101 </div>
99 102
100 103 </div>
101 104 </div>
102 105 <div class="field">
103 106 <div class="label-summary">
104 107 <label>${_('Target')}:</label>
105 108 </div>
106 109 <div class="input">
107 110 <div class="pr-targetinfo">
108 111 ## branch link is only valid if it is a branch
109 112 <span class="tag">
110 113 %if c.pull_request.target_ref_parts.type == 'branch':
111 114 <a href="${h.route_path('repo_commits', repo_name=c.pull_request.target_repo.repo_name, _query=dict(branch=c.pull_request.target_ref_parts.name))}">${c.pull_request.target_ref_parts.type}: ${c.pull_request.target_ref_parts.name}</a>
112 115 %else:
113 116 ${c.pull_request.target_ref_parts.type}: ${c.pull_request.target_ref_parts.name}
114 117 %endif
115 118 </span>
116 119 <span class="clone-url">
117 120 <a href="${h.route_path('repo_summary', repo_name=c.pull_request.target_repo.repo_name)}">${c.pull_request.target_repo.clone_url()}</a>
118 121 </span>
119 122 </div>
120 123 </div>
121 124 </div>
122 125
123 126 ## Link to the shadow repository.
124 127 <div class="field">
125 128 <div class="label-summary">
126 129 <label>${_('Merge')}:</label>
127 130 </div>
128 131 <div class="input">
129 132 % if not c.pull_request.is_closed() and c.pull_request.shadow_merge_ref:
130 133 %if h.is_hg(c.pull_request.target_repo):
131 134 <% clone_url = 'hg clone --update {} {} pull-request-{}'.format(c.pull_request.shadow_merge_ref.name, c.shadow_clone_url, c.pull_request.pull_request_id) %>
132 135 %elif h.is_git(c.pull_request.target_repo):
133 136 <% clone_url = 'git clone --branch {} {} pull-request-{}'.format(c.pull_request.shadow_merge_ref.name, c.shadow_clone_url, c.pull_request.pull_request_id) %>
134 137 %endif
135 138 <div class="">
136 139 <input type="text" class="input-monospace pr-mergeinfo" value="${clone_url}" readonly="readonly">
137 140 <i class="tooltip icon-clipboard clipboard-action pull-right pr-mergeinfo-copy" data-clipboard-text="${clone_url}" title="${_('Copy the clone url')}"></i>
138 141 </div>
139 142 % else:
140 143 <div class="">
141 144 ${_('Shadow repository data not available')}.
142 145 </div>
143 146 % endif
144 147 </div>
145 148 </div>
146 149
147 150 <div class="field">
148 151 <div class="label-summary">
149 152 <label>${_('Review')}:</label>
150 153 </div>
151 154 <div class="input">
152 155 %if c.pull_request_review_status:
153 156 <i class="icon-circle review-status-${c.pull_request_review_status}"></i>
154 <span class="changeset-status-lbl tooltip">
157 <span class="changeset-status-lbl">
155 158 %if c.pull_request.is_closed():
156 159 ${_('Closed')},
157 160 %endif
158 161 ${h.commit_status_lbl(c.pull_request_review_status)}
159 162 </span>
160 163 - ${_ungettext('calculated based on %s reviewer vote', 'calculated based on %s reviewers votes', len(c.pull_request_reviewers)) % len(c.pull_request_reviewers)}
161 164 %endif
162 165 </div>
163 166 </div>
164 167 <div class="field">
165 168 <div class="pr-description-label label-summary" title="${_('Rendered using {} renderer').format(c.renderer)}">
166 169 <label>${_('Description')}:</label>
167 170 </div>
168 171 <div id="pr-desc" class="input">
169 172 <div class="pr-description">${h.render(c.pull_request.description, renderer=c.renderer, repo_name=c.repo_name)}</div>
170 173 </div>
171 174 <div id="pr-desc-edit" class="input textarea editor" style="display: none;">
172 175 <input id="pr-renderer-input" type="hidden" name="description_renderer" value="${c.visual.default_renderer}">
173 176 ${dt.markup_form('pr-description-input', form_text=c.pull_request.description)}
174 177 </div>
175 178 </div>
176 179
177 180 <div class="field">
178 181 <div class="label-summary">
179 182 <label>${_('Versions')}:</label>
180 183 </div>
181 184
182 185 <% outdated_comm_count_ver = len(c.inline_versions[None]['outdated']) %>
183 186 <% general_outdated_comm_count_ver = len(c.comment_versions[None]['outdated']) %>
184 187
185 188 <div class="pr-versions">
186 189 % if c.show_version_changes:
187 190 <% outdated_comm_count_ver = len(c.inline_versions[c.at_version_num]['outdated']) %>
188 191 <% general_outdated_comm_count_ver = len(c.comment_versions[c.at_version_num]['outdated']) %>
189 192 <a id="show-pr-versions" class="input" onclick="return versionController.toggleVersionView(this)" href="#show-pr-versions"
190 193 data-toggle-on="${_ungettext('{} version available for this pull request, show it.', '{} versions available for this pull request, show them.', len(c.versions)).format(len(c.versions))}"
191 194 data-toggle-off="${_('Hide all versions of this pull request')}">
192 195 ${_ungettext('{} version available for this pull request, show it.', '{} versions available for this pull request, show them.', len(c.versions)).format(len(c.versions))}
193 196 </a>
194 197 <table>
195 198 ## SHOW ALL VERSIONS OF PR
196 199 <% ver_pr = None %>
197 200
198 201 % for data in reversed(list(enumerate(c.versions, 1))):
199 202 <% ver_pos = data[0] %>
200 203 <% ver = data[1] %>
201 204 <% ver_pr = ver.pull_request_version_id %>
202 205 <% display_row = '' if c.at_version and (c.at_version_num == ver_pr or c.from_version_num == ver_pr) else 'none' %>
203 206
204 207 <tr class="version-pr" style="display: ${display_row}">
205 208 <td>
206 209 <code>
207 210 <a href="${request.current_route_path(_query=dict(version=ver_pr or 'latest'))}">v${ver_pos}</a>
208 211 </code>
209 212 </td>
210 213 <td>
211 <input ${'checked="checked"' if c.from_version_num == ver_pr else ''} class="compare-radio-button" type="radio" name="ver_source" value="${ver_pr or 'latest'}" data-ver-pos="${ver_pos}"/>
212 <input ${'checked="checked"' if c.at_version_num == ver_pr else ''} class="compare-radio-button" type="radio" name="ver_target" value="${ver_pr or 'latest'}" data-ver-pos="${ver_pos}"/>
214 <input ${('checked="checked"' if c.from_version_num == ver_pr else '')} class="compare-radio-button" type="radio" name="ver_source" value="${ver_pr or 'latest'}" data-ver-pos="${ver_pos}"/>
215 <input ${('checked="checked"' if c.at_version_num == ver_pr else '')} class="compare-radio-button" type="radio" name="ver_target" value="${ver_pr or 'latest'}" data-ver-pos="${ver_pos}"/>
213 216 </td>
214 217 <td>
215 218 <% review_status = c.review_versions[ver_pr].status if ver_pr in c.review_versions else 'not_reviewed' %>
216 219 <i class="tooltip icon-circle review-status-${review_status}" title="${_('Your review status at this version')}"></i>
217 </div>
220
218 221 </td>
219 222 <td>
220 223 % if c.at_version_num != ver_pr:
221 224 <i class="icon-comment"></i>
222 225 <code class="tooltip" title="${_('Comment from pull request version v{0}, general:{1} inline:{2}').format(ver_pos, len(c.comment_versions[ver_pr]['at']), len(c.inline_versions[ver_pr]['at']))}">
223 226 G:${len(c.comment_versions[ver_pr]['at'])} / I:${len(c.inline_versions[ver_pr]['at'])}
224 227 </code>
225 228 % endif
226 229 </td>
227 230 <td>
228 231 ##<code>${ver.source_ref_parts.commit_id[:6]}</code>
229 232 </td>
230 233 <td>
231 234 ${h.age_component(ver.updated_on, time_is_local=True)}
232 235 </td>
233 236 </tr>
234 237 % endfor
235 238
236 239 <tr>
237 240 <td colspan="6">
238 241 <button id="show-version-diff" onclick="return versionController.showVersionDiff()" class="btn btn-sm" style="display: none"
239 242 data-label-text-locked="${_('select versions to show changes')}"
240 243 data-label-text-diff="${_('show changes between versions')}"
241 244 data-label-text-show="${_('show pull request for this version')}"
242 245 >
243 246 ${_('select versions to show changes')}
244 247 </button>
245 248 </td>
246 249 </tr>
247 250 </table>
248 251 % else:
249 252 <div class="input">
250 253 ${_('Pull request versions not available')}.
251 254 </div>
252 255 % endif
253 256 </div>
254 257 </div>
255 258
256 259 <div id="pr-save" class="field" style="display: none;">
257 260 <div class="label-summary"></div>
258 261 <div class="input">
259 262 <span id="edit_pull_request" class="btn btn-small no-margin">${_('Save Changes')}</span>
260 263 </div>
261 264 </div>
262 265 </div>
263 266 </div>
264 267 <div>
265 268 ## AUTHOR
266 269 <div class="reviewers-title block-right">
267 270 <div class="pr-details-title">
268 271 ${_('Author of this pull request')}
269 272 </div>
270 273 </div>
271 274 <div class="block-right pr-details-content reviewers">
272 275 <ul class="group_members">
273 276 <li>
274 277 ${self.gravatar_with_user(c.pull_request.author.email, 16, tooltip=True)}
275 278 </li>
276 279 </ul>
277 280 </div>
278 281
279 282 ## REVIEW RULES
280 283 <div id="review_rules" style="display: none" class="reviewers-title block-right">
281 284 <div class="pr-details-title">
282 285 ${_('Reviewer rules')}
283 286 %if c.allowed_to_update:
284 287 <span id="close_edit_reviewers" class="block-right action_button last-item" style="display: none;">${_('Close')}</span>
285 288 %endif
286 289 </div>
287 290 <div class="pr-reviewer-rules">
288 291 ## review rules will be appended here, by default reviewers logic
289 292 </div>
290 293 <input id="review_data" type="hidden" name="review_data" value="">
291 294 </div>
292 295
293 296 ## REVIEWERS
294 297 <div class="reviewers-title block-right">
295 298 <div class="pr-details-title">
296 299 ${_('Pull request reviewers')}
297 300 %if c.allowed_to_update:
298 301 <span id="open_edit_reviewers" class="block-right action_button last-item">${_('Edit')}</span>
299 302 %endif
300 303 </div>
301 304 </div>
302 305 <div id="reviewers" class="block-right pr-details-content reviewers">
303 306
304 307 ## members redering block
305 308 <input type="hidden" name="__start__" value="review_members:sequence">
306 309 <ul id="review_members" class="group_members">
307 310
308 311 % for review_obj, member, reasons, mandatory, status in c.pull_request_reviewers:
309 312 <script>
310 313 var member = ${h.json.dumps(h.reviewer_as_json(member, reasons=reasons, mandatory=mandatory, user_group=review_obj.rule_user_group_data()))|n};
311 314 var status = "${(status[0][1].status if status else 'not_reviewed')}";
312 315 var status_lbl = "${h.commit_status_lbl(status[0][1].status if status else 'not_reviewed')}";
313 316 var allowed_to_update = ${h.json.dumps(c.allowed_to_update)};
314 317
315 318 var entry = renderTemplate('reviewMemberEntry', {
316 319 'member': member,
317 320 'mandatory': member.mandatory,
318 321 'reasons': member.reasons,
319 322 'allowed_to_update': allowed_to_update,
320 323 'review_status': status,
321 324 'review_status_label': status_lbl,
322 325 'user_group': member.user_group,
323 326 'create': false
324 327 });
325 328 $('#review_members').append(entry)
326 329 </script>
327 330
328 331 % endfor
329 332
330 333 </ul>
331 334
332 335 <input type="hidden" name="__end__" value="review_members:sequence">
333 336 ## end members redering block
334 337
335 338 %if not c.pull_request.is_closed():
336 339 <div id="add_reviewer" class="ac" style="display: none;">
337 340 %if c.allowed_to_update:
338 341 % if not c.forbid_adding_reviewers:
339 342 <div id="add_reviewer_input" class="reviewer_ac">
340 343 ${h.text('user', class_='ac-input', placeholder=_('Add reviewer or reviewer group'))}
341 344 <div id="reviewers_container"></div>
342 345 </div>
343 346 % endif
344 347 <div class="pull-right">
345 348 <button id="update_pull_request" class="btn btn-small no-margin">${_('Save Changes')}</button>
346 349 </div>
347 350 %endif
348 351 </div>
349 352 %endif
350 353 </div>
351 354 </div>
352 355 </div>
356
353 357 <div class="box">
354 ##DIFF
358
359 % if c.state_progressing:
360 <h2 style="text-align: center">
361 ${_('Cannot show diff when pull request state is changing. Current progress state')}: <span class="tag tag-merge-state-${c.pull_request.state}">${c.pull_request.state}</span>
362 </h2>
363
364 % else:
365
366 ## Diffs rendered here
355 367 <div class="table" >
356 368 <div id="changeset_compare_view_content">
357 369 ##CS
358 370 % if c.missing_requirements:
359 371 <div class="box">
360 372 <div class="alert alert-warning">
361 373 <div>
362 374 <strong>${_('Missing requirements:')}</strong>
363 375 ${_('These commits cannot be displayed, because this repository uses the Mercurial largefiles extension, which was not enabled.')}
364 376 </div>
365 377 </div>
366 378 </div>
367 379 % elif c.missing_commits:
368 380 <div class="box">
369 381 <div class="alert alert-warning">
370 382 <div>
371 383 <strong>${_('Missing commits')}:</strong>
372 384 ${_('This pull request cannot be displayed, because one or more commits no longer exist in the source repository.')}
373 385 ${_('Please update this pull request, push the commits back into the source repository, or consider closing this pull request.')}
374 386 ${_('Consider doing a {force_refresh_url} in case you think this is an error.').format(force_refresh_url=h.link_to('force refresh', h.current_route_path(request, force_refresh='1')))|n}
375 387 </div>
376 388 </div>
377 389 </div>
378 390 % endif
379 391
380 392 <div class="compare_view_commits_title">
381 393 % if not c.compare_mode:
382 394
383 395 % if c.at_version_pos:
384 396 <h4>
385 397 ${_('Showing changes at v%d, commenting is disabled.') % c.at_version_pos}
386 398 </h4>
387 399 % endif
388 400
389 401 <div class="pull-left">
390 402 <div class="btn-group">
391 403 <a
392 404 class="btn"
393 405 href="#"
394 406 onclick="$('.compare_select').show();$('.compare_select_hidden').hide(); return false">
395 407 ${_ungettext('Expand %s commit','Expand %s commits', len(c.commit_ranges)) % len(c.commit_ranges)}
396 408 </a>
397 409 <a
398 410 class="btn"
399 411 href="#"
400 412 onclick="$('.compare_select').hide();$('.compare_select_hidden').show(); return false">
401 413 ${_ungettext('Collapse %s commit','Collapse %s commits', len(c.commit_ranges)) % len(c.commit_ranges)}
402 414 </a>
403 415 </div>
404 416 </div>
405 417
406 418 <div class="pull-right">
407 419 % if c.allowed_to_update and not c.pull_request.is_closed():
408 420
409 421 <div class="btn-group btn-group-actions">
410 422 <a id="update_commits" class="btn btn-primary no-margin" onclick="updateController.updateCommits(this); return false">
411 423 ${_('Update commits')}
412 424 </a>
413 425
414 426 <a id="update_commits_switcher" class="btn btn-primary" style="margin-left: -1px" data-toggle="dropdown" aria-pressed="false" role="button">
415 427 <i class="icon-down"></i>
416 428 </a>
417 429
418 430 <div class="btn-action-switcher-container" id="update-commits-switcher">
419 431 <ul class="btn-action-switcher" role="menu">
420 432 <li>
421 433 <a href="#forceUpdate" onclick="updateController.forceUpdateCommits(this); return false">
422 434 ${_('Force update commits')}
423 435 </a>
424 436 <div class="action-help-block">
425 437 ${_('Update commits and force refresh this pull request.')}
426 438 </div>
427 439 </li>
428 440 </ul>
429 441 </div>
430 442 </div>
431 443
432 444 % else:
433 445 <a class="tooltip btn disabled pull-right" disabled="disabled" title="${_('Update is disabled for current view')}">${_('Update commits')}</a>
434 446 % endif
435 447
436 448 </div>
437 449 % endif
438 450 </div>
439 451
440 452 % if not c.missing_commits:
441 453 % if c.compare_mode:
442 454 % if c.at_version:
443 455 <h4>
444 456 ${_('Commits and changes between v{ver_from} and {ver_to} of this pull request, commenting is disabled').format(ver_from=c.from_version_pos, ver_to=c.at_version_pos if c.at_version_pos else 'latest')}:
445 457 </h4>
446 458
447 459 <div class="subtitle-compare">
448 460 ${_('commits added: {}, removed: {}').format(len(c.commit_changes_summary.added), len(c.commit_changes_summary.removed))}
449 461 </div>
450 462
451 463 <div class="container">
452 464 <table class="rctable compare_view_commits">
453 465 <tr>
454 466 <th></th>
455 467 <th>${_('Time')}</th>
456 468 <th>${_('Author')}</th>
457 469 <th>${_('Commit')}</th>
458 470 <th></th>
459 471 <th>${_('Description')}</th>
460 472 </tr>
461 473
462 474 % for c_type, commit in c.commit_changes:
463 475 % if c_type in ['a', 'r']:
464 476 <%
465 477 if c_type == 'a':
466 478 cc_title = _('Commit added in displayed changes')
467 479 elif c_type == 'r':
468 480 cc_title = _('Commit removed in displayed changes')
469 481 else:
470 482 cc_title = ''
471 483 %>
472 484 <tr id="row-${commit.raw_id}" commit_id="${commit.raw_id}" class="compare_select">
473 485 <td>
474 486 <div class="commit-change-indicator color-${c_type}-border">
475 487 <div class="commit-change-content color-${c_type} tooltip" title="${h.tooltip(cc_title)}">
476 488 ${c_type.upper()}
477 489 </div>
478 490 </div>
479 491 </td>
480 492 <td class="td-time">
481 493 ${h.age_component(commit.date)}
482 494 </td>
483 495 <td class="td-user">
484 496 ${base.gravatar_with_user(commit.author, 16, tooltip=True)}
485 497 </td>
486 498 <td class="td-hash">
487 499 <code>
488 500 <a href="${h.route_path('repo_commit', repo_name=c.target_repo.repo_name, commit_id=commit.raw_id)}">
489 501 r${commit.idx}:${h.short_id(commit.raw_id)}
490 502 </a>
491 503 ${h.hidden('revisions', commit.raw_id)}
492 504 </code>
493 505 </td>
494 506 <td class="td-message expand_commit" data-commit-id="${commit.raw_id}" title="${_( 'Expand commit message')}" onclick="commitsController.expandCommit(this); return false">
495 507 <i class="icon-expand-linked"></i>
496 508 </td>
497 509 <td class="mid td-description">
498 510 <div class="log-container truncate-wrap">
499 511 <div class="message truncate" id="c-${commit.raw_id}" data-message-raw="${commit.message}">${h.urlify_commit_message(commit.message, c.repo_name)}</div>
500 512 </div>
501 513 </td>
502 514 </tr>
503 515 % endif
504 516 % endfor
505 517 </table>
506 518 </div>
507 519
508 520 % endif
509 521
510 522 % else:
511 523 <%include file="/compare/compare_commits.mako" />
512 524 % endif
513 525
514 526 <div class="cs_files">
515 527 <%namespace name="cbdiffs" file="/codeblocks/diffs.mako"/>
516 528 % if c.at_version:
517 529 <% c.inline_cnt = len(c.inline_versions[c.at_version_num]['display']) %>
518 530 <% c.comments = c.comment_versions[c.at_version_num]['display'] %>
519 531 % else:
520 532 <% c.inline_cnt = len(c.inline_versions[c.at_version_num]['until']) %>
521 533 <% c.comments = c.comment_versions[c.at_version_num]['until'] %>
522 534 % endif
523 535
524 536 <%
525 537 pr_menu_data = {
526 538 'outdated_comm_count_ver': outdated_comm_count_ver
527 539 }
528 540 %>
529 541
530 542 ${cbdiffs.render_diffset_menu(c.diffset, range_diff_on=c.range_diff_on)}
531 543
532 544 % if c.range_diff_on:
533 545 % for commit in c.commit_ranges:
534 546 ${cbdiffs.render_diffset(
535 547 c.changes[commit.raw_id],
536 548 commit=commit, use_comments=True,
537 549 collapse_when_files_over=5,
538 550 disable_new_comments=True,
539 551 deleted_files_comments=c.deleted_files_comments,
540 552 inline_comments=c.inline_comments,
541 553 pull_request_menu=pr_menu_data)}
542 554 % endfor
543 555 % else:
544 556 ${cbdiffs.render_diffset(
545 557 c.diffset, use_comments=True,
546 558 collapse_when_files_over=30,
547 559 disable_new_comments=not c.allowed_to_comment,
548 560 deleted_files_comments=c.deleted_files_comments,
549 561 inline_comments=c.inline_comments,
550 562 pull_request_menu=pr_menu_data)}
551 563 % endif
552 564
553 565 </div>
554 566 % else:
555 567 ## skipping commits we need to clear the view for missing commits
556 568 <div style="clear:both;"></div>
557 569 % endif
558 570
559 571 </div>
560 572 </div>
561 573
562 574 ## template for inline comment form
563 575 <%namespace name="comment" file="/changeset/changeset_file_comment.mako"/>
564 576
565 577 ## comments heading with count
566 578 <div class="comments-heading">
567 579 <i class="icon-comment"></i>
568 580 ${_('Comments')} ${len(c.comments)}
569 581 </div>
570 582
571 583 ## render general comments
572 584 <div id="comment-tr-show">
573 585 % if general_outdated_comm_count_ver:
574 586 <div class="info-box">
575 587 % if general_outdated_comm_count_ver == 1:
576 588 ${_('there is {num} general comment from older versions').format(num=general_outdated_comm_count_ver)},
577 589 <a href="#show-hidden-comments" onclick="$('.comment-general.comment-outdated').show(); $(this).parent().hide(); return false;">${_('show it')}</a>
578 590 % else:
579 591 ${_('there are {num} general comments from older versions').format(num=general_outdated_comm_count_ver)},
580 592 <a href="#show-hidden-comments" onclick="$('.comment-general.comment-outdated').show(); $(this).parent().hide(); return false;">${_('show them')}</a>
581 593 % endif
582 594 </div>
583 595 % endif
584 596 </div>
585 597
586 598 ${comment.generate_comments(c.comments, include_pull_request=True, is_pull_request=True)}
587 599
588 600 % if not c.pull_request.is_closed():
589 601 ## main comment form and it status
590 602 ${comment.comments(h.route_path('pullrequest_comment_create', repo_name=c.repo_name,
591 603 pull_request_id=c.pull_request.pull_request_id),
592 604 c.pull_request_review_status,
593 605 is_pull_request=True, change_status=c.allowed_to_change_status)}
594 606
595 607 ## merge status, and merge action
596 608 <div class="pull-request-merge">
597 609 <%include file="/pullrequests/pullrequest_merge_checks.mako"/>
598 610 </div>
599 611
600 612 %endif
601 613
602 <script type="text/javascript">
614 % endif
615 </div>
616
617 <script type="text/javascript">
603 618
604 619 versionController = new VersionController();
605 620 versionController.init();
606 621
607 622 reviewersController = new ReviewersController();
608 623 commitsController = new CommitsController();
609 624
610 625 updateController = new UpdatePrController();
611 626
612 627 $(function(){
613 628
614 629 // custom code mirror
615 630 var codeMirrorInstance = $('#pr-description-input').get(0).MarkupForm.cm;
616 631
617 632 var PRDetails = {
618 633 editButton: $('#open_edit_pullrequest'),
619 634 closeButton: $('#close_edit_pullrequest'),
620 635 deleteButton: $('#delete_pullrequest'),
621 636 viewFields: $('#pr-desc, #pr-title'),
622 637 editFields: $('#pr-desc-edit, #pr-title-edit, #pr-save'),
623 638
624 639 init: function() {
625 640 var that = this;
626 641 this.editButton.on('click', function(e) { that.edit(); });
627 642 this.closeButton.on('click', function(e) { that.view(); });
628 643 },
629 644
630 645 edit: function(event) {
631 646 this.viewFields.hide();
632 647 this.editButton.hide();
633 648 this.deleteButton.hide();
634 649 this.closeButton.show();
635 650 this.editFields.show();
636 651 codeMirrorInstance.refresh();
637 652 },
638 653
639 654 view: function(event) {
640 655 this.editButton.show();
641 656 this.deleteButton.show();
642 657 this.editFields.hide();
643 658 this.closeButton.hide();
644 659 this.viewFields.show();
645 660 }
646 661 };
647 662
648 663 var ReviewersPanel = {
649 664 editButton: $('#open_edit_reviewers'),
650 665 closeButton: $('#close_edit_reviewers'),
651 666 addButton: $('#add_reviewer'),
652 667 removeButtons: $('.reviewer_member_remove,.reviewer_member_mandatory_remove'),
653 668
654 669 init: function() {
655 670 var self = this;
656 671 this.editButton.on('click', function(e) { self.edit(); });
657 672 this.closeButton.on('click', function(e) { self.close(); });
658 673 },
659 674
660 675 edit: function(event) {
661 676 this.editButton.hide();
662 677 this.closeButton.show();
663 678 this.addButton.show();
664 679 this.removeButtons.css('visibility', 'visible');
665 680 // review rules
666 681 reviewersController.loadReviewRules(
667 682 ${c.pull_request.reviewer_data_json | n});
668 683 },
669 684
670 685 close: function(event) {
671 686 this.editButton.show();
672 687 this.closeButton.hide();
673 688 this.addButton.hide();
674 689 this.removeButtons.css('visibility', 'hidden');
675 690 // hide review rules
676 691 reviewersController.hideReviewRules()
677 692 }
678 693 };
679 694
680 695 PRDetails.init();
681 696 ReviewersPanel.init();
682 697
683 698 showOutdated = function(self){
684 699 $('.comment-inline.comment-outdated').show();
685 700 $('.filediff-outdated').show();
686 701 $('.showOutdatedComments').hide();
687 702 $('.hideOutdatedComments').show();
688 703 };
689 704
690 705 hideOutdated = function(self){
691 706 $('.comment-inline.comment-outdated').hide();
692 707 $('.filediff-outdated').hide();
693 708 $('.hideOutdatedComments').hide();
694 709 $('.showOutdatedComments').show();
695 710 };
696 711
697 712 refreshMergeChecks = function(){
698 713 var loadUrl = "${request.current_route_path(_query=dict(merge_checks=1))}";
699 714 $('.pull-request-merge').css('opacity', 0.3);
700 715 $('.action-buttons-extra').css('opacity', 0.3);
701 716
702 717 $('.pull-request-merge').load(
703 718 loadUrl, function() {
704 719 $('.pull-request-merge').css('opacity', 1);
705 720
706 721 $('.action-buttons-extra').css('opacity', 1);
707 722 }
708 723 );
709 724 };
710 725
711 726 closePullRequest = function (status) {
712 727 if (!confirm(_gettext('Are you sure to close this pull request without merging?'))) {
713 728 return false;
714 729 }
715 730 // inject closing flag
716 731 $('.action-buttons-extra').append('<input type="hidden" class="close-pr-input" id="close_pull_request" value="1">');
717 732 $(generalCommentForm.statusChange).select2("val", status).trigger('change');
718 733 $(generalCommentForm.submitForm).submit();
719 734 };
720 735
721 736 $('#show-outdated-comments').on('click', function(e){
722 737 var button = $(this);
723 738 var outdated = $('.comment-outdated');
724 739
725 740 if (button.html() === "(Show)") {
726 741 button.html("(Hide)");
727 742 outdated.show();
728 743 } else {
729 744 button.html("(Show)");
730 745 outdated.hide();
731 746 }
732 747 });
733 748
734 749 $('.show-inline-comments').on('change', function(e){
735 750 var show = 'none';
736 751 var target = e.currentTarget;
737 752 if(target.checked){
738 753 show = ''
739 754 }
740 755 var boxid = $(target).attr('id_for');
741 756 var comments = $('#{0} .inline-comments'.format(boxid));
742 757 var fn_display = function(idx){
743 758 $(this).css('display', show);
744 759 };
745 760 $(comments).each(fn_display);
746 761 var btns = $('#{0} .inline-comments-button'.format(boxid));
747 762 $(btns).each(fn_display);
748 763 });
749 764
750 765 $('#merge_pull_request_form').submit(function() {
751 766 if (!$('#merge_pull_request').attr('disabled')) {
752 767 $('#merge_pull_request').attr('disabled', 'disabled');
753 768 }
754 769 return true;
755 770 });
756 771
757 772 $('#edit_pull_request').on('click', function(e){
758 773 var title = $('#pr-title-input').val();
759 774 var description = codeMirrorInstance.getValue();
760 775 var renderer = $('#pr-renderer-input').val();
761 776 editPullRequest(
762 777 "${c.repo_name}", "${c.pull_request.pull_request_id}",
763 778 title, description, renderer);
764 779 });
765 780
766 781 $('#update_pull_request').on('click', function(e){
767 782 $(this).attr('disabled', 'disabled');
768 783 $(this).addClass('disabled');
769 784 $(this).html(_gettext('Saving...'));
770 785 reviewersController.updateReviewers(
771 786 "${c.repo_name}", "${c.pull_request.pull_request_id}");
772 787 });
773 788
774 789
775 790 // fixing issue with caches on firefox
776 791 $('#update_commits').removeAttr("disabled");
777 792
778 793 $('.show-inline-comments').on('click', function(e){
779 794 var boxid = $(this).attr('data-comment-id');
780 795 var button = $(this);
781 796
782 797 if(button.hasClass("comments-visible")) {
783 798 $('#{0} .inline-comments'.format(boxid)).each(function(index){
784 799 $(this).hide();
785 800 });
786 801 button.removeClass("comments-visible");
787 802 } else {
788 803 $('#{0} .inline-comments'.format(boxid)).each(function(index){
789 804 $(this).show();
790 805 });
791 806 button.addClass("comments-visible");
792 807 }
793 808 });
794 809
795 810 // register submit callback on commentForm form to track TODOs
796 811 window.commentFormGlobalSubmitSuccessCallback = function(){
797 812 refreshMergeChecks();
798 813 };
799 814
800 815 ReviewerAutoComplete('#user');
801 816
802 817 })
803 818
804 819 </script>
805
806 </div>
807 820 </div>
808 821
809 822 </%def>
@@ -1,143 +1,140 b''
1 1 <%inherit file="/base/base.mako"/>
2 2
3 3 <%def name="title()">
4 4 ${_('{} Pull Requests').format(c.repo_name)}
5 5 %if c.rhodecode_name:
6 6 &middot; ${h.branding(c.rhodecode_name)}
7 7 %endif
8 8 </%def>
9 9
10 10 <%def name="breadcrumbs_links()"></%def>
11 11
12 12 <%def name="menu_bar_nav()">
13 13 ${self.menu_items(active='repositories')}
14 14 </%def>
15 15
16 16
17 17 <%def name="menu_bar_subnav()">
18 18 ${self.repo_menu(active='showpullrequest')}
19 19 </%def>
20 20
21 21
22 22 <%def name="main()">
23 23
24 24 <div class="box">
25 25 <div class="title">
26 26 <ul class="button-links">
27 27 <li class="btn ${h.is_active('open', c.active)}"><a href="${h.route_path('pullrequest_show_all',repo_name=c.repo_name, _query={'source':0})}">${_('Opened')}</a></li>
28 28 <li class="btn ${h.is_active('my', c.active)}"><a href="${h.route_path('pullrequest_show_all',repo_name=c.repo_name, _query={'source':0,'my':1})}">${_('Opened by me')}</a></li>
29 29 <li class="btn ${h.is_active('awaiting', c.active)}"><a href="${h.route_path('pullrequest_show_all',repo_name=c.repo_name, _query={'source':0,'awaiting_review':1})}">${_('Awaiting review')}</a></li>
30 30 <li class="btn ${h.is_active('awaiting_my', c.active)}"><a href="${h.route_path('pullrequest_show_all',repo_name=c.repo_name, _query={'source':0,'awaiting_my_review':1})}">${_('Awaiting my review')}</a></li>
31 31 <li class="btn ${h.is_active('closed', c.active)}"><a href="${h.route_path('pullrequest_show_all',repo_name=c.repo_name, _query={'source':0,'closed':1})}">${_('Closed')}</a></li>
32 32 <li class="btn ${h.is_active('source', c.active)}"><a href="${h.route_path('pullrequest_show_all',repo_name=c.repo_name, _query={'source':1})}">${_('From this repo')}</a></li>
33 33 </ul>
34 34
35 35 <ul class="links">
36 36 % if c.rhodecode_user.username != h.DEFAULT_USER:
37 37 <li>
38 38 <span>
39 39 <a id="open_new_pull_request" class="btn btn-small btn-success" href="${h.route_path('pullrequest_new',repo_name=c.repo_name)}">
40 40 ${_('Open new Pull Request')}
41 41 </a>
42 42 </span>
43 43 </li>
44 44 % endif
45 45
46 46 <li>
47 47 <div class="grid-quick-filter">
48 48 <ul class="grid-filter-box">
49 49 <li class="grid-filter-box-icon">
50 50 <i class="icon-search"></i>
51 51 </li>
52 52 <li class="grid-filter-box-input">
53 53 <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value=""/>
54 54 </li>
55 55 </ul>
56 56 </div>
57 57 </li>
58 58
59 59 </ul>
60 60
61 61 </div>
62 62
63 63 <div class="main-content-full-width">
64 64 <table id="pull_request_list_table" class="display"></table>
65 65 </div>
66 66
67 67 </div>
68 68
69 69 <script type="text/javascript">
70 70 $(document).ready(function() {
71 71 var $pullRequestListTable = $('#pull_request_list_table');
72 72
73 73 // object list
74 74 $pullRequestListTable.DataTable({
75 75 processing: true,
76 76 serverSide: true,
77 77 ajax: {
78 78 "url": "${h.route_path('pullrequest_show_all_data', repo_name=c.repo_name)}",
79 79 "data": function (d) {
80 80 d.source = "${c.source}";
81 81 d.closed = "${c.closed}";
82 82 d.my = "${c.my}";
83 83 d.awaiting_review = "${c.awaiting_review}";
84 84 d.awaiting_my_review = "${c.awaiting_my_review}";
85 85 }
86 86 },
87 87 dom: 'rtp',
88 88 pageLength: ${c.visual.dashboard_items},
89 89 order: [[ 1, "desc" ]],
90 90 columns: [
91 91 { data: {"_": "status",
92 92 "sort": "status"}, title: "", className: "td-status", orderable: false},
93 93 { data: {"_": "name",
94 94 "sort": "name_raw"}, title: "${_('Id')}", className: "td-componentname", "type": "num" },
95 95 { data: {"_": "title",
96 96 "sort": "title"}, title: "${_('Title')}", className: "td-description" },
97 97 { data: {"_": "author",
98 98 "sort": "author_raw"}, title: "${_('Author')}", className: "td-user", orderable: false },
99 99 { data: {"_": "comments",
100 100 "sort": "comments_raw"}, title: "", className: "td-comments", orderable: false},
101 101 { data: {"_": "updated_on",
102 102 "sort": "updated_on_raw"}, title: "${_('Last Update')}", className: "td-time" }
103 103 ],
104 104 language: {
105 105 paginate: DEFAULT_GRID_PAGINATION,
106 106 sProcessing: _gettext('loading...'),
107 107 emptyTable: _gettext("No pull requests available yet.")
108 108 },
109 109 "drawCallback": function( settings, json ) {
110 110 timeagoActivate();
111 111 tooltipActivate();
112 112 },
113 113 "createdRow": function ( row, data, index ) {
114 114 if (data['closed']) {
115 115 $(row).addClass('closed');
116 116 }
117 if (data['state'] !== 'created') {
118 $(row).addClass('state-' + data['state']);
119 }
120 117 }
121 118 });
122 119
123 120 $pullRequestListTable.on('xhr.dt', function(e, settings, json, xhr){
124 121 $pullRequestListTable.css('opacity', 1);
125 122 });
126 123
127 124 $pullRequestListTable.on('preXhr.dt', function(e, settings, data){
128 125 $pullRequestListTable.css('opacity', 0.3);
129 126 });
130 127
131 128 // filter
132 129 $('#q_filter').on('keyup',
133 130 $.debounce(250, function() {
134 131 $pullRequestListTable.DataTable().search(
135 132 $('#q_filter').val()
136 133 ).draw();
137 134 })
138 135 );
139 136
140 137 });
141 138
142 139 </script>
143 140 </%def>
General Comments 0
You need to be logged in to leave comments. Login now