##// END OF EJS Templates
comments: use unified aggregation of comments counters....
marcink -
r1332:f4e615fc default
parent child Browse files
Show More
@@ -1,1029 +1,1018 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2012-2017 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 pull requests controller for rhodecode for initializing pull requests
23 23 """
24 24 import types
25 25
26 26 import peppercorn
27 27 import formencode
28 28 import logging
29 29 import collections
30 30
31 31 from webob.exc import HTTPNotFound, HTTPForbidden, HTTPBadRequest
32 32 from pylons import request, tmpl_context as c, url
33 33 from pylons.controllers.util import redirect
34 34 from pylons.i18n.translation import _
35 35 from pyramid.threadlocal import get_current_registry
36 36 from sqlalchemy.sql import func
37 37 from sqlalchemy.sql.expression import or_
38 38
39 39 from rhodecode import events
40 40 from rhodecode.lib import auth, diffs, helpers as h, codeblocks
41 41 from rhodecode.lib.ext_json import json
42 42 from rhodecode.lib.base import (
43 43 BaseRepoController, render, vcs_operation_context)
44 44 from rhodecode.lib.auth import (
45 45 LoginRequired, HasRepoPermissionAnyDecorator, NotAnonymous,
46 46 HasAcceptedRepoType, XHRRequired)
47 47 from rhodecode.lib.channelstream import channelstream_request
48 48 from rhodecode.lib.utils import jsonify
49 49 from rhodecode.lib.utils2 import (
50 50 safe_int, safe_str, str2bool, safe_unicode)
51 51 from rhodecode.lib.vcs.backends.base import (
52 52 EmptyCommit, UpdateFailureReason, EmptyRepository)
53 53 from rhodecode.lib.vcs.exceptions import (
54 54 EmptyRepositoryError, CommitDoesNotExistError, RepositoryRequirementError,
55 55 NodeDoesNotExistError)
56 56
57 57 from rhodecode.model.changeset_status import ChangesetStatusModel
58 58 from rhodecode.model.comment import CommentsModel
59 59 from rhodecode.model.db import (PullRequest, ChangesetStatus, ChangesetComment,
60 60 Repository, PullRequestVersion)
61 61 from rhodecode.model.forms import PullRequestForm
62 62 from rhodecode.model.meta import Session
63 63 from rhodecode.model.pull_request import PullRequestModel
64 64
65 65 log = logging.getLogger(__name__)
66 66
67 67
68 68 class PullrequestsController(BaseRepoController):
69 69 def __before__(self):
70 70 super(PullrequestsController, self).__before__()
71 71
72 72 def _load_compare_data(self, pull_request, inline_comments):
73 73 """
74 74 Load context data needed for generating compare diff
75 75
76 76 :param pull_request: object related to the request
77 77 :param enable_comments: flag to determine if comments are included
78 78 """
79 79 source_repo = pull_request.source_repo
80 80 source_ref_id = pull_request.source_ref_parts.commit_id
81 81
82 82 target_repo = pull_request.target_repo
83 83 target_ref_id = pull_request.target_ref_parts.commit_id
84 84
85 85 # despite opening commits for bookmarks/branches/tags, we always
86 86 # convert this to rev to prevent changes after bookmark or branch change
87 87 c.source_ref_type = 'rev'
88 88 c.source_ref = source_ref_id
89 89
90 90 c.target_ref_type = 'rev'
91 91 c.target_ref = target_ref_id
92 92
93 93 c.source_repo = source_repo
94 94 c.target_repo = target_repo
95 95
96 96 c.fulldiff = bool(request.GET.get('fulldiff'))
97 97
98 98 # diff_limit is the old behavior, will cut off the whole diff
99 99 # if the limit is applied otherwise will just hide the
100 100 # big files from the front-end
101 101 diff_limit = self.cut_off_limit_diff
102 102 file_limit = self.cut_off_limit_file
103 103
104 104 pre_load = ["author", "branch", "date", "message"]
105 105
106 106 c.commit_ranges = []
107 107 source_commit = EmptyCommit()
108 108 target_commit = EmptyCommit()
109 109 c.missing_requirements = False
110 110 try:
111 111 c.commit_ranges = [
112 112 source_repo.get_commit(commit_id=rev, pre_load=pre_load)
113 113 for rev in pull_request.revisions]
114 114
115 115 c.statuses = source_repo.statuses(
116 116 [x.raw_id for x in c.commit_ranges])
117 117
118 118 target_commit = source_repo.get_commit(
119 119 commit_id=safe_str(target_ref_id))
120 120 source_commit = source_repo.get_commit(
121 121 commit_id=safe_str(source_ref_id))
122 122 except RepositoryRequirementError:
123 123 c.missing_requirements = True
124 124
125 125 # auto collapse if we have more than limit
126 126 collapse_limit = diffs.DiffProcessor._collapse_commits_over
127 127 c.collapse_all_commits = len(c.commit_ranges) > collapse_limit
128 128
129 129 c.changes = {}
130 130 c.missing_commits = False
131 131 if (c.missing_requirements or
132 132 isinstance(source_commit, EmptyCommit) or
133 133 source_commit == target_commit):
134 134 _parsed = []
135 135 c.missing_commits = True
136 136 else:
137 137 vcs_diff = PullRequestModel().get_diff(pull_request)
138 138 diff_processor = diffs.DiffProcessor(
139 139 vcs_diff, format='newdiff', diff_limit=diff_limit,
140 140 file_limit=file_limit, show_full_diff=c.fulldiff)
141 141
142 142 _parsed = diff_processor.prepare()
143 143 c.limited_diff = isinstance(_parsed, diffs.LimitedDiffContainer)
144 144
145 145 included_files = {}
146 146 for f in _parsed:
147 147 included_files[f['filename']] = f['stats']
148 148
149 149 c.deleted_files = [fname for fname in inline_comments if
150 150 fname not in included_files]
151 151
152 152 c.deleted_files_comments = collections.defaultdict(dict)
153 153 for fname, per_line_comments in inline_comments.items():
154 154 if fname in c.deleted_files:
155 155 c.deleted_files_comments[fname]['stats'] = 0
156 156 c.deleted_files_comments[fname]['comments'] = list()
157 157 for lno, comments in per_line_comments.items():
158 158 c.deleted_files_comments[fname]['comments'].extend(comments)
159 159
160 160 def _node_getter(commit):
161 161 def get_node(fname):
162 162 try:
163 163 return commit.get_node(fname)
164 164 except NodeDoesNotExistError:
165 165 return None
166 166 return get_node
167 167
168 168 c.diffset = codeblocks.DiffSet(
169 169 repo_name=c.repo_name,
170 170 source_repo_name=c.source_repo.repo_name,
171 171 source_node_getter=_node_getter(target_commit),
172 172 target_node_getter=_node_getter(source_commit),
173 173 comments=inline_comments
174 174 ).render_patchset(_parsed, target_commit.raw_id, source_commit.raw_id)
175 175
176 176 def _extract_ordering(self, request):
177 177 column_index = safe_int(request.GET.get('order[0][column]'))
178 178 order_dir = request.GET.get('order[0][dir]', 'desc')
179 179 order_by = request.GET.get(
180 180 'columns[%s][data][sort]' % column_index, 'name_raw')
181 181 return order_by, order_dir
182 182
183 183 @LoginRequired()
184 184 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
185 185 'repository.admin')
186 186 @HasAcceptedRepoType('git', 'hg')
187 187 def show_all(self, repo_name):
188 188 # filter types
189 189 c.active = 'open'
190 190 c.source = str2bool(request.GET.get('source'))
191 191 c.closed = str2bool(request.GET.get('closed'))
192 192 c.my = str2bool(request.GET.get('my'))
193 193 c.awaiting_review = str2bool(request.GET.get('awaiting_review'))
194 194 c.awaiting_my_review = str2bool(request.GET.get('awaiting_my_review'))
195 195 c.repo_name = repo_name
196 196
197 197 opened_by = None
198 198 if c.my:
199 199 c.active = 'my'
200 200 opened_by = [c.rhodecode_user.user_id]
201 201
202 202 statuses = [PullRequest.STATUS_NEW, PullRequest.STATUS_OPEN]
203 203 if c.closed:
204 204 c.active = 'closed'
205 205 statuses = [PullRequest.STATUS_CLOSED]
206 206
207 207 if c.awaiting_review and not c.source:
208 208 c.active = 'awaiting'
209 209 if c.source and not c.awaiting_review:
210 210 c.active = 'source'
211 211 if c.awaiting_my_review:
212 212 c.active = 'awaiting_my'
213 213
214 214 data = self._get_pull_requests_list(
215 215 repo_name=repo_name, opened_by=opened_by, statuses=statuses)
216 216 if not request.is_xhr:
217 217 c.data = json.dumps(data['data'])
218 218 c.records_total = data['recordsTotal']
219 219 return render('/pullrequests/pullrequests.mako')
220 220 else:
221 221 return json.dumps(data)
222 222
223 223 def _get_pull_requests_list(self, repo_name, opened_by, statuses):
224 224 # pagination
225 225 start = safe_int(request.GET.get('start'), 0)
226 226 length = safe_int(request.GET.get('length'), c.visual.dashboard_items)
227 227 order_by, order_dir = self._extract_ordering(request)
228 228
229 229 if c.awaiting_review:
230 230 pull_requests = PullRequestModel().get_awaiting_review(
231 231 repo_name, source=c.source, opened_by=opened_by,
232 232 statuses=statuses, offset=start, length=length,
233 233 order_by=order_by, order_dir=order_dir)
234 234 pull_requests_total_count = PullRequestModel(
235 235 ).count_awaiting_review(
236 236 repo_name, source=c.source, statuses=statuses,
237 237 opened_by=opened_by)
238 238 elif c.awaiting_my_review:
239 239 pull_requests = PullRequestModel().get_awaiting_my_review(
240 240 repo_name, source=c.source, opened_by=opened_by,
241 241 user_id=c.rhodecode_user.user_id, statuses=statuses,
242 242 offset=start, length=length, order_by=order_by,
243 243 order_dir=order_dir)
244 244 pull_requests_total_count = PullRequestModel(
245 245 ).count_awaiting_my_review(
246 246 repo_name, source=c.source, user_id=c.rhodecode_user.user_id,
247 247 statuses=statuses, opened_by=opened_by)
248 248 else:
249 249 pull_requests = PullRequestModel().get_all(
250 250 repo_name, source=c.source, opened_by=opened_by,
251 251 statuses=statuses, offset=start, length=length,
252 252 order_by=order_by, order_dir=order_dir)
253 253 pull_requests_total_count = PullRequestModel().count_all(
254 254 repo_name, source=c.source, statuses=statuses,
255 255 opened_by=opened_by)
256 256
257 257 from rhodecode.lib.utils import PartialRenderer
258 258 _render = PartialRenderer('data_table/_dt_elements.mako')
259 259 data = []
260 260 for pr in pull_requests:
261 261 comments = CommentsModel().get_all_comments(
262 262 c.rhodecode_db_repo.repo_id, pull_request=pr)
263 263
264 264 data.append({
265 265 'name': _render('pullrequest_name',
266 266 pr.pull_request_id, pr.target_repo.repo_name),
267 267 'name_raw': pr.pull_request_id,
268 268 'status': _render('pullrequest_status',
269 269 pr.calculated_review_status()),
270 270 'title': _render(
271 271 'pullrequest_title', pr.title, pr.description),
272 272 'description': h.escape(pr.description),
273 273 'updated_on': _render('pullrequest_updated_on',
274 274 h.datetime_to_time(pr.updated_on)),
275 275 'updated_on_raw': h.datetime_to_time(pr.updated_on),
276 276 'created_on': _render('pullrequest_updated_on',
277 277 h.datetime_to_time(pr.created_on)),
278 278 'created_on_raw': h.datetime_to_time(pr.created_on),
279 279 'author': _render('pullrequest_author',
280 280 pr.author.full_contact, ),
281 281 'author_raw': pr.author.full_name,
282 282 'comments': _render('pullrequest_comments', len(comments)),
283 283 'comments_raw': len(comments),
284 284 'closed': pr.is_closed(),
285 285 })
286 286 # json used to render the grid
287 287 data = ({
288 288 'data': data,
289 289 'recordsTotal': pull_requests_total_count,
290 290 'recordsFiltered': pull_requests_total_count,
291 291 })
292 292 return data
293 293
294 294 @LoginRequired()
295 295 @NotAnonymous()
296 296 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
297 297 'repository.admin')
298 298 @HasAcceptedRepoType('git', 'hg')
299 299 def index(self):
300 300 source_repo = c.rhodecode_db_repo
301 301
302 302 try:
303 303 source_repo.scm_instance().get_commit()
304 304 except EmptyRepositoryError:
305 305 h.flash(h.literal(_('There are no commits yet')),
306 306 category='warning')
307 307 redirect(url('summary_home', repo_name=source_repo.repo_name))
308 308
309 309 commit_id = request.GET.get('commit')
310 310 branch_ref = request.GET.get('branch')
311 311 bookmark_ref = request.GET.get('bookmark')
312 312
313 313 try:
314 314 source_repo_data = PullRequestModel().generate_repo_data(
315 315 source_repo, commit_id=commit_id,
316 316 branch=branch_ref, bookmark=bookmark_ref)
317 317 except CommitDoesNotExistError as e:
318 318 log.exception(e)
319 319 h.flash(_('Commit does not exist'), 'error')
320 320 redirect(url('pullrequest_home', repo_name=source_repo.repo_name))
321 321
322 322 default_target_repo = source_repo
323 323
324 324 if source_repo.parent:
325 325 parent_vcs_obj = source_repo.parent.scm_instance()
326 326 if parent_vcs_obj and not parent_vcs_obj.is_empty():
327 327 # change default if we have a parent repo
328 328 default_target_repo = source_repo.parent
329 329
330 330 target_repo_data = PullRequestModel().generate_repo_data(
331 331 default_target_repo)
332 332
333 333 selected_source_ref = source_repo_data['refs']['selected_ref']
334 334
335 335 title_source_ref = selected_source_ref.split(':', 2)[1]
336 336 c.default_title = PullRequestModel().generate_pullrequest_title(
337 337 source=source_repo.repo_name,
338 338 source_ref=title_source_ref,
339 339 target=default_target_repo.repo_name
340 340 )
341 341
342 342 c.default_repo_data = {
343 343 'source_repo_name': source_repo.repo_name,
344 344 'source_refs_json': json.dumps(source_repo_data),
345 345 'target_repo_name': default_target_repo.repo_name,
346 346 'target_refs_json': json.dumps(target_repo_data),
347 347 }
348 348 c.default_source_ref = selected_source_ref
349 349
350 350 return render('/pullrequests/pullrequest.mako')
351 351
352 352 @LoginRequired()
353 353 @NotAnonymous()
354 354 @XHRRequired()
355 355 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
356 356 'repository.admin')
357 357 @jsonify
358 358 def get_repo_refs(self, repo_name, target_repo_name):
359 359 repo = Repository.get_by_repo_name(target_repo_name)
360 360 if not repo:
361 361 raise HTTPNotFound
362 362 return PullRequestModel().generate_repo_data(repo)
363 363
364 364 @LoginRequired()
365 365 @NotAnonymous()
366 366 @XHRRequired()
367 367 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
368 368 'repository.admin')
369 369 @jsonify
370 370 def get_repo_destinations(self, repo_name):
371 371 repo = Repository.get_by_repo_name(repo_name)
372 372 if not repo:
373 373 raise HTTPNotFound
374 374 filter_query = request.GET.get('query')
375 375
376 376 query = Repository.query() \
377 377 .order_by(func.length(Repository.repo_name)) \
378 378 .filter(or_(
379 379 Repository.repo_name == repo.repo_name,
380 380 Repository.fork_id == repo.repo_id))
381 381
382 382 if filter_query:
383 383 ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
384 384 query = query.filter(
385 385 Repository.repo_name.ilike(ilike_expression))
386 386
387 387 add_parent = False
388 388 if repo.parent:
389 389 if filter_query in repo.parent.repo_name:
390 390 parent_vcs_obj = repo.parent.scm_instance()
391 391 if parent_vcs_obj and not parent_vcs_obj.is_empty():
392 392 add_parent = True
393 393
394 394 limit = 20 - 1 if add_parent else 20
395 395 all_repos = query.limit(limit).all()
396 396 if add_parent:
397 397 all_repos += [repo.parent]
398 398
399 399 repos = []
400 400 for obj in self.scm_model.get_repos(all_repos):
401 401 repos.append({
402 402 'id': obj['name'],
403 403 'text': obj['name'],
404 404 'type': 'repo',
405 405 'obj': obj['dbrepo']
406 406 })
407 407
408 408 data = {
409 409 'more': False,
410 410 'results': [{
411 411 'text': _('Repositories'),
412 412 'children': repos
413 413 }] if repos else []
414 414 }
415 415 return data
416 416
417 417 @LoginRequired()
418 418 @NotAnonymous()
419 419 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
420 420 'repository.admin')
421 421 @HasAcceptedRepoType('git', 'hg')
422 422 @auth.CSRFRequired()
423 423 def create(self, repo_name):
424 424 repo = Repository.get_by_repo_name(repo_name)
425 425 if not repo:
426 426 raise HTTPNotFound
427 427
428 428 controls = peppercorn.parse(request.POST.items())
429 429
430 430 try:
431 431 _form = PullRequestForm(repo.repo_id)().to_python(controls)
432 432 except formencode.Invalid as errors:
433 433 if errors.error_dict.get('revisions'):
434 434 msg = 'Revisions: %s' % errors.error_dict['revisions']
435 435 elif errors.error_dict.get('pullrequest_title'):
436 436 msg = _('Pull request requires a title with min. 3 chars')
437 437 else:
438 438 msg = _('Error creating pull request: {}').format(errors)
439 439 log.exception(msg)
440 440 h.flash(msg, 'error')
441 441
442 442 # would rather just go back to form ...
443 443 return redirect(url('pullrequest_home', repo_name=repo_name))
444 444
445 445 source_repo = _form['source_repo']
446 446 source_ref = _form['source_ref']
447 447 target_repo = _form['target_repo']
448 448 target_ref = _form['target_ref']
449 449 commit_ids = _form['revisions'][::-1]
450 450 reviewers = [
451 451 (r['user_id'], r['reasons']) for r in _form['review_members']]
452 452
453 453 # find the ancestor for this pr
454 454 source_db_repo = Repository.get_by_repo_name(_form['source_repo'])
455 455 target_db_repo = Repository.get_by_repo_name(_form['target_repo'])
456 456
457 457 source_scm = source_db_repo.scm_instance()
458 458 target_scm = target_db_repo.scm_instance()
459 459
460 460 source_commit = source_scm.get_commit(source_ref.split(':')[-1])
461 461 target_commit = target_scm.get_commit(target_ref.split(':')[-1])
462 462
463 463 ancestor = source_scm.get_common_ancestor(
464 464 source_commit.raw_id, target_commit.raw_id, target_scm)
465 465
466 466 target_ref_type, target_ref_name, __ = _form['target_ref'].split(':')
467 467 target_ref = ':'.join((target_ref_type, target_ref_name, ancestor))
468 468
469 469 pullrequest_title = _form['pullrequest_title']
470 470 title_source_ref = source_ref.split(':', 2)[1]
471 471 if not pullrequest_title:
472 472 pullrequest_title = PullRequestModel().generate_pullrequest_title(
473 473 source=source_repo,
474 474 source_ref=title_source_ref,
475 475 target=target_repo
476 476 )
477 477
478 478 description = _form['pullrequest_desc']
479 479 try:
480 480 pull_request = PullRequestModel().create(
481 481 c.rhodecode_user.user_id, source_repo, source_ref, target_repo,
482 482 target_ref, commit_ids, reviewers, pullrequest_title,
483 483 description
484 484 )
485 485 Session().commit()
486 486 h.flash(_('Successfully opened new pull request'),
487 487 category='success')
488 488 except Exception as e:
489 489 msg = _('Error occurred during sending pull request')
490 490 log.exception(msg)
491 491 h.flash(msg, category='error')
492 492 return redirect(url('pullrequest_home', repo_name=repo_name))
493 493
494 494 return redirect(url('pullrequest_show', repo_name=target_repo,
495 495 pull_request_id=pull_request.pull_request_id))
496 496
497 497 @LoginRequired()
498 498 @NotAnonymous()
499 499 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
500 500 'repository.admin')
501 501 @auth.CSRFRequired()
502 502 @jsonify
503 503 def update(self, repo_name, pull_request_id):
504 504 pull_request_id = safe_int(pull_request_id)
505 505 pull_request = PullRequest.get_or_404(pull_request_id)
506 506 # only owner or admin can update it
507 507 allowed_to_update = PullRequestModel().check_user_update(
508 508 pull_request, c.rhodecode_user)
509 509 if allowed_to_update:
510 510 controls = peppercorn.parse(request.POST.items())
511 511
512 512 if 'review_members' in controls:
513 513 self._update_reviewers(
514 514 pull_request_id, controls['review_members'])
515 515 elif str2bool(request.POST.get('update_commits', 'false')):
516 516 self._update_commits(pull_request)
517 517 elif str2bool(request.POST.get('close_pull_request', 'false')):
518 518 self._reject_close(pull_request)
519 519 elif str2bool(request.POST.get('edit_pull_request', 'false')):
520 520 self._edit_pull_request(pull_request)
521 521 else:
522 522 raise HTTPBadRequest()
523 523 return True
524 524 raise HTTPForbidden()
525 525
526 526 def _edit_pull_request(self, pull_request):
527 527 try:
528 528 PullRequestModel().edit(
529 529 pull_request, request.POST.get('title'),
530 530 request.POST.get('description'))
531 531 except ValueError:
532 532 msg = _(u'Cannot update closed pull requests.')
533 533 h.flash(msg, category='error')
534 534 return
535 535 else:
536 536 Session().commit()
537 537
538 538 msg = _(u'Pull request title & description updated.')
539 539 h.flash(msg, category='success')
540 540 return
541 541
542 542 def _update_commits(self, pull_request):
543 543 resp = PullRequestModel().update_commits(pull_request)
544 544
545 545 if resp.executed:
546 546 msg = _(
547 547 u'Pull request updated to "{source_commit_id}" with '
548 548 u'{count_added} added, {count_removed} removed commits.')
549 549 msg = msg.format(
550 550 source_commit_id=pull_request.source_ref_parts.commit_id,
551 551 count_added=len(resp.changes.added),
552 552 count_removed=len(resp.changes.removed))
553 553 h.flash(msg, category='success')
554 554
555 555 registry = get_current_registry()
556 556 rhodecode_plugins = getattr(registry, 'rhodecode_plugins', {})
557 557 channelstream_config = rhodecode_plugins.get('channelstream', {})
558 558 if channelstream_config.get('enabled'):
559 559 message = msg + (
560 560 ' - <a onclick="window.location.reload()">'
561 561 '<strong>{}</strong></a>'.format(_('Reload page')))
562 562 channel = '/repo${}$/pr/{}'.format(
563 563 pull_request.target_repo.repo_name,
564 564 pull_request.pull_request_id
565 565 )
566 566 payload = {
567 567 'type': 'message',
568 568 'user': 'system',
569 569 'exclude_users': [request.user.username],
570 570 'channel': channel,
571 571 'message': {
572 572 'message': message,
573 573 'level': 'success',
574 574 'topic': '/notifications'
575 575 }
576 576 }
577 577 channelstream_request(
578 578 channelstream_config, [payload], '/message',
579 579 raise_exc=False)
580 580 else:
581 581 msg = PullRequestModel.UPDATE_STATUS_MESSAGES[resp.reason]
582 582 warning_reasons = [
583 583 UpdateFailureReason.NO_CHANGE,
584 584 UpdateFailureReason.WRONG_REF_TPYE,
585 585 ]
586 586 category = 'warning' if resp.reason in warning_reasons else 'error'
587 587 h.flash(msg, category=category)
588 588
589 589 @auth.CSRFRequired()
590 590 @LoginRequired()
591 591 @NotAnonymous()
592 592 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
593 593 'repository.admin')
594 594 def merge(self, repo_name, pull_request_id):
595 595 """
596 596 POST /{repo_name}/pull-request/{pull_request_id}
597 597
598 598 Merge will perform a server-side merge of the specified
599 599 pull request, if the pull request is approved and mergeable.
600 600 After succesfull merging, the pull request is automatically
601 601 closed, with a relevant comment.
602 602 """
603 603 pull_request_id = safe_int(pull_request_id)
604 604 pull_request = PullRequest.get_or_404(pull_request_id)
605 605 user = c.rhodecode_user
606 606
607 607 if self._meets_merge_pre_conditions(pull_request, user):
608 608 log.debug("Pre-conditions checked, trying to merge.")
609 609 extras = vcs_operation_context(
610 610 request.environ, repo_name=pull_request.target_repo.repo_name,
611 611 username=user.username, action='push',
612 612 scm=pull_request.target_repo.repo_type)
613 613 self._merge_pull_request(pull_request, user, extras)
614 614
615 615 return redirect(url(
616 616 'pullrequest_show',
617 617 repo_name=pull_request.target_repo.repo_name,
618 618 pull_request_id=pull_request.pull_request_id))
619 619
620 620 def _meets_merge_pre_conditions(self, pull_request, user):
621 621 if not PullRequestModel().check_user_merge(pull_request, user):
622 622 raise HTTPForbidden()
623 623
624 624 merge_status, msg = PullRequestModel().merge_status(pull_request)
625 625 if not merge_status:
626 626 log.debug("Cannot merge, not mergeable.")
627 627 h.flash(msg, category='error')
628 628 return False
629 629
630 630 if (pull_request.calculated_review_status()
631 631 is not ChangesetStatus.STATUS_APPROVED):
632 632 log.debug("Cannot merge, approval is pending.")
633 633 msg = _('Pull request reviewer approval is pending.')
634 634 h.flash(msg, category='error')
635 635 return False
636 636 return True
637 637
638 638 def _merge_pull_request(self, pull_request, user, extras):
639 639 merge_resp = PullRequestModel().merge(
640 640 pull_request, user, extras=extras)
641 641
642 642 if merge_resp.executed:
643 643 log.debug("The merge was successful, closing the pull request.")
644 644 PullRequestModel().close_pull_request(
645 645 pull_request.pull_request_id, user)
646 646 Session().commit()
647 647 msg = _('Pull request was successfully merged and closed.')
648 648 h.flash(msg, category='success')
649 649 else:
650 650 log.debug(
651 651 "The merge was not successful. Merge response: %s",
652 652 merge_resp)
653 653 msg = PullRequestModel().merge_status_message(
654 654 merge_resp.failure_reason)
655 655 h.flash(msg, category='error')
656 656
657 657 def _update_reviewers(self, pull_request_id, review_members):
658 658 reviewers = [
659 659 (int(r['user_id']), r['reasons']) for r in review_members]
660 660 PullRequestModel().update_reviewers(pull_request_id, reviewers)
661 661 Session().commit()
662 662
663 663 def _reject_close(self, pull_request):
664 664 if pull_request.is_closed():
665 665 raise HTTPForbidden()
666 666
667 667 PullRequestModel().close_pull_request_with_comment(
668 668 pull_request, c.rhodecode_user, c.rhodecode_db_repo)
669 669 Session().commit()
670 670
671 671 @LoginRequired()
672 672 @NotAnonymous()
673 673 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
674 674 'repository.admin')
675 675 @auth.CSRFRequired()
676 676 @jsonify
677 677 def delete(self, repo_name, pull_request_id):
678 678 pull_request_id = safe_int(pull_request_id)
679 679 pull_request = PullRequest.get_or_404(pull_request_id)
680 680 # only owner can delete it !
681 681 if pull_request.author.user_id == c.rhodecode_user.user_id:
682 682 PullRequestModel().delete(pull_request)
683 683 Session().commit()
684 684 h.flash(_('Successfully deleted pull request'),
685 685 category='success')
686 686 return redirect(url('my_account_pullrequests'))
687 687 raise HTTPForbidden()
688 688
689 689 def _get_pr_version(self, pull_request_id, version=None):
690 690 pull_request_id = safe_int(pull_request_id)
691 691 at_version = None
692 692
693 693 if version and version == 'latest':
694 694 pull_request_ver = PullRequest.get(pull_request_id)
695 695 pull_request_obj = pull_request_ver
696 696 _org_pull_request_obj = pull_request_obj
697 697 at_version = 'latest'
698 698 elif version:
699 699 pull_request_ver = PullRequestVersion.get_or_404(version)
700 700 pull_request_obj = pull_request_ver
701 701 _org_pull_request_obj = pull_request_ver.pull_request
702 702 at_version = pull_request_ver.pull_request_version_id
703 703 else:
704 704 _org_pull_request_obj = pull_request_obj = PullRequest.get_or_404(pull_request_id)
705 705
706 706 pull_request_display_obj = PullRequest.get_pr_display_object(
707 707 pull_request_obj, _org_pull_request_obj)
708 708 return _org_pull_request_obj, pull_request_obj, \
709 709 pull_request_display_obj, at_version
710 710
711 711 def _get_pr_version_changes(self, version, pull_request_latest):
712 712 """
713 713 Generate changes commits, and diff data based on the current pr version
714 714 """
715 715
716 716 #TODO(marcink): save those changes as JSON metadata for chaching later.
717 717
718 718 # fake the version to add the "initial" state object
719 719 pull_request_initial = PullRequest.get_pr_display_object(
720 720 pull_request_latest, pull_request_latest,
721 721 internal_methods=['get_commit', 'versions'])
722 722 pull_request_initial.revisions = []
723 723 pull_request_initial.source_repo.get_commit = types.MethodType(
724 724 lambda *a, **k: EmptyCommit(), pull_request_initial)
725 725 pull_request_initial.source_repo.scm_instance = types.MethodType(
726 726 lambda *a, **k: EmptyRepository(), pull_request_initial)
727 727
728 728 _changes_versions = [pull_request_latest] + \
729 729 list(reversed(c.versions)) + \
730 730 [pull_request_initial]
731 731
732 732 if version == 'latest':
733 733 index = 0
734 734 else:
735 735 for pos, prver in enumerate(_changes_versions):
736 736 ver = getattr(prver, 'pull_request_version_id', -1)
737 737 if ver == safe_int(version):
738 738 index = pos
739 739 break
740 740 else:
741 741 index = 0
742 742
743 743 cur_obj = _changes_versions[index]
744 744 prev_obj = _changes_versions[index + 1]
745 745
746 746 old_commit_ids = set(prev_obj.revisions)
747 747 new_commit_ids = set(cur_obj.revisions)
748 748
749 749 changes = PullRequestModel()._calculate_commit_id_changes(
750 750 old_commit_ids, new_commit_ids)
751 751
752 752 old_diff_data, new_diff_data = PullRequestModel()._generate_update_diffs(
753 753 cur_obj, prev_obj)
754 754 file_changes = PullRequestModel()._calculate_file_changes(
755 755 old_diff_data, new_diff_data)
756 756 return changes, file_changes
757 757
758 758 @LoginRequired()
759 759 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
760 760 'repository.admin')
761 761 def show(self, repo_name, pull_request_id):
762 762 pull_request_id = safe_int(pull_request_id)
763 763 version = request.GET.get('version')
764 764
765 765 (pull_request_latest,
766 766 pull_request_at_ver,
767 767 pull_request_display_obj,
768 768 at_version) = self._get_pr_version(pull_request_id, version=version)
769 769
770 770 c.template_context['pull_request_data']['pull_request_id'] = \
771 771 pull_request_id
772 772
773 773 # pull_requests repo_name we opened it against
774 774 # ie. target_repo must match
775 775 if repo_name != pull_request_at_ver.target_repo.repo_name:
776 776 raise HTTPNotFound
777 777
778 778 c.shadow_clone_url = PullRequestModel().get_shadow_clone_url(
779 779 pull_request_at_ver)
780 780
781 781 pr_closed = pull_request_latest.is_closed()
782 782 if at_version and not at_version == 'latest':
783 783 c.allowed_to_change_status = False
784 784 c.allowed_to_update = False
785 785 c.allowed_to_merge = False
786 786 c.allowed_to_delete = False
787 787 c.allowed_to_comment = False
788 788 else:
789 789 c.allowed_to_change_status = PullRequestModel(). \
790 790 check_user_change_status(pull_request_at_ver, c.rhodecode_user)
791 791 c.allowed_to_update = PullRequestModel().check_user_update(
792 792 pull_request_latest, c.rhodecode_user) and not pr_closed
793 793 c.allowed_to_merge = PullRequestModel().check_user_merge(
794 794 pull_request_latest, c.rhodecode_user) and not pr_closed
795 795 c.allowed_to_delete = PullRequestModel().check_user_delete(
796 796 pull_request_latest, c.rhodecode_user) and not pr_closed
797 797 c.allowed_to_comment = not pr_closed
798 798
799 799 cc_model = CommentsModel()
800 800
801 801 c.pull_request_reviewers = pull_request_at_ver.reviewers_statuses()
802 802 c.pull_request_review_status = pull_request_at_ver.calculated_review_status()
803 803 c.pr_merge_status, c.pr_merge_msg = PullRequestModel().merge_status(
804 804 pull_request_at_ver)
805 805 c.approval_msg = None
806 806 if c.pull_request_review_status != ChangesetStatus.STATUS_APPROVED:
807 807 c.approval_msg = _('Reviewer approval is pending.')
808 808 c.pr_merge_status = False
809 809
810 # inline comments
811 inline_comments = cc_model.get_inline_comments(
812 c.rhodecode_db_repo.repo_id, pull_request=pull_request_id)
813
814 _inline_cnt, c.inline_versions = cc_model.get_inline_comments_count(
815 inline_comments, version=at_version, include_aggregates=True)
816
817 810 c.versions = pull_request_display_obj.versions()
811 c.at_version = at_version
818 812 c.at_version_num = at_version if at_version and at_version != 'latest' else None
819 813 c.at_version_pos = ChangesetComment.get_index_from_version(
820 814 c.at_version_num, c.versions)
821 815
822 is_outdated = lambda co: \
823 not c.at_version_num \
824 or co.pull_request_version_id <= c.at_version_num
816 # GENERAL COMMENTS with versions #
817 q = cc_model._all_general_comments_of_pull_request(pull_request_latest)
818 general_comments = q.order_by(ChangesetComment.pull_request_version_id.asc())
825 819
826 # inline_comments_until_version
827 if c.at_version_num:
828 # if we use version, then do not show later comments
829 # than current version
830 paths = collections.defaultdict(lambda: collections.defaultdict(list))
831 for fname, per_line_comments in inline_comments.iteritems():
832 for lno, comments in per_line_comments.iteritems():
833 for co in comments:
834 if co.pull_request_version_id and is_outdated(co):
835 paths[co.f_path][co.line_no].append(co)
836 inline_comments = paths
820 # pick comments we want to render at current version
821 c.comment_versions = cc_model.aggregate_comments(
822 general_comments, c.versions, c.at_version_num)
823 c.comments = c.comment_versions[c.at_version_num]['until']
824
825 # INLINE COMMENTS with versions #
826 q = cc_model._all_inline_comments_of_pull_request(pull_request_latest)
827 inline_comments = q.order_by(ChangesetComment.pull_request_version_id.asc())
828 c.inline_versions = cc_model.aggregate_comments(
829 inline_comments, c.versions, c.at_version_num, inline=True)
837 830
838 # outdated comments
839 c.outdated_cnt = 0
840 if CommentsModel.use_outdated_comments(pull_request_latest):
841 outdated_comments = cc_model.get_outdated_comments(
842 c.rhodecode_db_repo.repo_id,
843 pull_request=pull_request_at_ver)
831 # if we use version, then do not show later comments
832 # than current version
833 paths = collections.defaultdict(lambda: collections.defaultdict(list))
834 for co in inline_comments:
835 if c.at_version_num:
836 # pick comments that are at least UPTO given version, so we
837 # don't render comments for higher version
838 should_render = co.pull_request_version_id and \
839 co.pull_request_version_id <= c.at_version_num
840 else:
841 # showing all, for 'latest'
842 should_render = True
844 843
845 # Count outdated comments and check for deleted files
846 is_outdated = lambda co: \
847 not c.at_version_num \
848 or co.pull_request_version_id < c.at_version_num
849 for file_name, lines in outdated_comments.iteritems():
850 for comments in lines.values():
851 comments = [comm for comm in comments if is_outdated(comm)]
852 c.outdated_cnt += len(comments)
844 if should_render:
845 paths[co.f_path][co.line_no].append(co)
846 inline_comments = paths
853 847
854 848 # load compare data into template context
855 849 self._load_compare_data(pull_request_at_ver, inline_comments)
856 850
857 851 # this is a hack to properly display links, when creating PR, the
858 852 # compare view and others uses different notation, and
859 853 # compare_commits.mako renders links based on the target_repo.
860 854 # We need to swap that here to generate it properly on the html side
861 855 c.target_repo = c.source_repo
862 856
863 # general comments
864 c.comments = cc_model.get_comments(
865 c.rhodecode_db_repo.repo_id, pull_request=pull_request_id)
866
867 857 if c.allowed_to_update:
868 858 force_close = ('forced_closed', _('Close Pull Request'))
869 859 statuses = ChangesetStatus.STATUSES + [force_close]
870 860 else:
871 861 statuses = ChangesetStatus.STATUSES
872 862 c.commit_statuses = statuses
873 863
874 864 c.ancestor = None # TODO: add ancestor here
875 865 c.pull_request = pull_request_display_obj
876 866 c.pull_request_latest = pull_request_latest
877 c.at_version = at_version
878 867
879 868 c.changes = None
880 869 c.file_changes = None
881 870
882 871 c.show_version_changes = 1 # control flag, not used yet
883 872
884 873 if at_version and c.show_version_changes:
885 874 c.changes, c.file_changes = self._get_pr_version_changes(
886 875 version, pull_request_latest)
887 876
888 877 return render('/pullrequests/pullrequest_show.mako')
889 878
890 879 @LoginRequired()
891 880 @NotAnonymous()
892 881 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
893 882 'repository.admin')
894 883 @auth.CSRFRequired()
895 884 @jsonify
896 885 def comment(self, repo_name, pull_request_id):
897 886 pull_request_id = safe_int(pull_request_id)
898 887 pull_request = PullRequest.get_or_404(pull_request_id)
899 888 if pull_request.is_closed():
900 889 raise HTTPForbidden()
901 890
902 891 # TODO: johbo: Re-think this bit, "approved_closed" does not exist
903 892 # as a changeset status, still we want to send it in one value.
904 893 status = request.POST.get('changeset_status', None)
905 894 text = request.POST.get('text')
906 895 comment_type = request.POST.get('comment_type')
907 896 resolves_comment_id = request.POST.get('resolves_comment_id', None)
908 897
909 898 if status and '_closed' in status:
910 899 close_pr = True
911 900 status = status.replace('_closed', '')
912 901 else:
913 902 close_pr = False
914 903
915 904 forced = (status == 'forced')
916 905 if forced:
917 906 status = 'rejected'
918 907
919 908 allowed_to_change_status = PullRequestModel().check_user_change_status(
920 909 pull_request, c.rhodecode_user)
921 910
922 911 if status and allowed_to_change_status:
923 912 message = (_('Status change %(transition_icon)s %(status)s')
924 913 % {'transition_icon': '>',
925 914 'status': ChangesetStatus.get_status_lbl(status)})
926 915 if close_pr:
927 916 message = _('Closing with') + ' ' + message
928 917 text = text or message
929 918 comm = CommentsModel().create(
930 919 text=text,
931 920 repo=c.rhodecode_db_repo.repo_id,
932 921 user=c.rhodecode_user.user_id,
933 922 pull_request=pull_request_id,
934 923 f_path=request.POST.get('f_path'),
935 924 line_no=request.POST.get('line'),
936 925 status_change=(ChangesetStatus.get_status_lbl(status)
937 926 if status and allowed_to_change_status else None),
938 927 status_change_type=(status
939 928 if status and allowed_to_change_status else None),
940 929 closing_pr=close_pr,
941 930 comment_type=comment_type,
942 931 resolves_comment_id=resolves_comment_id
943 932 )
944 933
945 934 if allowed_to_change_status:
946 935 old_calculated_status = pull_request.calculated_review_status()
947 936 # get status if set !
948 937 if status:
949 938 ChangesetStatusModel().set_status(
950 939 c.rhodecode_db_repo.repo_id,
951 940 status,
952 941 c.rhodecode_user.user_id,
953 942 comm,
954 943 pull_request=pull_request_id
955 944 )
956 945
957 946 Session().flush()
958 947 events.trigger(events.PullRequestCommentEvent(pull_request, comm))
959 948 # we now calculate the status of pull request, and based on that
960 949 # calculation we set the commits status
961 950 calculated_status = pull_request.calculated_review_status()
962 951 if old_calculated_status != calculated_status:
963 952 PullRequestModel()._trigger_pull_request_hook(
964 953 pull_request, c.rhodecode_user, 'review_status_change')
965 954
966 955 calculated_status_lbl = ChangesetStatus.get_status_lbl(
967 956 calculated_status)
968 957
969 958 if close_pr:
970 959 status_completed = (
971 960 calculated_status in [ChangesetStatus.STATUS_APPROVED,
972 961 ChangesetStatus.STATUS_REJECTED])
973 962 if forced or status_completed:
974 963 PullRequestModel().close_pull_request(
975 964 pull_request_id, c.rhodecode_user)
976 965 else:
977 966 h.flash(_('Closing pull request on other statuses than '
978 967 'rejected or approved is forbidden. '
979 968 'Calculated status from all reviewers '
980 969 'is currently: %s') % calculated_status_lbl,
981 970 category='warning')
982 971
983 972 Session().commit()
984 973
985 974 if not request.is_xhr:
986 975 return redirect(h.url('pullrequest_show', repo_name=repo_name,
987 976 pull_request_id=pull_request_id))
988 977
989 978 data = {
990 979 'target_id': h.safeid(h.safe_unicode(request.POST.get('f_path'))),
991 980 }
992 981 if comm:
993 982 c.co = comm
994 983 c.inline_comment = True if comm.line_no else False
995 984 data.update(comm.get_dict())
996 985 data.update({'rendered_text':
997 986 render('changeset/changeset_comment_block.mako')})
998 987
999 988 return data
1000 989
1001 990 @LoginRequired()
1002 991 @NotAnonymous()
1003 992 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
1004 993 'repository.admin')
1005 994 @auth.CSRFRequired()
1006 995 @jsonify
1007 996 def delete_comment(self, repo_name, comment_id):
1008 997 return self._delete_comment(comment_id)
1009 998
1010 999 def _delete_comment(self, comment_id):
1011 1000 comment_id = safe_int(comment_id)
1012 1001 co = ChangesetComment.get_or_404(comment_id)
1013 1002 if co.pull_request.is_closed():
1014 1003 # don't allow deleting comments on closed pull request
1015 1004 raise HTTPForbidden()
1016 1005
1017 1006 is_owner = co.author.user_id == c.rhodecode_user.user_id
1018 1007 is_repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name)
1019 1008 if h.HasPermissionAny('hg.admin')() or is_repo_admin or is_owner:
1020 1009 old_calculated_status = co.pull_request.calculated_review_status()
1021 1010 CommentsModel().delete(comment=co)
1022 1011 Session().commit()
1023 1012 calculated_status = co.pull_request.calculated_review_status()
1024 1013 if old_calculated_status != calculated_status:
1025 1014 PullRequestModel()._trigger_pull_request_hook(
1026 1015 co.pull_request, c.rhodecode_user, 'review_status_change')
1027 1016 return True
1028 1017 else:
1029 1018 raise HTTPForbidden()
@@ -1,551 +1,600 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2017 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 comments model for RhodeCode
23 23 """
24 24
25 25 import logging
26 26 import traceback
27 27 import collections
28 28
29 29 from datetime import datetime
30 30
31 31 from pylons.i18n.translation import _
32 32 from pyramid.threadlocal import get_current_registry
33 33 from sqlalchemy.sql.expression import null
34 34 from sqlalchemy.sql.functions import coalesce
35 35
36 36 from rhodecode.lib import helpers as h, diffs
37 37 from rhodecode.lib.channelstream import channelstream_request
38 38 from rhodecode.lib.utils import action_logger
39 39 from rhodecode.lib.utils2 import extract_mentioned_users
40 40 from rhodecode.model import BaseModel
41 41 from rhodecode.model.db import (
42 ChangesetComment, User, Notification, PullRequest)
42 ChangesetComment, User, Notification, PullRequest, AttributeDict)
43 43 from rhodecode.model.notification import NotificationModel
44 44 from rhodecode.model.meta import Session
45 45 from rhodecode.model.settings import VcsSettingsModel
46 46 from rhodecode.model.notification import EmailNotificationModel
47 47 from rhodecode.model.validation_schema.schemas import comment_schema
48 48
49 49
50 50 log = logging.getLogger(__name__)
51 51
52 52
53 53 class CommentsModel(BaseModel):
54 54
55 55 cls = ChangesetComment
56 56
57 57 DIFF_CONTEXT_BEFORE = 3
58 58 DIFF_CONTEXT_AFTER = 3
59 59
60 60 def __get_commit_comment(self, changeset_comment):
61 61 return self._get_instance(ChangesetComment, changeset_comment)
62 62
63 63 def __get_pull_request(self, pull_request):
64 64 return self._get_instance(PullRequest, pull_request)
65 65
66 66 def _extract_mentions(self, s):
67 67 user_objects = []
68 68 for username in extract_mentioned_users(s):
69 69 user_obj = User.get_by_username(username, case_insensitive=True)
70 70 if user_obj:
71 71 user_objects.append(user_obj)
72 72 return user_objects
73 73
74 74 def _get_renderer(self, global_renderer='rst'):
75 75 try:
76 76 # try reading from visual context
77 77 from pylons import tmpl_context
78 78 global_renderer = tmpl_context.visual.default_renderer
79 79 except AttributeError:
80 80 log.debug("Renderer not set, falling back "
81 81 "to default renderer '%s'", global_renderer)
82 82 except Exception:
83 83 log.error(traceback.format_exc())
84 84 return global_renderer
85 85
86 def aggregate_comments(self, comments, versions, show_version, inline=False):
87 # group by versions, and count until, and display objects
88
89 comment_groups = collections.defaultdict(list)
90 [comment_groups[
91 _co.pull_request_version_id].append(_co) for _co in comments]
92
93 def yield_comments(pos):
94 for co in comment_groups[pos]:
95 yield co
96
97 comment_versions = collections.defaultdict(
98 lambda: collections.defaultdict(list))
99 prev_prvid = -1
100 # fake last entry with None, to aggregate on "latest" version which
101 # doesn't have an pull_request_version_id
102 for ver in versions + [AttributeDict({'pull_request_version_id': None})]:
103 prvid = ver.pull_request_version_id
104 if prev_prvid == -1:
105 prev_prvid = prvid
106
107 for co in yield_comments(prvid):
108 comment_versions[prvid]['at'].append(co)
109
110 # save until
111 current = comment_versions[prvid]['at']
112 prev_until = comment_versions[prev_prvid]['until']
113 cur_until = prev_until + current
114 comment_versions[prvid]['until'].extend(cur_until)
115
116 # save outdated
117 if inline:
118 outdated = [x for x in cur_until
119 if x.outdated_at_version(show_version)]
120 else:
121 outdated = [x for x in cur_until
122 if x.older_than_version(show_version)]
123 display = [x for x in cur_until if x not in outdated]
124
125 comment_versions[prvid]['outdated'] = outdated
126 comment_versions[prvid]['display'] = display
127
128 prev_prvid = prvid
129
130 return comment_versions
131
86 132 def create(self, text, repo, user, commit_id=None, pull_request=None,
87 133 f_path=None, line_no=None, status_change=None,
88 134 status_change_type=None, comment_type=None,
89 135 resolves_comment_id=None, closing_pr=False, send_email=True,
90 136 renderer=None):
91 137 """
92 138 Creates new comment for commit or pull request.
93 139 IF status_change is not none this comment is associated with a
94 140 status change of commit or commit associated with pull request
95 141
96 142 :param text:
97 143 :param repo:
98 144 :param user:
99 145 :param commit_id:
100 146 :param pull_request:
101 147 :param f_path:
102 148 :param line_no:
103 149 :param status_change: Label for status change
104 150 :param comment_type: Type of comment
105 151 :param status_change_type: type of status change
106 152 :param closing_pr:
107 153 :param send_email:
108 154 :param renderer: pick renderer for this comment
109 155 """
110 156 if not text:
111 157 log.warning('Missing text for comment, skipping...')
112 158 return
113 159
114 160 if not renderer:
115 161 renderer = self._get_renderer()
116 162
117 163 repo = self._get_repo(repo)
118 164 user = self._get_user(user)
119 165
120 166 schema = comment_schema.CommentSchema()
121 167 validated_kwargs = schema.deserialize(dict(
122 168 comment_body=text,
123 169 comment_type=comment_type,
124 170 comment_file=f_path,
125 171 comment_line=line_no,
126 172 renderer_type=renderer,
127 173 status_change=status_change_type,
128 174 resolves_comment_id=resolves_comment_id,
129 175 repo=repo.repo_id,
130 176 user=user.user_id,
131 177 ))
132 178
133 179 comment = ChangesetComment()
134 180 comment.renderer = validated_kwargs['renderer_type']
135 181 comment.text = validated_kwargs['comment_body']
136 182 comment.f_path = validated_kwargs['comment_file']
137 183 comment.line_no = validated_kwargs['comment_line']
138 184 comment.comment_type = validated_kwargs['comment_type']
139 185
140 186 comment.repo = repo
141 187 comment.author = user
142 188 comment.resolved_comment = self.__get_commit_comment(
143 189 validated_kwargs['resolves_comment_id'])
144 190
145 191 pull_request_id = pull_request
146 192
147 193 commit_obj = None
148 194 pull_request_obj = None
149 195
150 196 if commit_id:
151 197 notification_type = EmailNotificationModel.TYPE_COMMIT_COMMENT
152 198 # do a lookup, so we don't pass something bad here
153 199 commit_obj = repo.scm_instance().get_commit(commit_id=commit_id)
154 200 comment.revision = commit_obj.raw_id
155 201
156 202 elif pull_request_id:
157 203 notification_type = EmailNotificationModel.TYPE_PULL_REQUEST_COMMENT
158 204 pull_request_obj = self.__get_pull_request(pull_request_id)
159 205 comment.pull_request = pull_request_obj
160 206 else:
161 207 raise Exception('Please specify commit or pull_request_id')
162 208
163 209 Session().add(comment)
164 210 Session().flush()
165 211 kwargs = {
166 212 'user': user,
167 213 'renderer_type': renderer,
168 214 'repo_name': repo.repo_name,
169 215 'status_change': status_change,
170 216 'status_change_type': status_change_type,
171 217 'comment_body': text,
172 218 'comment_file': f_path,
173 219 'comment_line': line_no,
174 220 }
175 221
176 222 if commit_obj:
177 223 recipients = ChangesetComment.get_users(
178 224 revision=commit_obj.raw_id)
179 225 # add commit author if it's in RhodeCode system
180 226 cs_author = User.get_from_cs_author(commit_obj.author)
181 227 if not cs_author:
182 228 # use repo owner if we cannot extract the author correctly
183 229 cs_author = repo.user
184 230 recipients += [cs_author]
185 231
186 232 commit_comment_url = self.get_url(comment)
187 233
188 234 target_repo_url = h.link_to(
189 235 repo.repo_name,
190 236 h.url('summary_home',
191 237 repo_name=repo.repo_name, qualified=True))
192 238
193 239 # commit specifics
194 240 kwargs.update({
195 241 'commit': commit_obj,
196 242 'commit_message': commit_obj.message,
197 243 'commit_target_repo': target_repo_url,
198 244 'commit_comment_url': commit_comment_url,
199 245 })
200 246
201 247 elif pull_request_obj:
202 248 # get the current participants of this pull request
203 249 recipients = ChangesetComment.get_users(
204 250 pull_request_id=pull_request_obj.pull_request_id)
205 251 # add pull request author
206 252 recipients += [pull_request_obj.author]
207 253
208 254 # add the reviewers to notification
209 255 recipients += [x.user for x in pull_request_obj.reviewers]
210 256
211 257 pr_target_repo = pull_request_obj.target_repo
212 258 pr_source_repo = pull_request_obj.source_repo
213 259
214 260 pr_comment_url = h.url(
215 261 'pullrequest_show',
216 262 repo_name=pr_target_repo.repo_name,
217 263 pull_request_id=pull_request_obj.pull_request_id,
218 264 anchor='comment-%s' % comment.comment_id,
219 265 qualified=True,)
220 266
221 267 # set some variables for email notification
222 268 pr_target_repo_url = h.url(
223 269 'summary_home', repo_name=pr_target_repo.repo_name,
224 270 qualified=True)
225 271
226 272 pr_source_repo_url = h.url(
227 273 'summary_home', repo_name=pr_source_repo.repo_name,
228 274 qualified=True)
229 275
230 276 # pull request specifics
231 277 kwargs.update({
232 278 'pull_request': pull_request_obj,
233 279 'pr_id': pull_request_obj.pull_request_id,
234 280 'pr_target_repo': pr_target_repo,
235 281 'pr_target_repo_url': pr_target_repo_url,
236 282 'pr_source_repo': pr_source_repo,
237 283 'pr_source_repo_url': pr_source_repo_url,
238 284 'pr_comment_url': pr_comment_url,
239 285 'pr_closing': closing_pr,
240 286 })
241 287 if send_email:
242 288 # pre-generate the subject for notification itself
243 289 (subject,
244 290 _h, _e, # we don't care about those
245 291 body_plaintext) = EmailNotificationModel().render_email(
246 292 notification_type, **kwargs)
247 293
248 294 mention_recipients = set(
249 295 self._extract_mentions(text)).difference(recipients)
250 296
251 297 # create notification objects, and emails
252 298 NotificationModel().create(
253 299 created_by=user,
254 300 notification_subject=subject,
255 301 notification_body=body_plaintext,
256 302 notification_type=notification_type,
257 303 recipients=recipients,
258 304 mention_recipients=mention_recipients,
259 305 email_kwargs=kwargs,
260 306 )
261 307
262 308 action = (
263 309 'user_commented_pull_request:{}'.format(
264 310 comment.pull_request.pull_request_id)
265 311 if comment.pull_request
266 312 else 'user_commented_revision:{}'.format(comment.revision)
267 313 )
268 314 action_logger(user, action, comment.repo)
269 315
270 316 registry = get_current_registry()
271 317 rhodecode_plugins = getattr(registry, 'rhodecode_plugins', {})
272 318 channelstream_config = rhodecode_plugins.get('channelstream', {})
273 319 msg_url = ''
274 320 if commit_obj:
275 321 msg_url = commit_comment_url
276 322 repo_name = repo.repo_name
277 323 elif pull_request_obj:
278 324 msg_url = pr_comment_url
279 325 repo_name = pr_target_repo.repo_name
280 326
281 327 if channelstream_config.get('enabled'):
282 328 message = '<strong>{}</strong> {} - ' \
283 329 '<a onclick="window.location=\'{}\';' \
284 330 'window.location.reload()">' \
285 331 '<strong>{}</strong></a>'
286 332 message = message.format(
287 333 user.username, _('made a comment'), msg_url,
288 334 _('Show it now'))
289 335 channel = '/repo${}$/pr/{}'.format(
290 336 repo_name,
291 337 pull_request_id
292 338 )
293 339 payload = {
294 340 'type': 'message',
295 341 'timestamp': datetime.utcnow(),
296 342 'user': 'system',
297 343 'exclude_users': [user.username],
298 344 'channel': channel,
299 345 'message': {
300 346 'message': message,
301 347 'level': 'info',
302 348 'topic': '/notifications'
303 349 }
304 350 }
305 351 channelstream_request(channelstream_config, [payload],
306 352 '/message', raise_exc=False)
307 353
308 354 return comment
309 355
310 356 def delete(self, comment):
311 357 """
312 358 Deletes given comment
313 359
314 360 :param comment_id:
315 361 """
316 362 comment = self.__get_commit_comment(comment)
317 363 Session().delete(comment)
318 364
319 365 return comment
320 366
321 367 def get_all_comments(self, repo_id, revision=None, pull_request=None):
322 368 q = ChangesetComment.query()\
323 369 .filter(ChangesetComment.repo_id == repo_id)
324 370 if revision:
325 371 q = q.filter(ChangesetComment.revision == revision)
326 372 elif pull_request:
327 373 pull_request = self.__get_pull_request(pull_request)
328 374 q = q.filter(ChangesetComment.pull_request == pull_request)
329 375 else:
330 376 raise Exception('Please specify commit or pull_request')
331 377 q = q.order_by(ChangesetComment.created_on)
332 378 return q.all()
333 379
334 380 def get_url(self, comment):
335 381 comment = self.__get_commit_comment(comment)
336 382 if comment.pull_request:
337 383 return h.url(
338 384 'pullrequest_show',
339 385 repo_name=comment.pull_request.target_repo.repo_name,
340 386 pull_request_id=comment.pull_request.pull_request_id,
341 387 anchor='comment-%s' % comment.comment_id,
342 388 qualified=True,)
343 389 else:
344 390 return h.url(
345 391 'changeset_home',
346 392 repo_name=comment.repo.repo_name,
347 393 revision=comment.revision,
348 394 anchor='comment-%s' % comment.comment_id,
349 395 qualified=True,)
350 396
351 397 def get_comments(self, repo_id, revision=None, pull_request=None):
352 398 """
353 399 Gets main comments based on revision or pull_request_id
354 400
355 401 :param repo_id:
356 402 :param revision:
357 403 :param pull_request:
358 404 """
359 405
360 406 q = ChangesetComment.query()\
361 407 .filter(ChangesetComment.repo_id == repo_id)\
362 408 .filter(ChangesetComment.line_no == None)\
363 409 .filter(ChangesetComment.f_path == None)
364 410 if revision:
365 411 q = q.filter(ChangesetComment.revision == revision)
366 412 elif pull_request:
367 413 pull_request = self.__get_pull_request(pull_request)
368 414 q = q.filter(ChangesetComment.pull_request == pull_request)
369 415 else:
370 416 raise Exception('Please specify commit or pull_request')
371 417 q = q.order_by(ChangesetComment.created_on)
372 418 return q.all()
373 419
374 420 def get_inline_comments(self, repo_id, revision=None, pull_request=None):
375 421 q = self._get_inline_comments_query(repo_id, revision, pull_request)
376 422 return self._group_comments_by_path_and_line_number(q)
377 423
378 424 def get_inline_comments_count(self, inline_comments, skip_outdated=True,
379 version=None, include_aggregates=False):
380 version_aggregates = collections.defaultdict(list)
425 version=None):
381 426 inline_cnt = 0
382 427 for fname, per_line_comments in inline_comments.iteritems():
383 428 for lno, comments in per_line_comments.iteritems():
384 429 for comm in comments:
385 version_aggregates[comm.pull_request_version_id].append(comm)
386 430 if not comm.outdated_at_version(version) and skip_outdated:
387 431 inline_cnt += 1
388 432
389 if include_aggregates:
390 return inline_cnt, version_aggregates
391 433 return inline_cnt
392 434
393 435 def get_outdated_comments(self, repo_id, pull_request):
394 436 # TODO: johbo: Remove `repo_id`, it is not needed to find the comments
395 437 # of a pull request.
396 438 q = self._all_inline_comments_of_pull_request(pull_request)
397 439 q = q.filter(
398 440 ChangesetComment.display_state ==
399 441 ChangesetComment.COMMENT_OUTDATED
400 442 ).order_by(ChangesetComment.comment_id.asc())
401 443
402 444 return self._group_comments_by_path_and_line_number(q)
403 445
404 446 def _get_inline_comments_query(self, repo_id, revision, pull_request):
405 447 # TODO: johbo: Split this into two methods: One for PR and one for
406 448 # commit.
407 449 if revision:
408 450 q = Session().query(ChangesetComment).filter(
409 451 ChangesetComment.repo_id == repo_id,
410 452 ChangesetComment.line_no != null(),
411 453 ChangesetComment.f_path != null(),
412 454 ChangesetComment.revision == revision)
413 455
414 456 elif pull_request:
415 457 pull_request = self.__get_pull_request(pull_request)
416 458 if not CommentsModel.use_outdated_comments(pull_request):
417 459 q = self._visible_inline_comments_of_pull_request(pull_request)
418 460 else:
419 461 q = self._all_inline_comments_of_pull_request(pull_request)
420 462
421 463 else:
422 464 raise Exception('Please specify commit or pull_request_id')
423 465 q = q.order_by(ChangesetComment.comment_id.asc())
424 466 return q
425 467
426 468 def _group_comments_by_path_and_line_number(self, q):
427 469 comments = q.all()
428 470 paths = collections.defaultdict(lambda: collections.defaultdict(list))
429 471 for co in comments:
430 472 paths[co.f_path][co.line_no].append(co)
431 473 return paths
432 474
433 475 @classmethod
434 476 def needed_extra_diff_context(cls):
435 477 return max(cls.DIFF_CONTEXT_BEFORE, cls.DIFF_CONTEXT_AFTER)
436 478
437 479 def outdate_comments(self, pull_request, old_diff_data, new_diff_data):
438 480 if not CommentsModel.use_outdated_comments(pull_request):
439 481 return
440 482
441 483 comments = self._visible_inline_comments_of_pull_request(pull_request)
442 484 comments_to_outdate = comments.all()
443 485
444 486 for comment in comments_to_outdate:
445 487 self._outdate_one_comment(comment, old_diff_data, new_diff_data)
446 488
447 489 def _outdate_one_comment(self, comment, old_diff_proc, new_diff_proc):
448 490 diff_line = _parse_comment_line_number(comment.line_no)
449 491
450 492 try:
451 493 old_context = old_diff_proc.get_context_of_line(
452 494 path=comment.f_path, diff_line=diff_line)
453 495 new_context = new_diff_proc.get_context_of_line(
454 496 path=comment.f_path, diff_line=diff_line)
455 497 except (diffs.LineNotInDiffException,
456 498 diffs.FileNotInDiffException):
457 499 comment.display_state = ChangesetComment.COMMENT_OUTDATED
458 500 return
459 501
460 502 if old_context == new_context:
461 503 return
462 504
463 505 if self._should_relocate_diff_line(diff_line):
464 506 new_diff_lines = new_diff_proc.find_context(
465 507 path=comment.f_path, context=old_context,
466 508 offset=self.DIFF_CONTEXT_BEFORE)
467 509 if not new_diff_lines:
468 510 comment.display_state = ChangesetComment.COMMENT_OUTDATED
469 511 else:
470 512 new_diff_line = self._choose_closest_diff_line(
471 513 diff_line, new_diff_lines)
472 514 comment.line_no = _diff_to_comment_line_number(new_diff_line)
473 515 else:
474 516 comment.display_state = ChangesetComment.COMMENT_OUTDATED
475 517
476 518 def _should_relocate_diff_line(self, diff_line):
477 519 """
478 520 Checks if relocation shall be tried for the given `diff_line`.
479 521
480 522 If a comment points into the first lines, then we can have a situation
481 523 that after an update another line has been added on top. In this case
482 524 we would find the context still and move the comment around. This
483 525 would be wrong.
484 526 """
485 527 should_relocate = (
486 528 (diff_line.new and diff_line.new > self.DIFF_CONTEXT_BEFORE) or
487 529 (diff_line.old and diff_line.old > self.DIFF_CONTEXT_BEFORE))
488 530 return should_relocate
489 531
490 532 def _choose_closest_diff_line(self, diff_line, new_diff_lines):
491 533 candidate = new_diff_lines[0]
492 534 best_delta = _diff_line_delta(diff_line, candidate)
493 535 for new_diff_line in new_diff_lines[1:]:
494 536 delta = _diff_line_delta(diff_line, new_diff_line)
495 537 if delta < best_delta:
496 538 candidate = new_diff_line
497 539 best_delta = delta
498 540 return candidate
499 541
500 542 def _visible_inline_comments_of_pull_request(self, pull_request):
501 543 comments = self._all_inline_comments_of_pull_request(pull_request)
502 544 comments = comments.filter(
503 545 coalesce(ChangesetComment.display_state, '') !=
504 546 ChangesetComment.COMMENT_OUTDATED)
505 547 return comments
506 548
507 549 def _all_inline_comments_of_pull_request(self, pull_request):
508 550 comments = Session().query(ChangesetComment)\
509 551 .filter(ChangesetComment.line_no != None)\
510 552 .filter(ChangesetComment.f_path != None)\
511 553 .filter(ChangesetComment.pull_request == pull_request)
512 554 return comments
513 555
556 def _all_general_comments_of_pull_request(self, pull_request):
557 comments = Session().query(ChangesetComment)\
558 .filter(ChangesetComment.line_no == None)\
559 .filter(ChangesetComment.f_path == None)\
560 .filter(ChangesetComment.pull_request == pull_request)
561 return comments
562
514 563 @staticmethod
515 564 def use_outdated_comments(pull_request):
516 565 settings_model = VcsSettingsModel(repo=pull_request.target_repo)
517 566 settings = settings_model.get_general_settings()
518 567 return settings.get('rhodecode_use_outdated_comments', False)
519 568
520 569
521 570 def _parse_comment_line_number(line_no):
522 571 """
523 572 Parses line numbers of the form "(o|n)\d+" and returns them in a tuple.
524 573 """
525 574 old_line = None
526 575 new_line = None
527 576 if line_no.startswith('o'):
528 577 old_line = int(line_no[1:])
529 578 elif line_no.startswith('n'):
530 579 new_line = int(line_no[1:])
531 580 else:
532 581 raise ValueError("Comment lines have to start with either 'o' or 'n'.")
533 582 return diffs.DiffLineNumber(old_line, new_line)
534 583
535 584
536 585 def _diff_to_comment_line_number(diff_line):
537 586 if diff_line.new is not None:
538 587 return u'n{}'.format(diff_line.new)
539 588 elif diff_line.old is not None:
540 589 return u'o{}'.format(diff_line.old)
541 590 return u''
542 591
543 592
544 593 def _diff_line_delta(a, b):
545 594 if None not in (a.new, b.new):
546 595 return abs(a.new - b.new)
547 596 elif None not in (a.old, b.old):
548 597 return abs(a.old - b.old)
549 598 else:
550 599 raise ValueError(
551 600 "Cannot compute delta between {} and {}".format(a, b))
@@ -1,3833 +1,3842 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2017 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 hashlib
29 29 import logging
30 30 import datetime
31 31 import warnings
32 32 import ipaddress
33 33 import functools
34 34 import traceback
35 35 import collections
36 36
37 37
38 38 from sqlalchemy import *
39 39 from sqlalchemy.ext.declarative import declared_attr
40 40 from sqlalchemy.ext.hybrid import hybrid_property
41 41 from sqlalchemy.orm import (
42 42 relationship, joinedload, class_mapper, validates, aliased)
43 43 from sqlalchemy.sql.expression import true
44 44 from beaker.cache import cache_region
45 45 from webob.exc import HTTPNotFound
46 46 from zope.cachedescriptors.property import Lazy as LazyProperty
47 47
48 48 from pylons import url
49 49 from pylons.i18n.translation import lazy_ugettext as _
50 50
51 51 from rhodecode.lib.vcs import get_vcs_instance
52 52 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
53 53 from rhodecode.lib.utils2 import (
54 54 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
55 55 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
56 56 glob2re, StrictAttributeDict)
57 57 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType
58 58 from rhodecode.lib.ext_json import json
59 59 from rhodecode.lib.caching_query import FromCache
60 60 from rhodecode.lib.encrypt import AESCipher
61 61
62 62 from rhodecode.model.meta import Base, Session
63 63
64 64 URL_SEP = '/'
65 65 log = logging.getLogger(__name__)
66 66
67 67 # =============================================================================
68 68 # BASE CLASSES
69 69 # =============================================================================
70 70
71 71 # this is propagated from .ini file rhodecode.encrypted_values.secret or
72 72 # beaker.session.secret if first is not set.
73 73 # and initialized at environment.py
74 74 ENCRYPTION_KEY = None
75 75
76 76 # used to sort permissions by types, '#' used here is not allowed to be in
77 77 # usernames, and it's very early in sorted string.printable table.
78 78 PERMISSION_TYPE_SORT = {
79 79 'admin': '####',
80 80 'write': '###',
81 81 'read': '##',
82 82 'none': '#',
83 83 }
84 84
85 85
86 86 def display_sort(obj):
87 87 """
88 88 Sort function used to sort permissions in .permissions() function of
89 89 Repository, RepoGroup, UserGroup. Also it put the default user in front
90 90 of all other resources
91 91 """
92 92
93 93 if obj.username == User.DEFAULT_USER:
94 94 return '#####'
95 95 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
96 96 return prefix + obj.username
97 97
98 98
99 99 def _hash_key(k):
100 100 return md5_safe(k)
101 101
102 102
103 103 class EncryptedTextValue(TypeDecorator):
104 104 """
105 105 Special column for encrypted long text data, use like::
106 106
107 107 value = Column("encrypted_value", EncryptedValue(), nullable=False)
108 108
109 109 This column is intelligent so if value is in unencrypted form it return
110 110 unencrypted form, but on save it always encrypts
111 111 """
112 112 impl = Text
113 113
114 114 def process_bind_param(self, value, dialect):
115 115 if not value:
116 116 return value
117 117 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
118 118 # protect against double encrypting if someone manually starts
119 119 # doing
120 120 raise ValueError('value needs to be in unencrypted format, ie. '
121 121 'not starting with enc$aes')
122 122 return 'enc$aes_hmac$%s' % AESCipher(
123 123 ENCRYPTION_KEY, hmac=True).encrypt(value)
124 124
125 125 def process_result_value(self, value, dialect):
126 126 import rhodecode
127 127
128 128 if not value:
129 129 return value
130 130
131 131 parts = value.split('$', 3)
132 132 if not len(parts) == 3:
133 133 # probably not encrypted values
134 134 return value
135 135 else:
136 136 if parts[0] != 'enc':
137 137 # parts ok but without our header ?
138 138 return value
139 139 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
140 140 'rhodecode.encrypted_values.strict') or True)
141 141 # at that stage we know it's our encryption
142 142 if parts[1] == 'aes':
143 143 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
144 144 elif parts[1] == 'aes_hmac':
145 145 decrypted_data = AESCipher(
146 146 ENCRYPTION_KEY, hmac=True,
147 147 strict_verification=enc_strict_mode).decrypt(parts[2])
148 148 else:
149 149 raise ValueError(
150 150 'Encryption type part is wrong, must be `aes` '
151 151 'or `aes_hmac`, got `%s` instead' % (parts[1]))
152 152 return decrypted_data
153 153
154 154
155 155 class BaseModel(object):
156 156 """
157 157 Base Model for all classes
158 158 """
159 159
160 160 @classmethod
161 161 def _get_keys(cls):
162 162 """return column names for this model """
163 163 return class_mapper(cls).c.keys()
164 164
165 165 def get_dict(self):
166 166 """
167 167 return dict with keys and values corresponding
168 168 to this model data """
169 169
170 170 d = {}
171 171 for k in self._get_keys():
172 172 d[k] = getattr(self, k)
173 173
174 174 # also use __json__() if present to get additional fields
175 175 _json_attr = getattr(self, '__json__', None)
176 176 if _json_attr:
177 177 # update with attributes from __json__
178 178 if callable(_json_attr):
179 179 _json_attr = _json_attr()
180 180 for k, val in _json_attr.iteritems():
181 181 d[k] = val
182 182 return d
183 183
184 184 def get_appstruct(self):
185 185 """return list with keys and values tuples corresponding
186 186 to this model data """
187 187
188 188 l = []
189 189 for k in self._get_keys():
190 190 l.append((k, getattr(self, k),))
191 191 return l
192 192
193 193 def populate_obj(self, populate_dict):
194 194 """populate model with data from given populate_dict"""
195 195
196 196 for k in self._get_keys():
197 197 if k in populate_dict:
198 198 setattr(self, k, populate_dict[k])
199 199
200 200 @classmethod
201 201 def query(cls):
202 202 return Session().query(cls)
203 203
204 204 @classmethod
205 205 def get(cls, id_):
206 206 if id_:
207 207 return cls.query().get(id_)
208 208
209 209 @classmethod
210 210 def get_or_404(cls, id_):
211 211 try:
212 212 id_ = int(id_)
213 213 except (TypeError, ValueError):
214 214 raise HTTPNotFound
215 215
216 216 res = cls.query().get(id_)
217 217 if not res:
218 218 raise HTTPNotFound
219 219 return res
220 220
221 221 @classmethod
222 222 def getAll(cls):
223 223 # deprecated and left for backward compatibility
224 224 return cls.get_all()
225 225
226 226 @classmethod
227 227 def get_all(cls):
228 228 return cls.query().all()
229 229
230 230 @classmethod
231 231 def delete(cls, id_):
232 232 obj = cls.query().get(id_)
233 233 Session().delete(obj)
234 234
235 235 @classmethod
236 236 def identity_cache(cls, session, attr_name, value):
237 237 exist_in_session = []
238 238 for (item_cls, pkey), instance in session.identity_map.items():
239 239 if cls == item_cls and getattr(instance, attr_name) == value:
240 240 exist_in_session.append(instance)
241 241 if exist_in_session:
242 242 if len(exist_in_session) == 1:
243 243 return exist_in_session[0]
244 244 log.exception(
245 245 'multiple objects with attr %s and '
246 246 'value %s found with same name: %r',
247 247 attr_name, value, exist_in_session)
248 248
249 249 def __repr__(self):
250 250 if hasattr(self, '__unicode__'):
251 251 # python repr needs to return str
252 252 try:
253 253 return safe_str(self.__unicode__())
254 254 except UnicodeDecodeError:
255 255 pass
256 256 return '<DB:%s>' % (self.__class__.__name__)
257 257
258 258
259 259 class RhodeCodeSetting(Base, BaseModel):
260 260 __tablename__ = 'rhodecode_settings'
261 261 __table_args__ = (
262 262 UniqueConstraint('app_settings_name'),
263 263 {'extend_existing': True, 'mysql_engine': 'InnoDB',
264 264 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
265 265 )
266 266
267 267 SETTINGS_TYPES = {
268 268 'str': safe_str,
269 269 'int': safe_int,
270 270 'unicode': safe_unicode,
271 271 'bool': str2bool,
272 272 'list': functools.partial(aslist, sep=',')
273 273 }
274 274 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
275 275 GLOBAL_CONF_KEY = 'app_settings'
276 276
277 277 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
278 278 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
279 279 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
280 280 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
281 281
282 282 def __init__(self, key='', val='', type='unicode'):
283 283 self.app_settings_name = key
284 284 self.app_settings_type = type
285 285 self.app_settings_value = val
286 286
287 287 @validates('_app_settings_value')
288 288 def validate_settings_value(self, key, val):
289 289 assert type(val) == unicode
290 290 return val
291 291
292 292 @hybrid_property
293 293 def app_settings_value(self):
294 294 v = self._app_settings_value
295 295 _type = self.app_settings_type
296 296 if _type:
297 297 _type = self.app_settings_type.split('.')[0]
298 298 # decode the encrypted value
299 299 if 'encrypted' in self.app_settings_type:
300 300 cipher = EncryptedTextValue()
301 301 v = safe_unicode(cipher.process_result_value(v, None))
302 302
303 303 converter = self.SETTINGS_TYPES.get(_type) or \
304 304 self.SETTINGS_TYPES['unicode']
305 305 return converter(v)
306 306
307 307 @app_settings_value.setter
308 308 def app_settings_value(self, val):
309 309 """
310 310 Setter that will always make sure we use unicode in app_settings_value
311 311
312 312 :param val:
313 313 """
314 314 val = safe_unicode(val)
315 315 # encode the encrypted value
316 316 if 'encrypted' in self.app_settings_type:
317 317 cipher = EncryptedTextValue()
318 318 val = safe_unicode(cipher.process_bind_param(val, None))
319 319 self._app_settings_value = val
320 320
321 321 @hybrid_property
322 322 def app_settings_type(self):
323 323 return self._app_settings_type
324 324
325 325 @app_settings_type.setter
326 326 def app_settings_type(self, val):
327 327 if val.split('.')[0] not in self.SETTINGS_TYPES:
328 328 raise Exception('type must be one of %s got %s'
329 329 % (self.SETTINGS_TYPES.keys(), val))
330 330 self._app_settings_type = val
331 331
332 332 def __unicode__(self):
333 333 return u"<%s('%s:%s[%s]')>" % (
334 334 self.__class__.__name__,
335 335 self.app_settings_name, self.app_settings_value,
336 336 self.app_settings_type
337 337 )
338 338
339 339
340 340 class RhodeCodeUi(Base, BaseModel):
341 341 __tablename__ = 'rhodecode_ui'
342 342 __table_args__ = (
343 343 UniqueConstraint('ui_key'),
344 344 {'extend_existing': True, 'mysql_engine': 'InnoDB',
345 345 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
346 346 )
347 347
348 348 HOOK_REPO_SIZE = 'changegroup.repo_size'
349 349 # HG
350 350 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
351 351 HOOK_PULL = 'outgoing.pull_logger'
352 352 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
353 353 HOOK_PUSH = 'changegroup.push_logger'
354 354
355 355 # TODO: johbo: Unify way how hooks are configured for git and hg,
356 356 # git part is currently hardcoded.
357 357
358 358 # SVN PATTERNS
359 359 SVN_BRANCH_ID = 'vcs_svn_branch'
360 360 SVN_TAG_ID = 'vcs_svn_tag'
361 361
362 362 ui_id = Column(
363 363 "ui_id", Integer(), nullable=False, unique=True, default=None,
364 364 primary_key=True)
365 365 ui_section = Column(
366 366 "ui_section", String(255), nullable=True, unique=None, default=None)
367 367 ui_key = Column(
368 368 "ui_key", String(255), nullable=True, unique=None, default=None)
369 369 ui_value = Column(
370 370 "ui_value", String(255), nullable=True, unique=None, default=None)
371 371 ui_active = Column(
372 372 "ui_active", Boolean(), nullable=True, unique=None, default=True)
373 373
374 374 def __repr__(self):
375 375 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
376 376 self.ui_key, self.ui_value)
377 377
378 378
379 379 class RepoRhodeCodeSetting(Base, BaseModel):
380 380 __tablename__ = 'repo_rhodecode_settings'
381 381 __table_args__ = (
382 382 UniqueConstraint(
383 383 'app_settings_name', 'repository_id',
384 384 name='uq_repo_rhodecode_setting_name_repo_id'),
385 385 {'extend_existing': True, 'mysql_engine': 'InnoDB',
386 386 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
387 387 )
388 388
389 389 repository_id = Column(
390 390 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
391 391 nullable=False)
392 392 app_settings_id = Column(
393 393 "app_settings_id", Integer(), nullable=False, unique=True,
394 394 default=None, primary_key=True)
395 395 app_settings_name = Column(
396 396 "app_settings_name", String(255), nullable=True, unique=None,
397 397 default=None)
398 398 _app_settings_value = Column(
399 399 "app_settings_value", String(4096), nullable=True, unique=None,
400 400 default=None)
401 401 _app_settings_type = Column(
402 402 "app_settings_type", String(255), nullable=True, unique=None,
403 403 default=None)
404 404
405 405 repository = relationship('Repository')
406 406
407 407 def __init__(self, repository_id, key='', val='', type='unicode'):
408 408 self.repository_id = repository_id
409 409 self.app_settings_name = key
410 410 self.app_settings_type = type
411 411 self.app_settings_value = val
412 412
413 413 @validates('_app_settings_value')
414 414 def validate_settings_value(self, key, val):
415 415 assert type(val) == unicode
416 416 return val
417 417
418 418 @hybrid_property
419 419 def app_settings_value(self):
420 420 v = self._app_settings_value
421 421 type_ = self.app_settings_type
422 422 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
423 423 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
424 424 return converter(v)
425 425
426 426 @app_settings_value.setter
427 427 def app_settings_value(self, val):
428 428 """
429 429 Setter that will always make sure we use unicode in app_settings_value
430 430
431 431 :param val:
432 432 """
433 433 self._app_settings_value = safe_unicode(val)
434 434
435 435 @hybrid_property
436 436 def app_settings_type(self):
437 437 return self._app_settings_type
438 438
439 439 @app_settings_type.setter
440 440 def app_settings_type(self, val):
441 441 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
442 442 if val not in SETTINGS_TYPES:
443 443 raise Exception('type must be one of %s got %s'
444 444 % (SETTINGS_TYPES.keys(), val))
445 445 self._app_settings_type = val
446 446
447 447 def __unicode__(self):
448 448 return u"<%s('%s:%s:%s[%s]')>" % (
449 449 self.__class__.__name__, self.repository.repo_name,
450 450 self.app_settings_name, self.app_settings_value,
451 451 self.app_settings_type
452 452 )
453 453
454 454
455 455 class RepoRhodeCodeUi(Base, BaseModel):
456 456 __tablename__ = 'repo_rhodecode_ui'
457 457 __table_args__ = (
458 458 UniqueConstraint(
459 459 'repository_id', 'ui_section', 'ui_key',
460 460 name='uq_repo_rhodecode_ui_repository_id_section_key'),
461 461 {'extend_existing': True, 'mysql_engine': 'InnoDB',
462 462 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
463 463 )
464 464
465 465 repository_id = Column(
466 466 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
467 467 nullable=False)
468 468 ui_id = Column(
469 469 "ui_id", Integer(), nullable=False, unique=True, default=None,
470 470 primary_key=True)
471 471 ui_section = Column(
472 472 "ui_section", String(255), nullable=True, unique=None, default=None)
473 473 ui_key = Column(
474 474 "ui_key", String(255), nullable=True, unique=None, default=None)
475 475 ui_value = Column(
476 476 "ui_value", String(255), nullable=True, unique=None, default=None)
477 477 ui_active = Column(
478 478 "ui_active", Boolean(), nullable=True, unique=None, default=True)
479 479
480 480 repository = relationship('Repository')
481 481
482 482 def __repr__(self):
483 483 return '<%s[%s:%s]%s=>%s]>' % (
484 484 self.__class__.__name__, self.repository.repo_name,
485 485 self.ui_section, self.ui_key, self.ui_value)
486 486
487 487
488 488 class User(Base, BaseModel):
489 489 __tablename__ = 'users'
490 490 __table_args__ = (
491 491 UniqueConstraint('username'), UniqueConstraint('email'),
492 492 Index('u_username_idx', 'username'),
493 493 Index('u_email_idx', 'email'),
494 494 {'extend_existing': True, 'mysql_engine': 'InnoDB',
495 495 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
496 496 )
497 497 DEFAULT_USER = 'default'
498 498 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
499 499 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
500 500
501 501 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
502 502 username = Column("username", String(255), nullable=True, unique=None, default=None)
503 503 password = Column("password", String(255), nullable=True, unique=None, default=None)
504 504 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
505 505 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
506 506 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
507 507 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
508 508 _email = Column("email", String(255), nullable=True, unique=None, default=None)
509 509 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
510 510 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
511 511 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
512 512 api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
513 513 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
514 514 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
515 515 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
516 516
517 517 user_log = relationship('UserLog')
518 518 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
519 519
520 520 repositories = relationship('Repository')
521 521 repository_groups = relationship('RepoGroup')
522 522 user_groups = relationship('UserGroup')
523 523
524 524 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
525 525 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
526 526
527 527 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
528 528 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
529 529 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
530 530
531 531 group_member = relationship('UserGroupMember', cascade='all')
532 532
533 533 notifications = relationship('UserNotification', cascade='all')
534 534 # notifications assigned to this user
535 535 user_created_notifications = relationship('Notification', cascade='all')
536 536 # comments created by this user
537 537 user_comments = relationship('ChangesetComment', cascade='all')
538 538 # user profile extra info
539 539 user_emails = relationship('UserEmailMap', cascade='all')
540 540 user_ip_map = relationship('UserIpMap', cascade='all')
541 541 user_auth_tokens = relationship('UserApiKeys', cascade='all')
542 542 # gists
543 543 user_gists = relationship('Gist', cascade='all')
544 544 # user pull requests
545 545 user_pull_requests = relationship('PullRequest', cascade='all')
546 546 # external identities
547 547 extenal_identities = relationship(
548 548 'ExternalIdentity',
549 549 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
550 550 cascade='all')
551 551
552 552 def __unicode__(self):
553 553 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
554 554 self.user_id, self.username)
555 555
556 556 @hybrid_property
557 557 def email(self):
558 558 return self._email
559 559
560 560 @email.setter
561 561 def email(self, val):
562 562 self._email = val.lower() if val else None
563 563
564 564 @property
565 565 def firstname(self):
566 566 # alias for future
567 567 return self.name
568 568
569 569 @property
570 570 def emails(self):
571 571 other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
572 572 return [self.email] + [x.email for x in other]
573 573
574 574 @property
575 575 def auth_tokens(self):
576 576 return [self.api_key] + [x.api_key for x in self.extra_auth_tokens]
577 577
578 578 @property
579 579 def extra_auth_tokens(self):
580 580 return UserApiKeys.query().filter(UserApiKeys.user == self).all()
581 581
582 582 @property
583 583 def feed_token(self):
584 584 feed_tokens = UserApiKeys.query()\
585 585 .filter(UserApiKeys.user == self)\
586 586 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\
587 587 .all()
588 588 if feed_tokens:
589 589 return feed_tokens[0].api_key
590 590 else:
591 591 # use the main token so we don't end up with nothing...
592 592 return self.api_key
593 593
594 594 @classmethod
595 595 def extra_valid_auth_tokens(cls, user, role=None):
596 596 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
597 597 .filter(or_(UserApiKeys.expires == -1,
598 598 UserApiKeys.expires >= time.time()))
599 599 if role:
600 600 tokens = tokens.filter(or_(UserApiKeys.role == role,
601 601 UserApiKeys.role == UserApiKeys.ROLE_ALL))
602 602 return tokens.all()
603 603
604 604 @property
605 605 def builtin_token_roles(self):
606 606 return map(UserApiKeys._get_role_name, [
607 607 UserApiKeys.ROLE_API, UserApiKeys.ROLE_FEED, UserApiKeys.ROLE_HTTP
608 608 ])
609 609
610 610 @property
611 611 def ip_addresses(self):
612 612 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
613 613 return [x.ip_addr for x in ret]
614 614
615 615 @property
616 616 def username_and_name(self):
617 617 return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
618 618
619 619 @property
620 620 def username_or_name_or_email(self):
621 621 full_name = self.full_name if self.full_name is not ' ' else None
622 622 return self.username or full_name or self.email
623 623
624 624 @property
625 625 def full_name(self):
626 626 return '%s %s' % (self.firstname, self.lastname)
627 627
628 628 @property
629 629 def full_name_or_username(self):
630 630 return ('%s %s' % (self.firstname, self.lastname)
631 631 if (self.firstname and self.lastname) else self.username)
632 632
633 633 @property
634 634 def full_contact(self):
635 635 return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
636 636
637 637 @property
638 638 def short_contact(self):
639 639 return '%s %s' % (self.firstname, self.lastname)
640 640
641 641 @property
642 642 def is_admin(self):
643 643 return self.admin
644 644
645 645 @property
646 646 def AuthUser(self):
647 647 """
648 648 Returns instance of AuthUser for this user
649 649 """
650 650 from rhodecode.lib.auth import AuthUser
651 651 return AuthUser(user_id=self.user_id, api_key=self.api_key,
652 652 username=self.username)
653 653
654 654 @hybrid_property
655 655 def user_data(self):
656 656 if not self._user_data:
657 657 return {}
658 658
659 659 try:
660 660 return json.loads(self._user_data)
661 661 except TypeError:
662 662 return {}
663 663
664 664 @user_data.setter
665 665 def user_data(self, val):
666 666 if not isinstance(val, dict):
667 667 raise Exception('user_data must be dict, got %s' % type(val))
668 668 try:
669 669 self._user_data = json.dumps(val)
670 670 except Exception:
671 671 log.error(traceback.format_exc())
672 672
673 673 @classmethod
674 674 def get_by_username(cls, username, case_insensitive=False,
675 675 cache=False, identity_cache=False):
676 676 session = Session()
677 677
678 678 if case_insensitive:
679 679 q = cls.query().filter(
680 680 func.lower(cls.username) == func.lower(username))
681 681 else:
682 682 q = cls.query().filter(cls.username == username)
683 683
684 684 if cache:
685 685 if identity_cache:
686 686 val = cls.identity_cache(session, 'username', username)
687 687 if val:
688 688 return val
689 689 else:
690 690 q = q.options(
691 691 FromCache("sql_cache_short",
692 692 "get_user_by_name_%s" % _hash_key(username)))
693 693
694 694 return q.scalar()
695 695
696 696 @classmethod
697 697 def get_by_auth_token(cls, auth_token, cache=False, fallback=True):
698 698 q = cls.query().filter(cls.api_key == auth_token)
699 699
700 700 if cache:
701 701 q = q.options(FromCache("sql_cache_short",
702 702 "get_auth_token_%s" % auth_token))
703 703 res = q.scalar()
704 704
705 705 if fallback and not res:
706 706 #fallback to additional keys
707 707 _res = UserApiKeys.query()\
708 708 .filter(UserApiKeys.api_key == auth_token)\
709 709 .filter(or_(UserApiKeys.expires == -1,
710 710 UserApiKeys.expires >= time.time()))\
711 711 .first()
712 712 if _res:
713 713 res = _res.user
714 714 return res
715 715
716 716 @classmethod
717 717 def get_by_email(cls, email, case_insensitive=False, cache=False):
718 718
719 719 if case_insensitive:
720 720 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
721 721
722 722 else:
723 723 q = cls.query().filter(cls.email == email)
724 724
725 725 if cache:
726 726 q = q.options(FromCache("sql_cache_short",
727 727 "get_email_key_%s" % _hash_key(email)))
728 728
729 729 ret = q.scalar()
730 730 if ret is None:
731 731 q = UserEmailMap.query()
732 732 # try fetching in alternate email map
733 733 if case_insensitive:
734 734 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
735 735 else:
736 736 q = q.filter(UserEmailMap.email == email)
737 737 q = q.options(joinedload(UserEmailMap.user))
738 738 if cache:
739 739 q = q.options(FromCache("sql_cache_short",
740 740 "get_email_map_key_%s" % email))
741 741 ret = getattr(q.scalar(), 'user', None)
742 742
743 743 return ret
744 744
745 745 @classmethod
746 746 def get_from_cs_author(cls, author):
747 747 """
748 748 Tries to get User objects out of commit author string
749 749
750 750 :param author:
751 751 """
752 752 from rhodecode.lib.helpers import email, author_name
753 753 # Valid email in the attribute passed, see if they're in the system
754 754 _email = email(author)
755 755 if _email:
756 756 user = cls.get_by_email(_email, case_insensitive=True)
757 757 if user:
758 758 return user
759 759 # Maybe we can match by username?
760 760 _author = author_name(author)
761 761 user = cls.get_by_username(_author, case_insensitive=True)
762 762 if user:
763 763 return user
764 764
765 765 def update_userdata(self, **kwargs):
766 766 usr = self
767 767 old = usr.user_data
768 768 old.update(**kwargs)
769 769 usr.user_data = old
770 770 Session().add(usr)
771 771 log.debug('updated userdata with ', kwargs)
772 772
773 773 def update_lastlogin(self):
774 774 """Update user lastlogin"""
775 775 self.last_login = datetime.datetime.now()
776 776 Session().add(self)
777 777 log.debug('updated user %s lastlogin', self.username)
778 778
779 779 def update_lastactivity(self):
780 780 """Update user lastactivity"""
781 781 usr = self
782 782 old = usr.user_data
783 783 old.update({'last_activity': time.time()})
784 784 usr.user_data = old
785 785 Session().add(usr)
786 786 log.debug('updated user %s lastactivity', usr.username)
787 787
788 788 def update_password(self, new_password, change_api_key=False):
789 789 from rhodecode.lib.auth import get_crypt_password,generate_auth_token
790 790
791 791 self.password = get_crypt_password(new_password)
792 792 if change_api_key:
793 793 self.api_key = generate_auth_token(self.username)
794 794 Session().add(self)
795 795
796 796 @classmethod
797 797 def get_first_super_admin(cls):
798 798 user = User.query().filter(User.admin == true()).first()
799 799 if user is None:
800 800 raise Exception('FATAL: Missing administrative account!')
801 801 return user
802 802
803 803 @classmethod
804 804 def get_all_super_admins(cls):
805 805 """
806 806 Returns all admin accounts sorted by username
807 807 """
808 808 return User.query().filter(User.admin == true())\
809 809 .order_by(User.username.asc()).all()
810 810
811 811 @classmethod
812 812 def get_default_user(cls, cache=False):
813 813 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
814 814 if user is None:
815 815 raise Exception('FATAL: Missing default account!')
816 816 return user
817 817
818 818 def _get_default_perms(self, user, suffix=''):
819 819 from rhodecode.model.permission import PermissionModel
820 820 return PermissionModel().get_default_perms(user.user_perms, suffix)
821 821
822 822 def get_default_perms(self, suffix=''):
823 823 return self._get_default_perms(self, suffix)
824 824
825 825 def get_api_data(self, include_secrets=False, details='full'):
826 826 """
827 827 Common function for generating user related data for API
828 828
829 829 :param include_secrets: By default secrets in the API data will be replaced
830 830 by a placeholder value to prevent exposing this data by accident. In case
831 831 this data shall be exposed, set this flag to ``True``.
832 832
833 833 :param details: details can be 'basic|full' basic gives only a subset of
834 834 the available user information that includes user_id, name and emails.
835 835 """
836 836 user = self
837 837 user_data = self.user_data
838 838 data = {
839 839 'user_id': user.user_id,
840 840 'username': user.username,
841 841 'firstname': user.name,
842 842 'lastname': user.lastname,
843 843 'email': user.email,
844 844 'emails': user.emails,
845 845 }
846 846 if details == 'basic':
847 847 return data
848 848
849 849 api_key_length = 40
850 850 api_key_replacement = '*' * api_key_length
851 851
852 852 extras = {
853 853 'api_key': api_key_replacement,
854 854 'api_keys': [api_key_replacement],
855 855 'active': user.active,
856 856 'admin': user.admin,
857 857 'extern_type': user.extern_type,
858 858 'extern_name': user.extern_name,
859 859 'last_login': user.last_login,
860 860 'ip_addresses': user.ip_addresses,
861 861 'language': user_data.get('language')
862 862 }
863 863 data.update(extras)
864 864
865 865 if include_secrets:
866 866 data['api_key'] = user.api_key
867 867 data['api_keys'] = user.auth_tokens
868 868 return data
869 869
870 870 def __json__(self):
871 871 data = {
872 872 'full_name': self.full_name,
873 873 'full_name_or_username': self.full_name_or_username,
874 874 'short_contact': self.short_contact,
875 875 'full_contact': self.full_contact,
876 876 }
877 877 data.update(self.get_api_data())
878 878 return data
879 879
880 880
881 881 class UserApiKeys(Base, BaseModel):
882 882 __tablename__ = 'user_api_keys'
883 883 __table_args__ = (
884 884 Index('uak_api_key_idx', 'api_key'),
885 885 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
886 886 UniqueConstraint('api_key'),
887 887 {'extend_existing': True, 'mysql_engine': 'InnoDB',
888 888 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
889 889 )
890 890 __mapper_args__ = {}
891 891
892 892 # ApiKey role
893 893 ROLE_ALL = 'token_role_all'
894 894 ROLE_HTTP = 'token_role_http'
895 895 ROLE_VCS = 'token_role_vcs'
896 896 ROLE_API = 'token_role_api'
897 897 ROLE_FEED = 'token_role_feed'
898 898 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
899 899
900 900 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
901 901 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
902 902 api_key = Column("api_key", String(255), nullable=False, unique=True)
903 903 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
904 904 expires = Column('expires', Float(53), nullable=False)
905 905 role = Column('role', String(255), nullable=True)
906 906 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
907 907
908 908 user = relationship('User', lazy='joined')
909 909
910 910 @classmethod
911 911 def _get_role_name(cls, role):
912 912 return {
913 913 cls.ROLE_ALL: _('all'),
914 914 cls.ROLE_HTTP: _('http/web interface'),
915 915 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
916 916 cls.ROLE_API: _('api calls'),
917 917 cls.ROLE_FEED: _('feed access'),
918 918 }.get(role, role)
919 919
920 920 @property
921 921 def expired(self):
922 922 if self.expires == -1:
923 923 return False
924 924 return time.time() > self.expires
925 925
926 926 @property
927 927 def role_humanized(self):
928 928 return self._get_role_name(self.role)
929 929
930 930
931 931 class UserEmailMap(Base, BaseModel):
932 932 __tablename__ = 'user_email_map'
933 933 __table_args__ = (
934 934 Index('uem_email_idx', 'email'),
935 935 UniqueConstraint('email'),
936 936 {'extend_existing': True, 'mysql_engine': 'InnoDB',
937 937 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
938 938 )
939 939 __mapper_args__ = {}
940 940
941 941 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
942 942 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
943 943 _email = Column("email", String(255), nullable=True, unique=False, default=None)
944 944 user = relationship('User', lazy='joined')
945 945
946 946 @validates('_email')
947 947 def validate_email(self, key, email):
948 948 # check if this email is not main one
949 949 main_email = Session().query(User).filter(User.email == email).scalar()
950 950 if main_email is not None:
951 951 raise AttributeError('email %s is present is user table' % email)
952 952 return email
953 953
954 954 @hybrid_property
955 955 def email(self):
956 956 return self._email
957 957
958 958 @email.setter
959 959 def email(self, val):
960 960 self._email = val.lower() if val else None
961 961
962 962
963 963 class UserIpMap(Base, BaseModel):
964 964 __tablename__ = 'user_ip_map'
965 965 __table_args__ = (
966 966 UniqueConstraint('user_id', 'ip_addr'),
967 967 {'extend_existing': True, 'mysql_engine': 'InnoDB',
968 968 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
969 969 )
970 970 __mapper_args__ = {}
971 971
972 972 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
973 973 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
974 974 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
975 975 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
976 976 description = Column("description", String(10000), nullable=True, unique=None, default=None)
977 977 user = relationship('User', lazy='joined')
978 978
979 979 @classmethod
980 980 def _get_ip_range(cls, ip_addr):
981 981 net = ipaddress.ip_network(ip_addr, strict=False)
982 982 return [str(net.network_address), str(net.broadcast_address)]
983 983
984 984 def __json__(self):
985 985 return {
986 986 'ip_addr': self.ip_addr,
987 987 'ip_range': self._get_ip_range(self.ip_addr),
988 988 }
989 989
990 990 def __unicode__(self):
991 991 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
992 992 self.user_id, self.ip_addr)
993 993
994 994 class UserLog(Base, BaseModel):
995 995 __tablename__ = 'user_logs'
996 996 __table_args__ = (
997 997 {'extend_existing': True, 'mysql_engine': 'InnoDB',
998 998 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
999 999 )
1000 1000 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1001 1001 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1002 1002 username = Column("username", String(255), nullable=True, unique=None, default=None)
1003 1003 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
1004 1004 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1005 1005 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1006 1006 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1007 1007 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1008 1008
1009 1009 def __unicode__(self):
1010 1010 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1011 1011 self.repository_name,
1012 1012 self.action)
1013 1013
1014 1014 @property
1015 1015 def action_as_day(self):
1016 1016 return datetime.date(*self.action_date.timetuple()[:3])
1017 1017
1018 1018 user = relationship('User')
1019 1019 repository = relationship('Repository', cascade='')
1020 1020
1021 1021
1022 1022 class UserGroup(Base, BaseModel):
1023 1023 __tablename__ = 'users_groups'
1024 1024 __table_args__ = (
1025 1025 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1026 1026 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1027 1027 )
1028 1028
1029 1029 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1030 1030 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1031 1031 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1032 1032 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1033 1033 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1034 1034 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1035 1035 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1036 1036 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1037 1037
1038 1038 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1039 1039 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1040 1040 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1041 1041 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1042 1042 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1043 1043 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1044 1044
1045 1045 user = relationship('User')
1046 1046
1047 1047 @hybrid_property
1048 1048 def group_data(self):
1049 1049 if not self._group_data:
1050 1050 return {}
1051 1051
1052 1052 try:
1053 1053 return json.loads(self._group_data)
1054 1054 except TypeError:
1055 1055 return {}
1056 1056
1057 1057 @group_data.setter
1058 1058 def group_data(self, val):
1059 1059 try:
1060 1060 self._group_data = json.dumps(val)
1061 1061 except Exception:
1062 1062 log.error(traceback.format_exc())
1063 1063
1064 1064 def __unicode__(self):
1065 1065 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1066 1066 self.users_group_id,
1067 1067 self.users_group_name)
1068 1068
1069 1069 @classmethod
1070 1070 def get_by_group_name(cls, group_name, cache=False,
1071 1071 case_insensitive=False):
1072 1072 if case_insensitive:
1073 1073 q = cls.query().filter(func.lower(cls.users_group_name) ==
1074 1074 func.lower(group_name))
1075 1075
1076 1076 else:
1077 1077 q = cls.query().filter(cls.users_group_name == group_name)
1078 1078 if cache:
1079 1079 q = q.options(FromCache(
1080 1080 "sql_cache_short",
1081 1081 "get_group_%s" % _hash_key(group_name)))
1082 1082 return q.scalar()
1083 1083
1084 1084 @classmethod
1085 1085 def get(cls, user_group_id, cache=False):
1086 1086 user_group = cls.query()
1087 1087 if cache:
1088 1088 user_group = user_group.options(FromCache("sql_cache_short",
1089 1089 "get_users_group_%s" % user_group_id))
1090 1090 return user_group.get(user_group_id)
1091 1091
1092 1092 def permissions(self, with_admins=True, with_owner=True):
1093 1093 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1094 1094 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1095 1095 joinedload(UserUserGroupToPerm.user),
1096 1096 joinedload(UserUserGroupToPerm.permission),)
1097 1097
1098 1098 # get owners and admins and permissions. We do a trick of re-writing
1099 1099 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1100 1100 # has a global reference and changing one object propagates to all
1101 1101 # others. This means if admin is also an owner admin_row that change
1102 1102 # would propagate to both objects
1103 1103 perm_rows = []
1104 1104 for _usr in q.all():
1105 1105 usr = AttributeDict(_usr.user.get_dict())
1106 1106 usr.permission = _usr.permission.permission_name
1107 1107 perm_rows.append(usr)
1108 1108
1109 1109 # filter the perm rows by 'default' first and then sort them by
1110 1110 # admin,write,read,none permissions sorted again alphabetically in
1111 1111 # each group
1112 1112 perm_rows = sorted(perm_rows, key=display_sort)
1113 1113
1114 1114 _admin_perm = 'usergroup.admin'
1115 1115 owner_row = []
1116 1116 if with_owner:
1117 1117 usr = AttributeDict(self.user.get_dict())
1118 1118 usr.owner_row = True
1119 1119 usr.permission = _admin_perm
1120 1120 owner_row.append(usr)
1121 1121
1122 1122 super_admin_rows = []
1123 1123 if with_admins:
1124 1124 for usr in User.get_all_super_admins():
1125 1125 # if this admin is also owner, don't double the record
1126 1126 if usr.user_id == owner_row[0].user_id:
1127 1127 owner_row[0].admin_row = True
1128 1128 else:
1129 1129 usr = AttributeDict(usr.get_dict())
1130 1130 usr.admin_row = True
1131 1131 usr.permission = _admin_perm
1132 1132 super_admin_rows.append(usr)
1133 1133
1134 1134 return super_admin_rows + owner_row + perm_rows
1135 1135
1136 1136 def permission_user_groups(self):
1137 1137 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1138 1138 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1139 1139 joinedload(UserGroupUserGroupToPerm.target_user_group),
1140 1140 joinedload(UserGroupUserGroupToPerm.permission),)
1141 1141
1142 1142 perm_rows = []
1143 1143 for _user_group in q.all():
1144 1144 usr = AttributeDict(_user_group.user_group.get_dict())
1145 1145 usr.permission = _user_group.permission.permission_name
1146 1146 perm_rows.append(usr)
1147 1147
1148 1148 return perm_rows
1149 1149
1150 1150 def _get_default_perms(self, user_group, suffix=''):
1151 1151 from rhodecode.model.permission import PermissionModel
1152 1152 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1153 1153
1154 1154 def get_default_perms(self, suffix=''):
1155 1155 return self._get_default_perms(self, suffix)
1156 1156
1157 1157 def get_api_data(self, with_group_members=True, include_secrets=False):
1158 1158 """
1159 1159 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1160 1160 basically forwarded.
1161 1161
1162 1162 """
1163 1163 user_group = self
1164 1164
1165 1165 data = {
1166 1166 'users_group_id': user_group.users_group_id,
1167 1167 'group_name': user_group.users_group_name,
1168 1168 'group_description': user_group.user_group_description,
1169 1169 'active': user_group.users_group_active,
1170 1170 'owner': user_group.user.username,
1171 1171 }
1172 1172 if with_group_members:
1173 1173 users = []
1174 1174 for user in user_group.members:
1175 1175 user = user.user
1176 1176 users.append(user.get_api_data(include_secrets=include_secrets))
1177 1177 data['users'] = users
1178 1178
1179 1179 return data
1180 1180
1181 1181
1182 1182 class UserGroupMember(Base, BaseModel):
1183 1183 __tablename__ = 'users_groups_members'
1184 1184 __table_args__ = (
1185 1185 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1186 1186 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1187 1187 )
1188 1188
1189 1189 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1190 1190 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1191 1191 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1192 1192
1193 1193 user = relationship('User', lazy='joined')
1194 1194 users_group = relationship('UserGroup')
1195 1195
1196 1196 def __init__(self, gr_id='', u_id=''):
1197 1197 self.users_group_id = gr_id
1198 1198 self.user_id = u_id
1199 1199
1200 1200
1201 1201 class RepositoryField(Base, BaseModel):
1202 1202 __tablename__ = 'repositories_fields'
1203 1203 __table_args__ = (
1204 1204 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1205 1205 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1206 1206 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1207 1207 )
1208 1208 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1209 1209
1210 1210 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1211 1211 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1212 1212 field_key = Column("field_key", String(250))
1213 1213 field_label = Column("field_label", String(1024), nullable=False)
1214 1214 field_value = Column("field_value", String(10000), nullable=False)
1215 1215 field_desc = Column("field_desc", String(1024), nullable=False)
1216 1216 field_type = Column("field_type", String(255), nullable=False, unique=None)
1217 1217 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1218 1218
1219 1219 repository = relationship('Repository')
1220 1220
1221 1221 @property
1222 1222 def field_key_prefixed(self):
1223 1223 return 'ex_%s' % self.field_key
1224 1224
1225 1225 @classmethod
1226 1226 def un_prefix_key(cls, key):
1227 1227 if key.startswith(cls.PREFIX):
1228 1228 return key[len(cls.PREFIX):]
1229 1229 return key
1230 1230
1231 1231 @classmethod
1232 1232 def get_by_key_name(cls, key, repo):
1233 1233 row = cls.query()\
1234 1234 .filter(cls.repository == repo)\
1235 1235 .filter(cls.field_key == key).scalar()
1236 1236 return row
1237 1237
1238 1238
1239 1239 class Repository(Base, BaseModel):
1240 1240 __tablename__ = 'repositories'
1241 1241 __table_args__ = (
1242 1242 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1243 1243 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1244 1244 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1245 1245 )
1246 1246 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1247 1247 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1248 1248
1249 1249 STATE_CREATED = 'repo_state_created'
1250 1250 STATE_PENDING = 'repo_state_pending'
1251 1251 STATE_ERROR = 'repo_state_error'
1252 1252
1253 1253 LOCK_AUTOMATIC = 'lock_auto'
1254 1254 LOCK_API = 'lock_api'
1255 1255 LOCK_WEB = 'lock_web'
1256 1256 LOCK_PULL = 'lock_pull'
1257 1257
1258 1258 NAME_SEP = URL_SEP
1259 1259
1260 1260 repo_id = Column(
1261 1261 "repo_id", Integer(), nullable=False, unique=True, default=None,
1262 1262 primary_key=True)
1263 1263 _repo_name = Column(
1264 1264 "repo_name", Text(), nullable=False, default=None)
1265 1265 _repo_name_hash = Column(
1266 1266 "repo_name_hash", String(255), nullable=False, unique=True)
1267 1267 repo_state = Column("repo_state", String(255), nullable=True)
1268 1268
1269 1269 clone_uri = Column(
1270 1270 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1271 1271 default=None)
1272 1272 repo_type = Column(
1273 1273 "repo_type", String(255), nullable=False, unique=False, default=None)
1274 1274 user_id = Column(
1275 1275 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1276 1276 unique=False, default=None)
1277 1277 private = Column(
1278 1278 "private", Boolean(), nullable=True, unique=None, default=None)
1279 1279 enable_statistics = Column(
1280 1280 "statistics", Boolean(), nullable=True, unique=None, default=True)
1281 1281 enable_downloads = Column(
1282 1282 "downloads", Boolean(), nullable=True, unique=None, default=True)
1283 1283 description = Column(
1284 1284 "description", String(10000), nullable=True, unique=None, default=None)
1285 1285 created_on = Column(
1286 1286 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1287 1287 default=datetime.datetime.now)
1288 1288 updated_on = Column(
1289 1289 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1290 1290 default=datetime.datetime.now)
1291 1291 _landing_revision = Column(
1292 1292 "landing_revision", String(255), nullable=False, unique=False,
1293 1293 default=None)
1294 1294 enable_locking = Column(
1295 1295 "enable_locking", Boolean(), nullable=False, unique=None,
1296 1296 default=False)
1297 1297 _locked = Column(
1298 1298 "locked", String(255), nullable=True, unique=False, default=None)
1299 1299 _changeset_cache = Column(
1300 1300 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1301 1301
1302 1302 fork_id = Column(
1303 1303 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1304 1304 nullable=True, unique=False, default=None)
1305 1305 group_id = Column(
1306 1306 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1307 1307 unique=False, default=None)
1308 1308
1309 1309 user = relationship('User', lazy='joined')
1310 1310 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1311 1311 group = relationship('RepoGroup', lazy='joined')
1312 1312 repo_to_perm = relationship(
1313 1313 'UserRepoToPerm', cascade='all',
1314 1314 order_by='UserRepoToPerm.repo_to_perm_id')
1315 1315 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1316 1316 stats = relationship('Statistics', cascade='all', uselist=False)
1317 1317
1318 1318 followers = relationship(
1319 1319 'UserFollowing',
1320 1320 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1321 1321 cascade='all')
1322 1322 extra_fields = relationship(
1323 1323 'RepositoryField', cascade="all, delete, delete-orphan")
1324 1324 logs = relationship('UserLog')
1325 1325 comments = relationship(
1326 1326 'ChangesetComment', cascade="all, delete, delete-orphan")
1327 1327 pull_requests_source = relationship(
1328 1328 'PullRequest',
1329 1329 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1330 1330 cascade="all, delete, delete-orphan")
1331 1331 pull_requests_target = relationship(
1332 1332 'PullRequest',
1333 1333 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1334 1334 cascade="all, delete, delete-orphan")
1335 1335 ui = relationship('RepoRhodeCodeUi', cascade="all")
1336 1336 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1337 1337 integrations = relationship('Integration',
1338 1338 cascade="all, delete, delete-orphan")
1339 1339
1340 1340 def __unicode__(self):
1341 1341 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1342 1342 safe_unicode(self.repo_name))
1343 1343
1344 1344 @hybrid_property
1345 1345 def landing_rev(self):
1346 1346 # always should return [rev_type, rev]
1347 1347 if self._landing_revision:
1348 1348 _rev_info = self._landing_revision.split(':')
1349 1349 if len(_rev_info) < 2:
1350 1350 _rev_info.insert(0, 'rev')
1351 1351 return [_rev_info[0], _rev_info[1]]
1352 1352 return [None, None]
1353 1353
1354 1354 @landing_rev.setter
1355 1355 def landing_rev(self, val):
1356 1356 if ':' not in val:
1357 1357 raise ValueError('value must be delimited with `:` and consist '
1358 1358 'of <rev_type>:<rev>, got %s instead' % val)
1359 1359 self._landing_revision = val
1360 1360
1361 1361 @hybrid_property
1362 1362 def locked(self):
1363 1363 if self._locked:
1364 1364 user_id, timelocked, reason = self._locked.split(':')
1365 1365 lock_values = int(user_id), timelocked, reason
1366 1366 else:
1367 1367 lock_values = [None, None, None]
1368 1368 return lock_values
1369 1369
1370 1370 @locked.setter
1371 1371 def locked(self, val):
1372 1372 if val and isinstance(val, (list, tuple)):
1373 1373 self._locked = ':'.join(map(str, val))
1374 1374 else:
1375 1375 self._locked = None
1376 1376
1377 1377 @hybrid_property
1378 1378 def changeset_cache(self):
1379 1379 from rhodecode.lib.vcs.backends.base import EmptyCommit
1380 1380 dummy = EmptyCommit().__json__()
1381 1381 if not self._changeset_cache:
1382 1382 return dummy
1383 1383 try:
1384 1384 return json.loads(self._changeset_cache)
1385 1385 except TypeError:
1386 1386 return dummy
1387 1387 except Exception:
1388 1388 log.error(traceback.format_exc())
1389 1389 return dummy
1390 1390
1391 1391 @changeset_cache.setter
1392 1392 def changeset_cache(self, val):
1393 1393 try:
1394 1394 self._changeset_cache = json.dumps(val)
1395 1395 except Exception:
1396 1396 log.error(traceback.format_exc())
1397 1397
1398 1398 @hybrid_property
1399 1399 def repo_name(self):
1400 1400 return self._repo_name
1401 1401
1402 1402 @repo_name.setter
1403 1403 def repo_name(self, value):
1404 1404 self._repo_name = value
1405 1405 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1406 1406
1407 1407 @classmethod
1408 1408 def normalize_repo_name(cls, repo_name):
1409 1409 """
1410 1410 Normalizes os specific repo_name to the format internally stored inside
1411 1411 database using URL_SEP
1412 1412
1413 1413 :param cls:
1414 1414 :param repo_name:
1415 1415 """
1416 1416 return cls.NAME_SEP.join(repo_name.split(os.sep))
1417 1417
1418 1418 @classmethod
1419 1419 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1420 1420 session = Session()
1421 1421 q = session.query(cls).filter(cls.repo_name == repo_name)
1422 1422
1423 1423 if cache:
1424 1424 if identity_cache:
1425 1425 val = cls.identity_cache(session, 'repo_name', repo_name)
1426 1426 if val:
1427 1427 return val
1428 1428 else:
1429 1429 q = q.options(
1430 1430 FromCache("sql_cache_short",
1431 1431 "get_repo_by_name_%s" % _hash_key(repo_name)))
1432 1432
1433 1433 return q.scalar()
1434 1434
1435 1435 @classmethod
1436 1436 def get_by_full_path(cls, repo_full_path):
1437 1437 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1438 1438 repo_name = cls.normalize_repo_name(repo_name)
1439 1439 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1440 1440
1441 1441 @classmethod
1442 1442 def get_repo_forks(cls, repo_id):
1443 1443 return cls.query().filter(Repository.fork_id == repo_id)
1444 1444
1445 1445 @classmethod
1446 1446 def base_path(cls):
1447 1447 """
1448 1448 Returns base path when all repos are stored
1449 1449
1450 1450 :param cls:
1451 1451 """
1452 1452 q = Session().query(RhodeCodeUi)\
1453 1453 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1454 1454 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1455 1455 return q.one().ui_value
1456 1456
1457 1457 @classmethod
1458 1458 def is_valid(cls, repo_name):
1459 1459 """
1460 1460 returns True if given repo name is a valid filesystem repository
1461 1461
1462 1462 :param cls:
1463 1463 :param repo_name:
1464 1464 """
1465 1465 from rhodecode.lib.utils import is_valid_repo
1466 1466
1467 1467 return is_valid_repo(repo_name, cls.base_path())
1468 1468
1469 1469 @classmethod
1470 1470 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1471 1471 case_insensitive=True):
1472 1472 q = Repository.query()
1473 1473
1474 1474 if not isinstance(user_id, Optional):
1475 1475 q = q.filter(Repository.user_id == user_id)
1476 1476
1477 1477 if not isinstance(group_id, Optional):
1478 1478 q = q.filter(Repository.group_id == group_id)
1479 1479
1480 1480 if case_insensitive:
1481 1481 q = q.order_by(func.lower(Repository.repo_name))
1482 1482 else:
1483 1483 q = q.order_by(Repository.repo_name)
1484 1484 return q.all()
1485 1485
1486 1486 @property
1487 1487 def forks(self):
1488 1488 """
1489 1489 Return forks of this repo
1490 1490 """
1491 1491 return Repository.get_repo_forks(self.repo_id)
1492 1492
1493 1493 @property
1494 1494 def parent(self):
1495 1495 """
1496 1496 Returns fork parent
1497 1497 """
1498 1498 return self.fork
1499 1499
1500 1500 @property
1501 1501 def just_name(self):
1502 1502 return self.repo_name.split(self.NAME_SEP)[-1]
1503 1503
1504 1504 @property
1505 1505 def groups_with_parents(self):
1506 1506 groups = []
1507 1507 if self.group is None:
1508 1508 return groups
1509 1509
1510 1510 cur_gr = self.group
1511 1511 groups.insert(0, cur_gr)
1512 1512 while 1:
1513 1513 gr = getattr(cur_gr, 'parent_group', None)
1514 1514 cur_gr = cur_gr.parent_group
1515 1515 if gr is None:
1516 1516 break
1517 1517 groups.insert(0, gr)
1518 1518
1519 1519 return groups
1520 1520
1521 1521 @property
1522 1522 def groups_and_repo(self):
1523 1523 return self.groups_with_parents, self
1524 1524
1525 1525 @LazyProperty
1526 1526 def repo_path(self):
1527 1527 """
1528 1528 Returns base full path for that repository means where it actually
1529 1529 exists on a filesystem
1530 1530 """
1531 1531 q = Session().query(RhodeCodeUi).filter(
1532 1532 RhodeCodeUi.ui_key == self.NAME_SEP)
1533 1533 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1534 1534 return q.one().ui_value
1535 1535
1536 1536 @property
1537 1537 def repo_full_path(self):
1538 1538 p = [self.repo_path]
1539 1539 # we need to split the name by / since this is how we store the
1540 1540 # names in the database, but that eventually needs to be converted
1541 1541 # into a valid system path
1542 1542 p += self.repo_name.split(self.NAME_SEP)
1543 1543 return os.path.join(*map(safe_unicode, p))
1544 1544
1545 1545 @property
1546 1546 def cache_keys(self):
1547 1547 """
1548 1548 Returns associated cache keys for that repo
1549 1549 """
1550 1550 return CacheKey.query()\
1551 1551 .filter(CacheKey.cache_args == self.repo_name)\
1552 1552 .order_by(CacheKey.cache_key)\
1553 1553 .all()
1554 1554
1555 1555 def get_new_name(self, repo_name):
1556 1556 """
1557 1557 returns new full repository name based on assigned group and new new
1558 1558
1559 1559 :param group_name:
1560 1560 """
1561 1561 path_prefix = self.group.full_path_splitted if self.group else []
1562 1562 return self.NAME_SEP.join(path_prefix + [repo_name])
1563 1563
1564 1564 @property
1565 1565 def _config(self):
1566 1566 """
1567 1567 Returns db based config object.
1568 1568 """
1569 1569 from rhodecode.lib.utils import make_db_config
1570 1570 return make_db_config(clear_session=False, repo=self)
1571 1571
1572 1572 def permissions(self, with_admins=True, with_owner=True):
1573 1573 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1574 1574 q = q.options(joinedload(UserRepoToPerm.repository),
1575 1575 joinedload(UserRepoToPerm.user),
1576 1576 joinedload(UserRepoToPerm.permission),)
1577 1577
1578 1578 # get owners and admins and permissions. We do a trick of re-writing
1579 1579 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1580 1580 # has a global reference and changing one object propagates to all
1581 1581 # others. This means if admin is also an owner admin_row that change
1582 1582 # would propagate to both objects
1583 1583 perm_rows = []
1584 1584 for _usr in q.all():
1585 1585 usr = AttributeDict(_usr.user.get_dict())
1586 1586 usr.permission = _usr.permission.permission_name
1587 1587 perm_rows.append(usr)
1588 1588
1589 1589 # filter the perm rows by 'default' first and then sort them by
1590 1590 # admin,write,read,none permissions sorted again alphabetically in
1591 1591 # each group
1592 1592 perm_rows = sorted(perm_rows, key=display_sort)
1593 1593
1594 1594 _admin_perm = 'repository.admin'
1595 1595 owner_row = []
1596 1596 if with_owner:
1597 1597 usr = AttributeDict(self.user.get_dict())
1598 1598 usr.owner_row = True
1599 1599 usr.permission = _admin_perm
1600 1600 owner_row.append(usr)
1601 1601
1602 1602 super_admin_rows = []
1603 1603 if with_admins:
1604 1604 for usr in User.get_all_super_admins():
1605 1605 # if this admin is also owner, don't double the record
1606 1606 if usr.user_id == owner_row[0].user_id:
1607 1607 owner_row[0].admin_row = True
1608 1608 else:
1609 1609 usr = AttributeDict(usr.get_dict())
1610 1610 usr.admin_row = True
1611 1611 usr.permission = _admin_perm
1612 1612 super_admin_rows.append(usr)
1613 1613
1614 1614 return super_admin_rows + owner_row + perm_rows
1615 1615
1616 1616 def permission_user_groups(self):
1617 1617 q = UserGroupRepoToPerm.query().filter(
1618 1618 UserGroupRepoToPerm.repository == self)
1619 1619 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1620 1620 joinedload(UserGroupRepoToPerm.users_group),
1621 1621 joinedload(UserGroupRepoToPerm.permission),)
1622 1622
1623 1623 perm_rows = []
1624 1624 for _user_group in q.all():
1625 1625 usr = AttributeDict(_user_group.users_group.get_dict())
1626 1626 usr.permission = _user_group.permission.permission_name
1627 1627 perm_rows.append(usr)
1628 1628
1629 1629 return perm_rows
1630 1630
1631 1631 def get_api_data(self, include_secrets=False):
1632 1632 """
1633 1633 Common function for generating repo api data
1634 1634
1635 1635 :param include_secrets: See :meth:`User.get_api_data`.
1636 1636
1637 1637 """
1638 1638 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1639 1639 # move this methods on models level.
1640 1640 from rhodecode.model.settings import SettingsModel
1641 1641
1642 1642 repo = self
1643 1643 _user_id, _time, _reason = self.locked
1644 1644
1645 1645 data = {
1646 1646 'repo_id': repo.repo_id,
1647 1647 'repo_name': repo.repo_name,
1648 1648 'repo_type': repo.repo_type,
1649 1649 'clone_uri': repo.clone_uri or '',
1650 1650 'url': url('summary_home', repo_name=self.repo_name, qualified=True),
1651 1651 'private': repo.private,
1652 1652 'created_on': repo.created_on,
1653 1653 'description': repo.description,
1654 1654 'landing_rev': repo.landing_rev,
1655 1655 'owner': repo.user.username,
1656 1656 'fork_of': repo.fork.repo_name if repo.fork else None,
1657 1657 'enable_statistics': repo.enable_statistics,
1658 1658 'enable_locking': repo.enable_locking,
1659 1659 'enable_downloads': repo.enable_downloads,
1660 1660 'last_changeset': repo.changeset_cache,
1661 1661 'locked_by': User.get(_user_id).get_api_data(
1662 1662 include_secrets=include_secrets) if _user_id else None,
1663 1663 'locked_date': time_to_datetime(_time) if _time else None,
1664 1664 'lock_reason': _reason if _reason else None,
1665 1665 }
1666 1666
1667 1667 # TODO: mikhail: should be per-repo settings here
1668 1668 rc_config = SettingsModel().get_all_settings()
1669 1669 repository_fields = str2bool(
1670 1670 rc_config.get('rhodecode_repository_fields'))
1671 1671 if repository_fields:
1672 1672 for f in self.extra_fields:
1673 1673 data[f.field_key_prefixed] = f.field_value
1674 1674
1675 1675 return data
1676 1676
1677 1677 @classmethod
1678 1678 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1679 1679 if not lock_time:
1680 1680 lock_time = time.time()
1681 1681 if not lock_reason:
1682 1682 lock_reason = cls.LOCK_AUTOMATIC
1683 1683 repo.locked = [user_id, lock_time, lock_reason]
1684 1684 Session().add(repo)
1685 1685 Session().commit()
1686 1686
1687 1687 @classmethod
1688 1688 def unlock(cls, repo):
1689 1689 repo.locked = None
1690 1690 Session().add(repo)
1691 1691 Session().commit()
1692 1692
1693 1693 @classmethod
1694 1694 def getlock(cls, repo):
1695 1695 return repo.locked
1696 1696
1697 1697 def is_user_lock(self, user_id):
1698 1698 if self.lock[0]:
1699 1699 lock_user_id = safe_int(self.lock[0])
1700 1700 user_id = safe_int(user_id)
1701 1701 # both are ints, and they are equal
1702 1702 return all([lock_user_id, user_id]) and lock_user_id == user_id
1703 1703
1704 1704 return False
1705 1705
1706 1706 def get_locking_state(self, action, user_id, only_when_enabled=True):
1707 1707 """
1708 1708 Checks locking on this repository, if locking is enabled and lock is
1709 1709 present returns a tuple of make_lock, locked, locked_by.
1710 1710 make_lock can have 3 states None (do nothing) True, make lock
1711 1711 False release lock, This value is later propagated to hooks, which
1712 1712 do the locking. Think about this as signals passed to hooks what to do.
1713 1713
1714 1714 """
1715 1715 # TODO: johbo: This is part of the business logic and should be moved
1716 1716 # into the RepositoryModel.
1717 1717
1718 1718 if action not in ('push', 'pull'):
1719 1719 raise ValueError("Invalid action value: %s" % repr(action))
1720 1720
1721 1721 # defines if locked error should be thrown to user
1722 1722 currently_locked = False
1723 1723 # defines if new lock should be made, tri-state
1724 1724 make_lock = None
1725 1725 repo = self
1726 1726 user = User.get(user_id)
1727 1727
1728 1728 lock_info = repo.locked
1729 1729
1730 1730 if repo and (repo.enable_locking or not only_when_enabled):
1731 1731 if action == 'push':
1732 1732 # check if it's already locked !, if it is compare users
1733 1733 locked_by_user_id = lock_info[0]
1734 1734 if user.user_id == locked_by_user_id:
1735 1735 log.debug(
1736 1736 'Got `push` action from user %s, now unlocking', user)
1737 1737 # unlock if we have push from user who locked
1738 1738 make_lock = False
1739 1739 else:
1740 1740 # we're not the same user who locked, ban with
1741 1741 # code defined in settings (default is 423 HTTP Locked) !
1742 1742 log.debug('Repo %s is currently locked by %s', repo, user)
1743 1743 currently_locked = True
1744 1744 elif action == 'pull':
1745 1745 # [0] user [1] date
1746 1746 if lock_info[0] and lock_info[1]:
1747 1747 log.debug('Repo %s is currently locked by %s', repo, user)
1748 1748 currently_locked = True
1749 1749 else:
1750 1750 log.debug('Setting lock on repo %s by %s', repo, user)
1751 1751 make_lock = True
1752 1752
1753 1753 else:
1754 1754 log.debug('Repository %s do not have locking enabled', repo)
1755 1755
1756 1756 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
1757 1757 make_lock, currently_locked, lock_info)
1758 1758
1759 1759 from rhodecode.lib.auth import HasRepoPermissionAny
1760 1760 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
1761 1761 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
1762 1762 # if we don't have at least write permission we cannot make a lock
1763 1763 log.debug('lock state reset back to FALSE due to lack '
1764 1764 'of at least read permission')
1765 1765 make_lock = False
1766 1766
1767 1767 return make_lock, currently_locked, lock_info
1768 1768
1769 1769 @property
1770 1770 def last_db_change(self):
1771 1771 return self.updated_on
1772 1772
1773 1773 @property
1774 1774 def clone_uri_hidden(self):
1775 1775 clone_uri = self.clone_uri
1776 1776 if clone_uri:
1777 1777 import urlobject
1778 1778 url_obj = urlobject.URLObject(clone_uri)
1779 1779 if url_obj.password:
1780 1780 clone_uri = url_obj.with_password('*****')
1781 1781 return clone_uri
1782 1782
1783 1783 def clone_url(self, **override):
1784 1784 qualified_home_url = url('home', qualified=True)
1785 1785
1786 1786 uri_tmpl = None
1787 1787 if 'with_id' in override:
1788 1788 uri_tmpl = self.DEFAULT_CLONE_URI_ID
1789 1789 del override['with_id']
1790 1790
1791 1791 if 'uri_tmpl' in override:
1792 1792 uri_tmpl = override['uri_tmpl']
1793 1793 del override['uri_tmpl']
1794 1794
1795 1795 # we didn't override our tmpl from **overrides
1796 1796 if not uri_tmpl:
1797 1797 uri_tmpl = self.DEFAULT_CLONE_URI
1798 1798 try:
1799 1799 from pylons import tmpl_context as c
1800 1800 uri_tmpl = c.clone_uri_tmpl
1801 1801 except Exception:
1802 1802 # in any case if we call this outside of request context,
1803 1803 # ie, not having tmpl_context set up
1804 1804 pass
1805 1805
1806 1806 return get_clone_url(uri_tmpl=uri_tmpl,
1807 1807 qualifed_home_url=qualified_home_url,
1808 1808 repo_name=self.repo_name,
1809 1809 repo_id=self.repo_id, **override)
1810 1810
1811 1811 def set_state(self, state):
1812 1812 self.repo_state = state
1813 1813 Session().add(self)
1814 1814 #==========================================================================
1815 1815 # SCM PROPERTIES
1816 1816 #==========================================================================
1817 1817
1818 1818 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
1819 1819 return get_commit_safe(
1820 1820 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
1821 1821
1822 1822 def get_changeset(self, rev=None, pre_load=None):
1823 1823 warnings.warn("Use get_commit", DeprecationWarning)
1824 1824 commit_id = None
1825 1825 commit_idx = None
1826 1826 if isinstance(rev, basestring):
1827 1827 commit_id = rev
1828 1828 else:
1829 1829 commit_idx = rev
1830 1830 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
1831 1831 pre_load=pre_load)
1832 1832
1833 1833 def get_landing_commit(self):
1834 1834 """
1835 1835 Returns landing commit, or if that doesn't exist returns the tip
1836 1836 """
1837 1837 _rev_type, _rev = self.landing_rev
1838 1838 commit = self.get_commit(_rev)
1839 1839 if isinstance(commit, EmptyCommit):
1840 1840 return self.get_commit()
1841 1841 return commit
1842 1842
1843 1843 def update_commit_cache(self, cs_cache=None, config=None):
1844 1844 """
1845 1845 Update cache of last changeset for repository, keys should be::
1846 1846
1847 1847 short_id
1848 1848 raw_id
1849 1849 revision
1850 1850 parents
1851 1851 message
1852 1852 date
1853 1853 author
1854 1854
1855 1855 :param cs_cache:
1856 1856 """
1857 1857 from rhodecode.lib.vcs.backends.base import BaseChangeset
1858 1858 if cs_cache is None:
1859 1859 # use no-cache version here
1860 1860 scm_repo = self.scm_instance(cache=False, config=config)
1861 1861 if scm_repo:
1862 1862 cs_cache = scm_repo.get_commit(
1863 1863 pre_load=["author", "date", "message", "parents"])
1864 1864 else:
1865 1865 cs_cache = EmptyCommit()
1866 1866
1867 1867 if isinstance(cs_cache, BaseChangeset):
1868 1868 cs_cache = cs_cache.__json__()
1869 1869
1870 1870 def is_outdated(new_cs_cache):
1871 1871 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
1872 1872 new_cs_cache['revision'] != self.changeset_cache['revision']):
1873 1873 return True
1874 1874 return False
1875 1875
1876 1876 # check if we have maybe already latest cached revision
1877 1877 if is_outdated(cs_cache) or not self.changeset_cache:
1878 1878 _default = datetime.datetime.fromtimestamp(0)
1879 1879 last_change = cs_cache.get('date') or _default
1880 1880 log.debug('updated repo %s with new cs cache %s',
1881 1881 self.repo_name, cs_cache)
1882 1882 self.updated_on = last_change
1883 1883 self.changeset_cache = cs_cache
1884 1884 Session().add(self)
1885 1885 Session().commit()
1886 1886 else:
1887 1887 log.debug('Skipping update_commit_cache for repo:`%s` '
1888 1888 'commit already with latest changes', self.repo_name)
1889 1889
1890 1890 @property
1891 1891 def tip(self):
1892 1892 return self.get_commit('tip')
1893 1893
1894 1894 @property
1895 1895 def author(self):
1896 1896 return self.tip.author
1897 1897
1898 1898 @property
1899 1899 def last_change(self):
1900 1900 return self.scm_instance().last_change
1901 1901
1902 1902 def get_comments(self, revisions=None):
1903 1903 """
1904 1904 Returns comments for this repository grouped by revisions
1905 1905
1906 1906 :param revisions: filter query by revisions only
1907 1907 """
1908 1908 cmts = ChangesetComment.query()\
1909 1909 .filter(ChangesetComment.repo == self)
1910 1910 if revisions:
1911 1911 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
1912 1912 grouped = collections.defaultdict(list)
1913 1913 for cmt in cmts.all():
1914 1914 grouped[cmt.revision].append(cmt)
1915 1915 return grouped
1916 1916
1917 1917 def statuses(self, revisions=None):
1918 1918 """
1919 1919 Returns statuses for this repository
1920 1920
1921 1921 :param revisions: list of revisions to get statuses for
1922 1922 """
1923 1923 statuses = ChangesetStatus.query()\
1924 1924 .filter(ChangesetStatus.repo == self)\
1925 1925 .filter(ChangesetStatus.version == 0)
1926 1926
1927 1927 if revisions:
1928 1928 # Try doing the filtering in chunks to avoid hitting limits
1929 1929 size = 500
1930 1930 status_results = []
1931 1931 for chunk in xrange(0, len(revisions), size):
1932 1932 status_results += statuses.filter(
1933 1933 ChangesetStatus.revision.in_(
1934 1934 revisions[chunk: chunk+size])
1935 1935 ).all()
1936 1936 else:
1937 1937 status_results = statuses.all()
1938 1938
1939 1939 grouped = {}
1940 1940
1941 1941 # maybe we have open new pullrequest without a status?
1942 1942 stat = ChangesetStatus.STATUS_UNDER_REVIEW
1943 1943 status_lbl = ChangesetStatus.get_status_lbl(stat)
1944 1944 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
1945 1945 for rev in pr.revisions:
1946 1946 pr_id = pr.pull_request_id
1947 1947 pr_repo = pr.target_repo.repo_name
1948 1948 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
1949 1949
1950 1950 for stat in status_results:
1951 1951 pr_id = pr_repo = None
1952 1952 if stat.pull_request:
1953 1953 pr_id = stat.pull_request.pull_request_id
1954 1954 pr_repo = stat.pull_request.target_repo.repo_name
1955 1955 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
1956 1956 pr_id, pr_repo]
1957 1957 return grouped
1958 1958
1959 1959 # ==========================================================================
1960 1960 # SCM CACHE INSTANCE
1961 1961 # ==========================================================================
1962 1962
1963 1963 def scm_instance(self, **kwargs):
1964 1964 import rhodecode
1965 1965
1966 1966 # Passing a config will not hit the cache currently only used
1967 1967 # for repo2dbmapper
1968 1968 config = kwargs.pop('config', None)
1969 1969 cache = kwargs.pop('cache', None)
1970 1970 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
1971 1971 # if cache is NOT defined use default global, else we have a full
1972 1972 # control over cache behaviour
1973 1973 if cache is None and full_cache and not config:
1974 1974 return self._get_instance_cached()
1975 1975 return self._get_instance(cache=bool(cache), config=config)
1976 1976
1977 1977 def _get_instance_cached(self):
1978 1978 @cache_region('long_term')
1979 1979 def _get_repo(cache_key):
1980 1980 return self._get_instance()
1981 1981
1982 1982 invalidator_context = CacheKey.repo_context_cache(
1983 1983 _get_repo, self.repo_name, None, thread_scoped=True)
1984 1984
1985 1985 with invalidator_context as context:
1986 1986 context.invalidate()
1987 1987 repo = context.compute()
1988 1988
1989 1989 return repo
1990 1990
1991 1991 def _get_instance(self, cache=True, config=None):
1992 1992 config = config or self._config
1993 1993 custom_wire = {
1994 1994 'cache': cache # controls the vcs.remote cache
1995 1995 }
1996 1996 repo = get_vcs_instance(
1997 1997 repo_path=safe_str(self.repo_full_path),
1998 1998 config=config,
1999 1999 with_wire=custom_wire,
2000 2000 create=False,
2001 2001 _vcs_alias=self.repo_type)
2002 2002
2003 2003 return repo
2004 2004
2005 2005 def __json__(self):
2006 2006 return {'landing_rev': self.landing_rev}
2007 2007
2008 2008 def get_dict(self):
2009 2009
2010 2010 # Since we transformed `repo_name` to a hybrid property, we need to
2011 2011 # keep compatibility with the code which uses `repo_name` field.
2012 2012
2013 2013 result = super(Repository, self).get_dict()
2014 2014 result['repo_name'] = result.pop('_repo_name', None)
2015 2015 return result
2016 2016
2017 2017
2018 2018 class RepoGroup(Base, BaseModel):
2019 2019 __tablename__ = 'groups'
2020 2020 __table_args__ = (
2021 2021 UniqueConstraint('group_name', 'group_parent_id'),
2022 2022 CheckConstraint('group_id != group_parent_id'),
2023 2023 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2024 2024 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2025 2025 )
2026 2026 __mapper_args__ = {'order_by': 'group_name'}
2027 2027
2028 2028 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2029 2029
2030 2030 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2031 2031 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2032 2032 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2033 2033 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2034 2034 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2035 2035 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2036 2036 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2037 2037 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2038 2038
2039 2039 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2040 2040 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2041 2041 parent_group = relationship('RepoGroup', remote_side=group_id)
2042 2042 user = relationship('User')
2043 2043 integrations = relationship('Integration',
2044 2044 cascade="all, delete, delete-orphan")
2045 2045
2046 2046 def __init__(self, group_name='', parent_group=None):
2047 2047 self.group_name = group_name
2048 2048 self.parent_group = parent_group
2049 2049
2050 2050 def __unicode__(self):
2051 2051 return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
2052 2052 self.group_name)
2053 2053
2054 2054 @classmethod
2055 2055 def _generate_choice(cls, repo_group):
2056 2056 from webhelpers.html import literal as _literal
2057 2057 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2058 2058 return repo_group.group_id, _name(repo_group.full_path_splitted)
2059 2059
2060 2060 @classmethod
2061 2061 def groups_choices(cls, groups=None, show_empty_group=True):
2062 2062 if not groups:
2063 2063 groups = cls.query().all()
2064 2064
2065 2065 repo_groups = []
2066 2066 if show_empty_group:
2067 2067 repo_groups = [('-1', u'-- %s --' % _('No parent'))]
2068 2068
2069 2069 repo_groups.extend([cls._generate_choice(x) for x in groups])
2070 2070
2071 2071 repo_groups = sorted(
2072 2072 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2073 2073 return repo_groups
2074 2074
2075 2075 @classmethod
2076 2076 def url_sep(cls):
2077 2077 return URL_SEP
2078 2078
2079 2079 @classmethod
2080 2080 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2081 2081 if case_insensitive:
2082 2082 gr = cls.query().filter(func.lower(cls.group_name)
2083 2083 == func.lower(group_name))
2084 2084 else:
2085 2085 gr = cls.query().filter(cls.group_name == group_name)
2086 2086 if cache:
2087 2087 gr = gr.options(FromCache(
2088 2088 "sql_cache_short",
2089 2089 "get_group_%s" % _hash_key(group_name)))
2090 2090 return gr.scalar()
2091 2091
2092 2092 @classmethod
2093 2093 def get_user_personal_repo_group(cls, user_id):
2094 2094 user = User.get(user_id)
2095 2095 return cls.query()\
2096 2096 .filter(cls.personal == true())\
2097 2097 .filter(cls.user == user).scalar()
2098 2098
2099 2099 @classmethod
2100 2100 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2101 2101 case_insensitive=True):
2102 2102 q = RepoGroup.query()
2103 2103
2104 2104 if not isinstance(user_id, Optional):
2105 2105 q = q.filter(RepoGroup.user_id == user_id)
2106 2106
2107 2107 if not isinstance(group_id, Optional):
2108 2108 q = q.filter(RepoGroup.group_parent_id == group_id)
2109 2109
2110 2110 if case_insensitive:
2111 2111 q = q.order_by(func.lower(RepoGroup.group_name))
2112 2112 else:
2113 2113 q = q.order_by(RepoGroup.group_name)
2114 2114 return q.all()
2115 2115
2116 2116 @property
2117 2117 def parents(self):
2118 2118 parents_recursion_limit = 10
2119 2119 groups = []
2120 2120 if self.parent_group is None:
2121 2121 return groups
2122 2122 cur_gr = self.parent_group
2123 2123 groups.insert(0, cur_gr)
2124 2124 cnt = 0
2125 2125 while 1:
2126 2126 cnt += 1
2127 2127 gr = getattr(cur_gr, 'parent_group', None)
2128 2128 cur_gr = cur_gr.parent_group
2129 2129 if gr is None:
2130 2130 break
2131 2131 if cnt == parents_recursion_limit:
2132 2132 # this will prevent accidental infinit loops
2133 2133 log.error(('more than %s parents found for group %s, stopping '
2134 2134 'recursive parent fetching' % (parents_recursion_limit, self)))
2135 2135 break
2136 2136
2137 2137 groups.insert(0, gr)
2138 2138 return groups
2139 2139
2140 2140 @property
2141 2141 def children(self):
2142 2142 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2143 2143
2144 2144 @property
2145 2145 def name(self):
2146 2146 return self.group_name.split(RepoGroup.url_sep())[-1]
2147 2147
2148 2148 @property
2149 2149 def full_path(self):
2150 2150 return self.group_name
2151 2151
2152 2152 @property
2153 2153 def full_path_splitted(self):
2154 2154 return self.group_name.split(RepoGroup.url_sep())
2155 2155
2156 2156 @property
2157 2157 def repositories(self):
2158 2158 return Repository.query()\
2159 2159 .filter(Repository.group == self)\
2160 2160 .order_by(Repository.repo_name)
2161 2161
2162 2162 @property
2163 2163 def repositories_recursive_count(self):
2164 2164 cnt = self.repositories.count()
2165 2165
2166 2166 def children_count(group):
2167 2167 cnt = 0
2168 2168 for child in group.children:
2169 2169 cnt += child.repositories.count()
2170 2170 cnt += children_count(child)
2171 2171 return cnt
2172 2172
2173 2173 return cnt + children_count(self)
2174 2174
2175 2175 def _recursive_objects(self, include_repos=True):
2176 2176 all_ = []
2177 2177
2178 2178 def _get_members(root_gr):
2179 2179 if include_repos:
2180 2180 for r in root_gr.repositories:
2181 2181 all_.append(r)
2182 2182 childs = root_gr.children.all()
2183 2183 if childs:
2184 2184 for gr in childs:
2185 2185 all_.append(gr)
2186 2186 _get_members(gr)
2187 2187
2188 2188 _get_members(self)
2189 2189 return [self] + all_
2190 2190
2191 2191 def recursive_groups_and_repos(self):
2192 2192 """
2193 2193 Recursive return all groups, with repositories in those groups
2194 2194 """
2195 2195 return self._recursive_objects()
2196 2196
2197 2197 def recursive_groups(self):
2198 2198 """
2199 2199 Returns all children groups for this group including children of children
2200 2200 """
2201 2201 return self._recursive_objects(include_repos=False)
2202 2202
2203 2203 def get_new_name(self, group_name):
2204 2204 """
2205 2205 returns new full group name based on parent and new name
2206 2206
2207 2207 :param group_name:
2208 2208 """
2209 2209 path_prefix = (self.parent_group.full_path_splitted if
2210 2210 self.parent_group else [])
2211 2211 return RepoGroup.url_sep().join(path_prefix + [group_name])
2212 2212
2213 2213 def permissions(self, with_admins=True, with_owner=True):
2214 2214 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2215 2215 q = q.options(joinedload(UserRepoGroupToPerm.group),
2216 2216 joinedload(UserRepoGroupToPerm.user),
2217 2217 joinedload(UserRepoGroupToPerm.permission),)
2218 2218
2219 2219 # get owners and admins and permissions. We do a trick of re-writing
2220 2220 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2221 2221 # has a global reference and changing one object propagates to all
2222 2222 # others. This means if admin is also an owner admin_row that change
2223 2223 # would propagate to both objects
2224 2224 perm_rows = []
2225 2225 for _usr in q.all():
2226 2226 usr = AttributeDict(_usr.user.get_dict())
2227 2227 usr.permission = _usr.permission.permission_name
2228 2228 perm_rows.append(usr)
2229 2229
2230 2230 # filter the perm rows by 'default' first and then sort them by
2231 2231 # admin,write,read,none permissions sorted again alphabetically in
2232 2232 # each group
2233 2233 perm_rows = sorted(perm_rows, key=display_sort)
2234 2234
2235 2235 _admin_perm = 'group.admin'
2236 2236 owner_row = []
2237 2237 if with_owner:
2238 2238 usr = AttributeDict(self.user.get_dict())
2239 2239 usr.owner_row = True
2240 2240 usr.permission = _admin_perm
2241 2241 owner_row.append(usr)
2242 2242
2243 2243 super_admin_rows = []
2244 2244 if with_admins:
2245 2245 for usr in User.get_all_super_admins():
2246 2246 # if this admin is also owner, don't double the record
2247 2247 if usr.user_id == owner_row[0].user_id:
2248 2248 owner_row[0].admin_row = True
2249 2249 else:
2250 2250 usr = AttributeDict(usr.get_dict())
2251 2251 usr.admin_row = True
2252 2252 usr.permission = _admin_perm
2253 2253 super_admin_rows.append(usr)
2254 2254
2255 2255 return super_admin_rows + owner_row + perm_rows
2256 2256
2257 2257 def permission_user_groups(self):
2258 2258 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2259 2259 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2260 2260 joinedload(UserGroupRepoGroupToPerm.users_group),
2261 2261 joinedload(UserGroupRepoGroupToPerm.permission),)
2262 2262
2263 2263 perm_rows = []
2264 2264 for _user_group in q.all():
2265 2265 usr = AttributeDict(_user_group.users_group.get_dict())
2266 2266 usr.permission = _user_group.permission.permission_name
2267 2267 perm_rows.append(usr)
2268 2268
2269 2269 return perm_rows
2270 2270
2271 2271 def get_api_data(self):
2272 2272 """
2273 2273 Common function for generating api data
2274 2274
2275 2275 """
2276 2276 group = self
2277 2277 data = {
2278 2278 'group_id': group.group_id,
2279 2279 'group_name': group.group_name,
2280 2280 'group_description': group.group_description,
2281 2281 'parent_group': group.parent_group.group_name if group.parent_group else None,
2282 2282 'repositories': [x.repo_name for x in group.repositories],
2283 2283 'owner': group.user.username,
2284 2284 }
2285 2285 return data
2286 2286
2287 2287
2288 2288 class Permission(Base, BaseModel):
2289 2289 __tablename__ = 'permissions'
2290 2290 __table_args__ = (
2291 2291 Index('p_perm_name_idx', 'permission_name'),
2292 2292 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2293 2293 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2294 2294 )
2295 2295 PERMS = [
2296 2296 ('hg.admin', _('RhodeCode Super Administrator')),
2297 2297
2298 2298 ('repository.none', _('Repository no access')),
2299 2299 ('repository.read', _('Repository read access')),
2300 2300 ('repository.write', _('Repository write access')),
2301 2301 ('repository.admin', _('Repository admin access')),
2302 2302
2303 2303 ('group.none', _('Repository group no access')),
2304 2304 ('group.read', _('Repository group read access')),
2305 2305 ('group.write', _('Repository group write access')),
2306 2306 ('group.admin', _('Repository group admin access')),
2307 2307
2308 2308 ('usergroup.none', _('User group no access')),
2309 2309 ('usergroup.read', _('User group read access')),
2310 2310 ('usergroup.write', _('User group write access')),
2311 2311 ('usergroup.admin', _('User group admin access')),
2312 2312
2313 2313 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2314 2314 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2315 2315
2316 2316 ('hg.usergroup.create.false', _('User Group creation disabled')),
2317 2317 ('hg.usergroup.create.true', _('User Group creation enabled')),
2318 2318
2319 2319 ('hg.create.none', _('Repository creation disabled')),
2320 2320 ('hg.create.repository', _('Repository creation enabled')),
2321 2321 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2322 2322 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2323 2323
2324 2324 ('hg.fork.none', _('Repository forking disabled')),
2325 2325 ('hg.fork.repository', _('Repository forking enabled')),
2326 2326
2327 2327 ('hg.register.none', _('Registration disabled')),
2328 2328 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2329 2329 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2330 2330
2331 2331 ('hg.password_reset.enabled', _('Password reset enabled')),
2332 2332 ('hg.password_reset.hidden', _('Password reset hidden')),
2333 2333 ('hg.password_reset.disabled', _('Password reset disabled')),
2334 2334
2335 2335 ('hg.extern_activate.manual', _('Manual activation of external account')),
2336 2336 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2337 2337
2338 2338 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2339 2339 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2340 2340 ]
2341 2341
2342 2342 # definition of system default permissions for DEFAULT user
2343 2343 DEFAULT_USER_PERMISSIONS = [
2344 2344 'repository.read',
2345 2345 'group.read',
2346 2346 'usergroup.read',
2347 2347 'hg.create.repository',
2348 2348 'hg.repogroup.create.false',
2349 2349 'hg.usergroup.create.false',
2350 2350 'hg.create.write_on_repogroup.true',
2351 2351 'hg.fork.repository',
2352 2352 'hg.register.manual_activate',
2353 2353 'hg.password_reset.enabled',
2354 2354 'hg.extern_activate.auto',
2355 2355 'hg.inherit_default_perms.true',
2356 2356 ]
2357 2357
2358 2358 # defines which permissions are more important higher the more important
2359 2359 # Weight defines which permissions are more important.
2360 2360 # The higher number the more important.
2361 2361 PERM_WEIGHTS = {
2362 2362 'repository.none': 0,
2363 2363 'repository.read': 1,
2364 2364 'repository.write': 3,
2365 2365 'repository.admin': 4,
2366 2366
2367 2367 'group.none': 0,
2368 2368 'group.read': 1,
2369 2369 'group.write': 3,
2370 2370 'group.admin': 4,
2371 2371
2372 2372 'usergroup.none': 0,
2373 2373 'usergroup.read': 1,
2374 2374 'usergroup.write': 3,
2375 2375 'usergroup.admin': 4,
2376 2376
2377 2377 'hg.repogroup.create.false': 0,
2378 2378 'hg.repogroup.create.true': 1,
2379 2379
2380 2380 'hg.usergroup.create.false': 0,
2381 2381 'hg.usergroup.create.true': 1,
2382 2382
2383 2383 'hg.fork.none': 0,
2384 2384 'hg.fork.repository': 1,
2385 2385 'hg.create.none': 0,
2386 2386 'hg.create.repository': 1
2387 2387 }
2388 2388
2389 2389 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2390 2390 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2391 2391 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2392 2392
2393 2393 def __unicode__(self):
2394 2394 return u"<%s('%s:%s')>" % (
2395 2395 self.__class__.__name__, self.permission_id, self.permission_name
2396 2396 )
2397 2397
2398 2398 @classmethod
2399 2399 def get_by_key(cls, key):
2400 2400 return cls.query().filter(cls.permission_name == key).scalar()
2401 2401
2402 2402 @classmethod
2403 2403 def get_default_repo_perms(cls, user_id, repo_id=None):
2404 2404 q = Session().query(UserRepoToPerm, Repository, Permission)\
2405 2405 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2406 2406 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2407 2407 .filter(UserRepoToPerm.user_id == user_id)
2408 2408 if repo_id:
2409 2409 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2410 2410 return q.all()
2411 2411
2412 2412 @classmethod
2413 2413 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2414 2414 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2415 2415 .join(
2416 2416 Permission,
2417 2417 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2418 2418 .join(
2419 2419 Repository,
2420 2420 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2421 2421 .join(
2422 2422 UserGroup,
2423 2423 UserGroupRepoToPerm.users_group_id ==
2424 2424 UserGroup.users_group_id)\
2425 2425 .join(
2426 2426 UserGroupMember,
2427 2427 UserGroupRepoToPerm.users_group_id ==
2428 2428 UserGroupMember.users_group_id)\
2429 2429 .filter(
2430 2430 UserGroupMember.user_id == user_id,
2431 2431 UserGroup.users_group_active == true())
2432 2432 if repo_id:
2433 2433 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2434 2434 return q.all()
2435 2435
2436 2436 @classmethod
2437 2437 def get_default_group_perms(cls, user_id, repo_group_id=None):
2438 2438 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2439 2439 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2440 2440 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2441 2441 .filter(UserRepoGroupToPerm.user_id == user_id)
2442 2442 if repo_group_id:
2443 2443 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2444 2444 return q.all()
2445 2445
2446 2446 @classmethod
2447 2447 def get_default_group_perms_from_user_group(
2448 2448 cls, user_id, repo_group_id=None):
2449 2449 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2450 2450 .join(
2451 2451 Permission,
2452 2452 UserGroupRepoGroupToPerm.permission_id ==
2453 2453 Permission.permission_id)\
2454 2454 .join(
2455 2455 RepoGroup,
2456 2456 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2457 2457 .join(
2458 2458 UserGroup,
2459 2459 UserGroupRepoGroupToPerm.users_group_id ==
2460 2460 UserGroup.users_group_id)\
2461 2461 .join(
2462 2462 UserGroupMember,
2463 2463 UserGroupRepoGroupToPerm.users_group_id ==
2464 2464 UserGroupMember.users_group_id)\
2465 2465 .filter(
2466 2466 UserGroupMember.user_id == user_id,
2467 2467 UserGroup.users_group_active == true())
2468 2468 if repo_group_id:
2469 2469 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2470 2470 return q.all()
2471 2471
2472 2472 @classmethod
2473 2473 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2474 2474 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2475 2475 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2476 2476 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2477 2477 .filter(UserUserGroupToPerm.user_id == user_id)
2478 2478 if user_group_id:
2479 2479 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2480 2480 return q.all()
2481 2481
2482 2482 @classmethod
2483 2483 def get_default_user_group_perms_from_user_group(
2484 2484 cls, user_id, user_group_id=None):
2485 2485 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2486 2486 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2487 2487 .join(
2488 2488 Permission,
2489 2489 UserGroupUserGroupToPerm.permission_id ==
2490 2490 Permission.permission_id)\
2491 2491 .join(
2492 2492 TargetUserGroup,
2493 2493 UserGroupUserGroupToPerm.target_user_group_id ==
2494 2494 TargetUserGroup.users_group_id)\
2495 2495 .join(
2496 2496 UserGroup,
2497 2497 UserGroupUserGroupToPerm.user_group_id ==
2498 2498 UserGroup.users_group_id)\
2499 2499 .join(
2500 2500 UserGroupMember,
2501 2501 UserGroupUserGroupToPerm.user_group_id ==
2502 2502 UserGroupMember.users_group_id)\
2503 2503 .filter(
2504 2504 UserGroupMember.user_id == user_id,
2505 2505 UserGroup.users_group_active == true())
2506 2506 if user_group_id:
2507 2507 q = q.filter(
2508 2508 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2509 2509
2510 2510 return q.all()
2511 2511
2512 2512
2513 2513 class UserRepoToPerm(Base, BaseModel):
2514 2514 __tablename__ = 'repo_to_perm'
2515 2515 __table_args__ = (
2516 2516 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2517 2517 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2518 2518 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2519 2519 )
2520 2520 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2521 2521 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2522 2522 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2523 2523 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2524 2524
2525 2525 user = relationship('User')
2526 2526 repository = relationship('Repository')
2527 2527 permission = relationship('Permission')
2528 2528
2529 2529 @classmethod
2530 2530 def create(cls, user, repository, permission):
2531 2531 n = cls()
2532 2532 n.user = user
2533 2533 n.repository = repository
2534 2534 n.permission = permission
2535 2535 Session().add(n)
2536 2536 return n
2537 2537
2538 2538 def __unicode__(self):
2539 2539 return u'<%s => %s >' % (self.user, self.repository)
2540 2540
2541 2541
2542 2542 class UserUserGroupToPerm(Base, BaseModel):
2543 2543 __tablename__ = 'user_user_group_to_perm'
2544 2544 __table_args__ = (
2545 2545 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2546 2546 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2547 2547 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2548 2548 )
2549 2549 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2550 2550 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2551 2551 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2552 2552 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2553 2553
2554 2554 user = relationship('User')
2555 2555 user_group = relationship('UserGroup')
2556 2556 permission = relationship('Permission')
2557 2557
2558 2558 @classmethod
2559 2559 def create(cls, user, user_group, permission):
2560 2560 n = cls()
2561 2561 n.user = user
2562 2562 n.user_group = user_group
2563 2563 n.permission = permission
2564 2564 Session().add(n)
2565 2565 return n
2566 2566
2567 2567 def __unicode__(self):
2568 2568 return u'<%s => %s >' % (self.user, self.user_group)
2569 2569
2570 2570
2571 2571 class UserToPerm(Base, BaseModel):
2572 2572 __tablename__ = 'user_to_perm'
2573 2573 __table_args__ = (
2574 2574 UniqueConstraint('user_id', 'permission_id'),
2575 2575 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2576 2576 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2577 2577 )
2578 2578 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2579 2579 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2580 2580 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2581 2581
2582 2582 user = relationship('User')
2583 2583 permission = relationship('Permission', lazy='joined')
2584 2584
2585 2585 def __unicode__(self):
2586 2586 return u'<%s => %s >' % (self.user, self.permission)
2587 2587
2588 2588
2589 2589 class UserGroupRepoToPerm(Base, BaseModel):
2590 2590 __tablename__ = 'users_group_repo_to_perm'
2591 2591 __table_args__ = (
2592 2592 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2593 2593 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2594 2594 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2595 2595 )
2596 2596 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2597 2597 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2598 2598 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2599 2599 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2600 2600
2601 2601 users_group = relationship('UserGroup')
2602 2602 permission = relationship('Permission')
2603 2603 repository = relationship('Repository')
2604 2604
2605 2605 @classmethod
2606 2606 def create(cls, users_group, repository, permission):
2607 2607 n = cls()
2608 2608 n.users_group = users_group
2609 2609 n.repository = repository
2610 2610 n.permission = permission
2611 2611 Session().add(n)
2612 2612 return n
2613 2613
2614 2614 def __unicode__(self):
2615 2615 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2616 2616
2617 2617
2618 2618 class UserGroupUserGroupToPerm(Base, BaseModel):
2619 2619 __tablename__ = 'user_group_user_group_to_perm'
2620 2620 __table_args__ = (
2621 2621 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2622 2622 CheckConstraint('target_user_group_id != user_group_id'),
2623 2623 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2624 2624 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2625 2625 )
2626 2626 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)
2627 2627 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2628 2628 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2629 2629 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2630 2630
2631 2631 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2632 2632 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2633 2633 permission = relationship('Permission')
2634 2634
2635 2635 @classmethod
2636 2636 def create(cls, target_user_group, user_group, permission):
2637 2637 n = cls()
2638 2638 n.target_user_group = target_user_group
2639 2639 n.user_group = user_group
2640 2640 n.permission = permission
2641 2641 Session().add(n)
2642 2642 return n
2643 2643
2644 2644 def __unicode__(self):
2645 2645 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2646 2646
2647 2647
2648 2648 class UserGroupToPerm(Base, BaseModel):
2649 2649 __tablename__ = 'users_group_to_perm'
2650 2650 __table_args__ = (
2651 2651 UniqueConstraint('users_group_id', 'permission_id',),
2652 2652 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2653 2653 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2654 2654 )
2655 2655 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2656 2656 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2657 2657 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2658 2658
2659 2659 users_group = relationship('UserGroup')
2660 2660 permission = relationship('Permission')
2661 2661
2662 2662
2663 2663 class UserRepoGroupToPerm(Base, BaseModel):
2664 2664 __tablename__ = 'user_repo_group_to_perm'
2665 2665 __table_args__ = (
2666 2666 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2667 2667 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2668 2668 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2669 2669 )
2670 2670
2671 2671 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2672 2672 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2673 2673 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2674 2674 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2675 2675
2676 2676 user = relationship('User')
2677 2677 group = relationship('RepoGroup')
2678 2678 permission = relationship('Permission')
2679 2679
2680 2680 @classmethod
2681 2681 def create(cls, user, repository_group, permission):
2682 2682 n = cls()
2683 2683 n.user = user
2684 2684 n.group = repository_group
2685 2685 n.permission = permission
2686 2686 Session().add(n)
2687 2687 return n
2688 2688
2689 2689
2690 2690 class UserGroupRepoGroupToPerm(Base, BaseModel):
2691 2691 __tablename__ = 'users_group_repo_group_to_perm'
2692 2692 __table_args__ = (
2693 2693 UniqueConstraint('users_group_id', 'group_id'),
2694 2694 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2695 2695 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2696 2696 )
2697 2697
2698 2698 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)
2699 2699 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2700 2700 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2701 2701 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2702 2702
2703 2703 users_group = relationship('UserGroup')
2704 2704 permission = relationship('Permission')
2705 2705 group = relationship('RepoGroup')
2706 2706
2707 2707 @classmethod
2708 2708 def create(cls, user_group, repository_group, permission):
2709 2709 n = cls()
2710 2710 n.users_group = user_group
2711 2711 n.group = repository_group
2712 2712 n.permission = permission
2713 2713 Session().add(n)
2714 2714 return n
2715 2715
2716 2716 def __unicode__(self):
2717 2717 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
2718 2718
2719 2719
2720 2720 class Statistics(Base, BaseModel):
2721 2721 __tablename__ = 'statistics'
2722 2722 __table_args__ = (
2723 2723 UniqueConstraint('repository_id'),
2724 2724 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2725 2725 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2726 2726 )
2727 2727 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2728 2728 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
2729 2729 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
2730 2730 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
2731 2731 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
2732 2732 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
2733 2733
2734 2734 repository = relationship('Repository', single_parent=True)
2735 2735
2736 2736
2737 2737 class UserFollowing(Base, BaseModel):
2738 2738 __tablename__ = 'user_followings'
2739 2739 __table_args__ = (
2740 2740 UniqueConstraint('user_id', 'follows_repository_id'),
2741 2741 UniqueConstraint('user_id', 'follows_user_id'),
2742 2742 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2743 2743 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2744 2744 )
2745 2745
2746 2746 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2747 2747 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2748 2748 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
2749 2749 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
2750 2750 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2751 2751
2752 2752 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
2753 2753
2754 2754 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
2755 2755 follows_repository = relationship('Repository', order_by='Repository.repo_name')
2756 2756
2757 2757 @classmethod
2758 2758 def get_repo_followers(cls, repo_id):
2759 2759 return cls.query().filter(cls.follows_repo_id == repo_id)
2760 2760
2761 2761
2762 2762 class CacheKey(Base, BaseModel):
2763 2763 __tablename__ = 'cache_invalidation'
2764 2764 __table_args__ = (
2765 2765 UniqueConstraint('cache_key'),
2766 2766 Index('key_idx', 'cache_key'),
2767 2767 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2768 2768 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2769 2769 )
2770 2770 CACHE_TYPE_ATOM = 'ATOM'
2771 2771 CACHE_TYPE_RSS = 'RSS'
2772 2772 CACHE_TYPE_README = 'README'
2773 2773
2774 2774 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2775 2775 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
2776 2776 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
2777 2777 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
2778 2778
2779 2779 def __init__(self, cache_key, cache_args=''):
2780 2780 self.cache_key = cache_key
2781 2781 self.cache_args = cache_args
2782 2782 self.cache_active = False
2783 2783
2784 2784 def __unicode__(self):
2785 2785 return u"<%s('%s:%s[%s]')>" % (
2786 2786 self.__class__.__name__,
2787 2787 self.cache_id, self.cache_key, self.cache_active)
2788 2788
2789 2789 def _cache_key_partition(self):
2790 2790 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
2791 2791 return prefix, repo_name, suffix
2792 2792
2793 2793 def get_prefix(self):
2794 2794 """
2795 2795 Try to extract prefix from existing cache key. The key could consist
2796 2796 of prefix, repo_name, suffix
2797 2797 """
2798 2798 # this returns prefix, repo_name, suffix
2799 2799 return self._cache_key_partition()[0]
2800 2800
2801 2801 def get_suffix(self):
2802 2802 """
2803 2803 get suffix that might have been used in _get_cache_key to
2804 2804 generate self.cache_key. Only used for informational purposes
2805 2805 in repo_edit.mako.
2806 2806 """
2807 2807 # prefix, repo_name, suffix
2808 2808 return self._cache_key_partition()[2]
2809 2809
2810 2810 @classmethod
2811 2811 def delete_all_cache(cls):
2812 2812 """
2813 2813 Delete all cache keys from database.
2814 2814 Should only be run when all instances are down and all entries
2815 2815 thus stale.
2816 2816 """
2817 2817 cls.query().delete()
2818 2818 Session().commit()
2819 2819
2820 2820 @classmethod
2821 2821 def get_cache_key(cls, repo_name, cache_type):
2822 2822 """
2823 2823
2824 2824 Generate a cache key for this process of RhodeCode instance.
2825 2825 Prefix most likely will be process id or maybe explicitly set
2826 2826 instance_id from .ini file.
2827 2827 """
2828 2828 import rhodecode
2829 2829 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
2830 2830
2831 2831 repo_as_unicode = safe_unicode(repo_name)
2832 2832 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
2833 2833 if cache_type else repo_as_unicode
2834 2834
2835 2835 return u'{}{}'.format(prefix, key)
2836 2836
2837 2837 @classmethod
2838 2838 def set_invalidate(cls, repo_name, delete=False):
2839 2839 """
2840 2840 Mark all caches of a repo as invalid in the database.
2841 2841 """
2842 2842
2843 2843 try:
2844 2844 qry = Session().query(cls).filter(cls.cache_args == repo_name)
2845 2845 if delete:
2846 2846 log.debug('cache objects deleted for repo %s',
2847 2847 safe_str(repo_name))
2848 2848 qry.delete()
2849 2849 else:
2850 2850 log.debug('cache objects marked as invalid for repo %s',
2851 2851 safe_str(repo_name))
2852 2852 qry.update({"cache_active": False})
2853 2853
2854 2854 Session().commit()
2855 2855 except Exception:
2856 2856 log.exception(
2857 2857 'Cache key invalidation failed for repository %s',
2858 2858 safe_str(repo_name))
2859 2859 Session().rollback()
2860 2860
2861 2861 @classmethod
2862 2862 def get_active_cache(cls, cache_key):
2863 2863 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
2864 2864 if inv_obj:
2865 2865 return inv_obj
2866 2866 return None
2867 2867
2868 2868 @classmethod
2869 2869 def repo_context_cache(cls, compute_func, repo_name, cache_type,
2870 2870 thread_scoped=False):
2871 2871 """
2872 2872 @cache_region('long_term')
2873 2873 def _heavy_calculation(cache_key):
2874 2874 return 'result'
2875 2875
2876 2876 cache_context = CacheKey.repo_context_cache(
2877 2877 _heavy_calculation, repo_name, cache_type)
2878 2878
2879 2879 with cache_context as context:
2880 2880 context.invalidate()
2881 2881 computed = context.compute()
2882 2882
2883 2883 assert computed == 'result'
2884 2884 """
2885 2885 from rhodecode.lib import caches
2886 2886 return caches.InvalidationContext(
2887 2887 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
2888 2888
2889 2889
2890 2890 class ChangesetComment(Base, BaseModel):
2891 2891 __tablename__ = 'changeset_comments'
2892 2892 __table_args__ = (
2893 2893 Index('cc_revision_idx', 'revision'),
2894 2894 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2895 2895 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2896 2896 )
2897 2897
2898 2898 COMMENT_OUTDATED = u'comment_outdated'
2899 2899 COMMENT_TYPE_NOTE = u'note'
2900 2900 COMMENT_TYPE_TODO = u'todo'
2901 2901 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
2902 2902
2903 2903 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
2904 2904 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
2905 2905 revision = Column('revision', String(40), nullable=True)
2906 2906 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
2907 2907 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
2908 2908 line_no = Column('line_no', Unicode(10), nullable=True)
2909 2909 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
2910 2910 f_path = Column('f_path', Unicode(1000), nullable=True)
2911 2911 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
2912 2912 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
2913 2913 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2914 2914 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2915 2915 renderer = Column('renderer', Unicode(64), nullable=True)
2916 2916 display_state = Column('display_state', Unicode(128), nullable=True)
2917 2917
2918 2918 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
2919 2919 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
2920 2920 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
2921 2921 author = relationship('User', lazy='joined')
2922 2922 repo = relationship('Repository')
2923 2923 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
2924 2924 pull_request = relationship('PullRequest', lazy='joined')
2925 2925 pull_request_version = relationship('PullRequestVersion')
2926 2926
2927 2927 @classmethod
2928 2928 def get_users(cls, revision=None, pull_request_id=None):
2929 2929 """
2930 2930 Returns user associated with this ChangesetComment. ie those
2931 2931 who actually commented
2932 2932
2933 2933 :param cls:
2934 2934 :param revision:
2935 2935 """
2936 2936 q = Session().query(User)\
2937 2937 .join(ChangesetComment.author)
2938 2938 if revision:
2939 2939 q = q.filter(cls.revision == revision)
2940 2940 elif pull_request_id:
2941 2941 q = q.filter(cls.pull_request_id == pull_request_id)
2942 2942 return q.all()
2943 2943
2944 2944 @classmethod
2945 2945 def get_index_from_version(cls, pr_version, versions):
2946 2946 num_versions = [x.pull_request_version_id for x in versions]
2947 2947 try:
2948 2948 return num_versions.index(pr_version) +1
2949 2949 except (IndexError, ValueError):
2950 2950 return
2951 2951
2952 2952 @property
2953 2953 def outdated(self):
2954 2954 return self.display_state == self.COMMENT_OUTDATED
2955 2955
2956 2956 def outdated_at_version(self, version):
2957 2957 """
2958 2958 Checks if comment is outdated for given pull request version
2959 2959 """
2960 2960 return self.outdated and self.pull_request_version_id != version
2961 2961
2962 def older_than_version(self, version):
2963 """
2964 Checks if comment is made from previous version than given
2965 """
2966 if version is None:
2967 return self.pull_request_version_id is not None
2968
2969 return self.pull_request_version_id < version
2970
2962 2971 @property
2963 2972 def resolved(self):
2964 2973 return self.resolved_by[0] if self.resolved_by else None
2965 2974
2966 2975 def get_index_version(self, versions):
2967 2976 return self.get_index_from_version(
2968 2977 self.pull_request_version_id, versions)
2969 2978
2970 2979 def render(self, mentions=False):
2971 2980 from rhodecode.lib import helpers as h
2972 2981 return h.render(self.text, renderer=self.renderer, mentions=mentions)
2973 2982
2974 2983 def __repr__(self):
2975 2984 if self.comment_id:
2976 return '<DB:ChangesetComment #%s>' % self.comment_id
2985 return '<DB:Comment #%s>' % self.comment_id
2977 2986 else:
2978 return '<DB:ChangesetComment at %#x>' % id(self)
2987 return '<DB:Comment at %#x>' % id(self)
2979 2988
2980 2989
2981 2990 class ChangesetStatus(Base, BaseModel):
2982 2991 __tablename__ = 'changeset_statuses'
2983 2992 __table_args__ = (
2984 2993 Index('cs_revision_idx', 'revision'),
2985 2994 Index('cs_version_idx', 'version'),
2986 2995 UniqueConstraint('repo_id', 'revision', 'version'),
2987 2996 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2988 2997 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2989 2998 )
2990 2999 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
2991 3000 STATUS_APPROVED = 'approved'
2992 3001 STATUS_REJECTED = 'rejected'
2993 3002 STATUS_UNDER_REVIEW = 'under_review'
2994 3003
2995 3004 STATUSES = [
2996 3005 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
2997 3006 (STATUS_APPROVED, _("Approved")),
2998 3007 (STATUS_REJECTED, _("Rejected")),
2999 3008 (STATUS_UNDER_REVIEW, _("Under Review")),
3000 3009 ]
3001 3010
3002 3011 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3003 3012 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3004 3013 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3005 3014 revision = Column('revision', String(40), nullable=False)
3006 3015 status = Column('status', String(128), nullable=False, default=DEFAULT)
3007 3016 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3008 3017 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3009 3018 version = Column('version', Integer(), nullable=False, default=0)
3010 3019 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3011 3020
3012 3021 author = relationship('User', lazy='joined')
3013 3022 repo = relationship('Repository')
3014 3023 comment = relationship('ChangesetComment', lazy='joined')
3015 3024 pull_request = relationship('PullRequest', lazy='joined')
3016 3025
3017 3026 def __unicode__(self):
3018 3027 return u"<%s('%s[%s]:%s')>" % (
3019 3028 self.__class__.__name__,
3020 3029 self.status, self.version, self.author
3021 3030 )
3022 3031
3023 3032 @classmethod
3024 3033 def get_status_lbl(cls, value):
3025 3034 return dict(cls.STATUSES).get(value)
3026 3035
3027 3036 @property
3028 3037 def status_lbl(self):
3029 3038 return ChangesetStatus.get_status_lbl(self.status)
3030 3039
3031 3040
3032 3041 class _PullRequestBase(BaseModel):
3033 3042 """
3034 3043 Common attributes of pull request and version entries.
3035 3044 """
3036 3045
3037 3046 # .status values
3038 3047 STATUS_NEW = u'new'
3039 3048 STATUS_OPEN = u'open'
3040 3049 STATUS_CLOSED = u'closed'
3041 3050
3042 3051 title = Column('title', Unicode(255), nullable=True)
3043 3052 description = Column(
3044 3053 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3045 3054 nullable=True)
3046 3055 # new/open/closed status of pull request (not approve/reject/etc)
3047 3056 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3048 3057 created_on = Column(
3049 3058 'created_on', DateTime(timezone=False), nullable=False,
3050 3059 default=datetime.datetime.now)
3051 3060 updated_on = Column(
3052 3061 'updated_on', DateTime(timezone=False), nullable=False,
3053 3062 default=datetime.datetime.now)
3054 3063
3055 3064 @declared_attr
3056 3065 def user_id(cls):
3057 3066 return Column(
3058 3067 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3059 3068 unique=None)
3060 3069
3061 3070 # 500 revisions max
3062 3071 _revisions = Column(
3063 3072 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3064 3073
3065 3074 @declared_attr
3066 3075 def source_repo_id(cls):
3067 3076 # TODO: dan: rename column to source_repo_id
3068 3077 return Column(
3069 3078 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3070 3079 nullable=False)
3071 3080
3072 3081 source_ref = Column('org_ref', Unicode(255), nullable=False)
3073 3082
3074 3083 @declared_attr
3075 3084 def target_repo_id(cls):
3076 3085 # TODO: dan: rename column to target_repo_id
3077 3086 return Column(
3078 3087 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3079 3088 nullable=False)
3080 3089
3081 3090 target_ref = Column('other_ref', Unicode(255), nullable=False)
3082 3091 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3083 3092
3084 3093 # TODO: dan: rename column to last_merge_source_rev
3085 3094 _last_merge_source_rev = Column(
3086 3095 'last_merge_org_rev', String(40), nullable=True)
3087 3096 # TODO: dan: rename column to last_merge_target_rev
3088 3097 _last_merge_target_rev = Column(
3089 3098 'last_merge_other_rev', String(40), nullable=True)
3090 3099 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3091 3100 merge_rev = Column('merge_rev', String(40), nullable=True)
3092 3101
3093 3102 @hybrid_property
3094 3103 def revisions(self):
3095 3104 return self._revisions.split(':') if self._revisions else []
3096 3105
3097 3106 @revisions.setter
3098 3107 def revisions(self, val):
3099 3108 self._revisions = ':'.join(val)
3100 3109
3101 3110 @declared_attr
3102 3111 def author(cls):
3103 3112 return relationship('User', lazy='joined')
3104 3113
3105 3114 @declared_attr
3106 3115 def source_repo(cls):
3107 3116 return relationship(
3108 3117 'Repository',
3109 3118 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3110 3119
3111 3120 @property
3112 3121 def source_ref_parts(self):
3113 3122 return self.unicode_to_reference(self.source_ref)
3114 3123
3115 3124 @declared_attr
3116 3125 def target_repo(cls):
3117 3126 return relationship(
3118 3127 'Repository',
3119 3128 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3120 3129
3121 3130 @property
3122 3131 def target_ref_parts(self):
3123 3132 return self.unicode_to_reference(self.target_ref)
3124 3133
3125 3134 @property
3126 3135 def shadow_merge_ref(self):
3127 3136 return self.unicode_to_reference(self._shadow_merge_ref)
3128 3137
3129 3138 @shadow_merge_ref.setter
3130 3139 def shadow_merge_ref(self, ref):
3131 3140 self._shadow_merge_ref = self.reference_to_unicode(ref)
3132 3141
3133 3142 def unicode_to_reference(self, raw):
3134 3143 """
3135 3144 Convert a unicode (or string) to a reference object.
3136 3145 If unicode evaluates to False it returns None.
3137 3146 """
3138 3147 if raw:
3139 3148 refs = raw.split(':')
3140 3149 return Reference(*refs)
3141 3150 else:
3142 3151 return None
3143 3152
3144 3153 def reference_to_unicode(self, ref):
3145 3154 """
3146 3155 Convert a reference object to unicode.
3147 3156 If reference is None it returns None.
3148 3157 """
3149 3158 if ref:
3150 3159 return u':'.join(ref)
3151 3160 else:
3152 3161 return None
3153 3162
3154 3163 def get_api_data(self):
3155 3164 from rhodecode.model.pull_request import PullRequestModel
3156 3165 pull_request = self
3157 3166 merge_status = PullRequestModel().merge_status(pull_request)
3158 3167
3159 3168 pull_request_url = url(
3160 3169 'pullrequest_show', repo_name=self.target_repo.repo_name,
3161 3170 pull_request_id=self.pull_request_id, qualified=True)
3162 3171
3163 3172 merge_data = {
3164 3173 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3165 3174 'reference': (
3166 3175 pull_request.shadow_merge_ref._asdict()
3167 3176 if pull_request.shadow_merge_ref else None),
3168 3177 }
3169 3178
3170 3179 data = {
3171 3180 'pull_request_id': pull_request.pull_request_id,
3172 3181 'url': pull_request_url,
3173 3182 'title': pull_request.title,
3174 3183 'description': pull_request.description,
3175 3184 'status': pull_request.status,
3176 3185 'created_on': pull_request.created_on,
3177 3186 'updated_on': pull_request.updated_on,
3178 3187 'commit_ids': pull_request.revisions,
3179 3188 'review_status': pull_request.calculated_review_status(),
3180 3189 'mergeable': {
3181 3190 'status': merge_status[0],
3182 3191 'message': unicode(merge_status[1]),
3183 3192 },
3184 3193 'source': {
3185 3194 'clone_url': pull_request.source_repo.clone_url(),
3186 3195 'repository': pull_request.source_repo.repo_name,
3187 3196 'reference': {
3188 3197 'name': pull_request.source_ref_parts.name,
3189 3198 'type': pull_request.source_ref_parts.type,
3190 3199 'commit_id': pull_request.source_ref_parts.commit_id,
3191 3200 },
3192 3201 },
3193 3202 'target': {
3194 3203 'clone_url': pull_request.target_repo.clone_url(),
3195 3204 'repository': pull_request.target_repo.repo_name,
3196 3205 'reference': {
3197 3206 'name': pull_request.target_ref_parts.name,
3198 3207 'type': pull_request.target_ref_parts.type,
3199 3208 'commit_id': pull_request.target_ref_parts.commit_id,
3200 3209 },
3201 3210 },
3202 3211 'merge': merge_data,
3203 3212 'author': pull_request.author.get_api_data(include_secrets=False,
3204 3213 details='basic'),
3205 3214 'reviewers': [
3206 3215 {
3207 3216 'user': reviewer.get_api_data(include_secrets=False,
3208 3217 details='basic'),
3209 3218 'reasons': reasons,
3210 3219 'review_status': st[0][1].status if st else 'not_reviewed',
3211 3220 }
3212 3221 for reviewer, reasons, st in pull_request.reviewers_statuses()
3213 3222 ]
3214 3223 }
3215 3224
3216 3225 return data
3217 3226
3218 3227
3219 3228 class PullRequest(Base, _PullRequestBase):
3220 3229 __tablename__ = 'pull_requests'
3221 3230 __table_args__ = (
3222 3231 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3223 3232 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3224 3233 )
3225 3234
3226 3235 pull_request_id = Column(
3227 3236 'pull_request_id', Integer(), nullable=False, primary_key=True)
3228 3237
3229 3238 def __repr__(self):
3230 3239 if self.pull_request_id:
3231 3240 return '<DB:PullRequest #%s>' % self.pull_request_id
3232 3241 else:
3233 3242 return '<DB:PullRequest at %#x>' % id(self)
3234 3243
3235 3244 reviewers = relationship('PullRequestReviewers',
3236 3245 cascade="all, delete, delete-orphan")
3237 3246 statuses = relationship('ChangesetStatus')
3238 3247 comments = relationship('ChangesetComment',
3239 3248 cascade="all, delete, delete-orphan")
3240 3249 versions = relationship('PullRequestVersion',
3241 3250 cascade="all, delete, delete-orphan",
3242 3251 lazy='dynamic')
3243 3252
3244 3253
3245 3254 @classmethod
3246 3255 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3247 3256 internal_methods=None):
3248 3257
3249 3258 class PullRequestDisplay(object):
3250 3259 """
3251 3260 Special object wrapper for showing PullRequest data via Versions
3252 3261 It mimics PR object as close as possible. This is read only object
3253 3262 just for display
3254 3263 """
3255 3264
3256 3265 def __init__(self, attrs, internal=None):
3257 3266 self.attrs = attrs
3258 3267 # internal have priority over the given ones via attrs
3259 3268 self.internal = internal or ['versions']
3260 3269
3261 3270 def __getattr__(self, item):
3262 3271 if item in self.internal:
3263 3272 return getattr(self, item)
3264 3273 try:
3265 3274 return self.attrs[item]
3266 3275 except KeyError:
3267 3276 raise AttributeError(
3268 3277 '%s object has no attribute %s' % (self, item))
3269 3278
3270 3279 def __repr__(self):
3271 3280 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3272 3281
3273 3282 def versions(self):
3274 3283 return pull_request_obj.versions.order_by(
3275 3284 PullRequestVersion.pull_request_version_id).all()
3276 3285
3277 3286 def is_closed(self):
3278 3287 return pull_request_obj.is_closed()
3279 3288
3280 3289 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3281 3290
3282 3291 attrs.author = StrictAttributeDict(
3283 3292 pull_request_obj.author.get_api_data())
3284 3293 if pull_request_obj.target_repo:
3285 3294 attrs.target_repo = StrictAttributeDict(
3286 3295 pull_request_obj.target_repo.get_api_data())
3287 3296 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3288 3297
3289 3298 if pull_request_obj.source_repo:
3290 3299 attrs.source_repo = StrictAttributeDict(
3291 3300 pull_request_obj.source_repo.get_api_data())
3292 3301 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3293 3302
3294 3303 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3295 3304 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3296 3305 attrs.revisions = pull_request_obj.revisions
3297 3306
3298 3307 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3299 3308
3300 3309 return PullRequestDisplay(attrs, internal=internal_methods)
3301 3310
3302 3311 def is_closed(self):
3303 3312 return self.status == self.STATUS_CLOSED
3304 3313
3305 3314 def __json__(self):
3306 3315 return {
3307 3316 'revisions': self.revisions,
3308 3317 }
3309 3318
3310 3319 def calculated_review_status(self):
3311 3320 from rhodecode.model.changeset_status import ChangesetStatusModel
3312 3321 return ChangesetStatusModel().calculated_review_status(self)
3313 3322
3314 3323 def reviewers_statuses(self):
3315 3324 from rhodecode.model.changeset_status import ChangesetStatusModel
3316 3325 return ChangesetStatusModel().reviewers_statuses(self)
3317 3326
3318 3327
3319 3328 class PullRequestVersion(Base, _PullRequestBase):
3320 3329 __tablename__ = 'pull_request_versions'
3321 3330 __table_args__ = (
3322 3331 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3323 3332 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3324 3333 )
3325 3334
3326 3335 pull_request_version_id = Column(
3327 3336 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3328 3337 pull_request_id = Column(
3329 3338 'pull_request_id', Integer(),
3330 3339 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3331 3340 pull_request = relationship('PullRequest')
3332 3341
3333 3342 def __repr__(self):
3334 3343 if self.pull_request_version_id:
3335 3344 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3336 3345 else:
3337 3346 return '<DB:PullRequestVersion at %#x>' % id(self)
3338 3347
3339 3348 @property
3340 3349 def reviewers(self):
3341 3350 return self.pull_request.reviewers
3342 3351
3343 3352 @property
3344 3353 def versions(self):
3345 3354 return self.pull_request.versions
3346 3355
3347 3356 def is_closed(self):
3348 3357 # calculate from original
3349 3358 return self.pull_request.status == self.STATUS_CLOSED
3350 3359
3351 3360 def calculated_review_status(self):
3352 3361 return self.pull_request.calculated_review_status()
3353 3362
3354 3363 def reviewers_statuses(self):
3355 3364 return self.pull_request.reviewers_statuses()
3356 3365
3357 3366
3358 3367 class PullRequestReviewers(Base, BaseModel):
3359 3368 __tablename__ = 'pull_request_reviewers'
3360 3369 __table_args__ = (
3361 3370 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3362 3371 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3363 3372 )
3364 3373
3365 3374 def __init__(self, user=None, pull_request=None, reasons=None):
3366 3375 self.user = user
3367 3376 self.pull_request = pull_request
3368 3377 self.reasons = reasons or []
3369 3378
3370 3379 @hybrid_property
3371 3380 def reasons(self):
3372 3381 if not self._reasons:
3373 3382 return []
3374 3383 return self._reasons
3375 3384
3376 3385 @reasons.setter
3377 3386 def reasons(self, val):
3378 3387 val = val or []
3379 3388 if any(not isinstance(x, basestring) for x in val):
3380 3389 raise Exception('invalid reasons type, must be list of strings')
3381 3390 self._reasons = val
3382 3391
3383 3392 pull_requests_reviewers_id = Column(
3384 3393 'pull_requests_reviewers_id', Integer(), nullable=False,
3385 3394 primary_key=True)
3386 3395 pull_request_id = Column(
3387 3396 "pull_request_id", Integer(),
3388 3397 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3389 3398 user_id = Column(
3390 3399 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3391 3400 _reasons = Column(
3392 3401 'reason', MutationList.as_mutable(
3393 3402 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3394 3403
3395 3404 user = relationship('User')
3396 3405 pull_request = relationship('PullRequest')
3397 3406
3398 3407
3399 3408 class Notification(Base, BaseModel):
3400 3409 __tablename__ = 'notifications'
3401 3410 __table_args__ = (
3402 3411 Index('notification_type_idx', 'type'),
3403 3412 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3404 3413 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3405 3414 )
3406 3415
3407 3416 TYPE_CHANGESET_COMMENT = u'cs_comment'
3408 3417 TYPE_MESSAGE = u'message'
3409 3418 TYPE_MENTION = u'mention'
3410 3419 TYPE_REGISTRATION = u'registration'
3411 3420 TYPE_PULL_REQUEST = u'pull_request'
3412 3421 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3413 3422
3414 3423 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3415 3424 subject = Column('subject', Unicode(512), nullable=True)
3416 3425 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3417 3426 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3418 3427 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3419 3428 type_ = Column('type', Unicode(255))
3420 3429
3421 3430 created_by_user = relationship('User')
3422 3431 notifications_to_users = relationship('UserNotification', lazy='joined',
3423 3432 cascade="all, delete, delete-orphan")
3424 3433
3425 3434 @property
3426 3435 def recipients(self):
3427 3436 return [x.user for x in UserNotification.query()\
3428 3437 .filter(UserNotification.notification == self)\
3429 3438 .order_by(UserNotification.user_id.asc()).all()]
3430 3439
3431 3440 @classmethod
3432 3441 def create(cls, created_by, subject, body, recipients, type_=None):
3433 3442 if type_ is None:
3434 3443 type_ = Notification.TYPE_MESSAGE
3435 3444
3436 3445 notification = cls()
3437 3446 notification.created_by_user = created_by
3438 3447 notification.subject = subject
3439 3448 notification.body = body
3440 3449 notification.type_ = type_
3441 3450 notification.created_on = datetime.datetime.now()
3442 3451
3443 3452 for u in recipients:
3444 3453 assoc = UserNotification()
3445 3454 assoc.notification = notification
3446 3455
3447 3456 # if created_by is inside recipients mark his notification
3448 3457 # as read
3449 3458 if u.user_id == created_by.user_id:
3450 3459 assoc.read = True
3451 3460
3452 3461 u.notifications.append(assoc)
3453 3462 Session().add(notification)
3454 3463
3455 3464 return notification
3456 3465
3457 3466 @property
3458 3467 def description(self):
3459 3468 from rhodecode.model.notification import NotificationModel
3460 3469 return NotificationModel().make_description(self)
3461 3470
3462 3471
3463 3472 class UserNotification(Base, BaseModel):
3464 3473 __tablename__ = 'user_to_notification'
3465 3474 __table_args__ = (
3466 3475 UniqueConstraint('user_id', 'notification_id'),
3467 3476 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3468 3477 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3469 3478 )
3470 3479 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3471 3480 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3472 3481 read = Column('read', Boolean, default=False)
3473 3482 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3474 3483
3475 3484 user = relationship('User', lazy="joined")
3476 3485 notification = relationship('Notification', lazy="joined",
3477 3486 order_by=lambda: Notification.created_on.desc(),)
3478 3487
3479 3488 def mark_as_read(self):
3480 3489 self.read = True
3481 3490 Session().add(self)
3482 3491
3483 3492
3484 3493 class Gist(Base, BaseModel):
3485 3494 __tablename__ = 'gists'
3486 3495 __table_args__ = (
3487 3496 Index('g_gist_access_id_idx', 'gist_access_id'),
3488 3497 Index('g_created_on_idx', 'created_on'),
3489 3498 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3490 3499 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3491 3500 )
3492 3501 GIST_PUBLIC = u'public'
3493 3502 GIST_PRIVATE = u'private'
3494 3503 DEFAULT_FILENAME = u'gistfile1.txt'
3495 3504
3496 3505 ACL_LEVEL_PUBLIC = u'acl_public'
3497 3506 ACL_LEVEL_PRIVATE = u'acl_private'
3498 3507
3499 3508 gist_id = Column('gist_id', Integer(), primary_key=True)
3500 3509 gist_access_id = Column('gist_access_id', Unicode(250))
3501 3510 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3502 3511 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3503 3512 gist_expires = Column('gist_expires', Float(53), nullable=False)
3504 3513 gist_type = Column('gist_type', Unicode(128), nullable=False)
3505 3514 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3506 3515 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3507 3516 acl_level = Column('acl_level', Unicode(128), nullable=True)
3508 3517
3509 3518 owner = relationship('User')
3510 3519
3511 3520 def __repr__(self):
3512 3521 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3513 3522
3514 3523 @classmethod
3515 3524 def get_or_404(cls, id_):
3516 3525 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3517 3526 if not res:
3518 3527 raise HTTPNotFound
3519 3528 return res
3520 3529
3521 3530 @classmethod
3522 3531 def get_by_access_id(cls, gist_access_id):
3523 3532 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3524 3533
3525 3534 def gist_url(self):
3526 3535 import rhodecode
3527 3536 alias_url = rhodecode.CONFIG.get('gist_alias_url')
3528 3537 if alias_url:
3529 3538 return alias_url.replace('{gistid}', self.gist_access_id)
3530 3539
3531 3540 return url('gist', gist_id=self.gist_access_id, qualified=True)
3532 3541
3533 3542 @classmethod
3534 3543 def base_path(cls):
3535 3544 """
3536 3545 Returns base path when all gists are stored
3537 3546
3538 3547 :param cls:
3539 3548 """
3540 3549 from rhodecode.model.gist import GIST_STORE_LOC
3541 3550 q = Session().query(RhodeCodeUi)\
3542 3551 .filter(RhodeCodeUi.ui_key == URL_SEP)
3543 3552 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3544 3553 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3545 3554
3546 3555 def get_api_data(self):
3547 3556 """
3548 3557 Common function for generating gist related data for API
3549 3558 """
3550 3559 gist = self
3551 3560 data = {
3552 3561 'gist_id': gist.gist_id,
3553 3562 'type': gist.gist_type,
3554 3563 'access_id': gist.gist_access_id,
3555 3564 'description': gist.gist_description,
3556 3565 'url': gist.gist_url(),
3557 3566 'expires': gist.gist_expires,
3558 3567 'created_on': gist.created_on,
3559 3568 'modified_at': gist.modified_at,
3560 3569 'content': None,
3561 3570 'acl_level': gist.acl_level,
3562 3571 }
3563 3572 return data
3564 3573
3565 3574 def __json__(self):
3566 3575 data = dict(
3567 3576 )
3568 3577 data.update(self.get_api_data())
3569 3578 return data
3570 3579 # SCM functions
3571 3580
3572 3581 def scm_instance(self, **kwargs):
3573 3582 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3574 3583 return get_vcs_instance(
3575 3584 repo_path=safe_str(full_repo_path), create=False)
3576 3585
3577 3586
3578 3587 class ExternalIdentity(Base, BaseModel):
3579 3588 __tablename__ = 'external_identities'
3580 3589 __table_args__ = (
3581 3590 Index('local_user_id_idx', 'local_user_id'),
3582 3591 Index('external_id_idx', 'external_id'),
3583 3592 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3584 3593 'mysql_charset': 'utf8'})
3585 3594
3586 3595 external_id = Column('external_id', Unicode(255), default=u'',
3587 3596 primary_key=True)
3588 3597 external_username = Column('external_username', Unicode(1024), default=u'')
3589 3598 local_user_id = Column('local_user_id', Integer(),
3590 3599 ForeignKey('users.user_id'), primary_key=True)
3591 3600 provider_name = Column('provider_name', Unicode(255), default=u'',
3592 3601 primary_key=True)
3593 3602 access_token = Column('access_token', String(1024), default=u'')
3594 3603 alt_token = Column('alt_token', String(1024), default=u'')
3595 3604 token_secret = Column('token_secret', String(1024), default=u'')
3596 3605
3597 3606 @classmethod
3598 3607 def by_external_id_and_provider(cls, external_id, provider_name,
3599 3608 local_user_id=None):
3600 3609 """
3601 3610 Returns ExternalIdentity instance based on search params
3602 3611
3603 3612 :param external_id:
3604 3613 :param provider_name:
3605 3614 :return: ExternalIdentity
3606 3615 """
3607 3616 query = cls.query()
3608 3617 query = query.filter(cls.external_id == external_id)
3609 3618 query = query.filter(cls.provider_name == provider_name)
3610 3619 if local_user_id:
3611 3620 query = query.filter(cls.local_user_id == local_user_id)
3612 3621 return query.first()
3613 3622
3614 3623 @classmethod
3615 3624 def user_by_external_id_and_provider(cls, external_id, provider_name):
3616 3625 """
3617 3626 Returns User instance based on search params
3618 3627
3619 3628 :param external_id:
3620 3629 :param provider_name:
3621 3630 :return: User
3622 3631 """
3623 3632 query = User.query()
3624 3633 query = query.filter(cls.external_id == external_id)
3625 3634 query = query.filter(cls.provider_name == provider_name)
3626 3635 query = query.filter(User.user_id == cls.local_user_id)
3627 3636 return query.first()
3628 3637
3629 3638 @classmethod
3630 3639 def by_local_user_id(cls, local_user_id):
3631 3640 """
3632 3641 Returns all tokens for user
3633 3642
3634 3643 :param local_user_id:
3635 3644 :return: ExternalIdentity
3636 3645 """
3637 3646 query = cls.query()
3638 3647 query = query.filter(cls.local_user_id == local_user_id)
3639 3648 return query
3640 3649
3641 3650
3642 3651 class Integration(Base, BaseModel):
3643 3652 __tablename__ = 'integrations'
3644 3653 __table_args__ = (
3645 3654 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3646 3655 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3647 3656 )
3648 3657
3649 3658 integration_id = Column('integration_id', Integer(), primary_key=True)
3650 3659 integration_type = Column('integration_type', String(255))
3651 3660 enabled = Column('enabled', Boolean(), nullable=False)
3652 3661 name = Column('name', String(255), nullable=False)
3653 3662 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
3654 3663 default=False)
3655 3664
3656 3665 settings = Column(
3657 3666 'settings_json', MutationObj.as_mutable(
3658 3667 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3659 3668 repo_id = Column(
3660 3669 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
3661 3670 nullable=True, unique=None, default=None)
3662 3671 repo = relationship('Repository', lazy='joined')
3663 3672
3664 3673 repo_group_id = Column(
3665 3674 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
3666 3675 nullable=True, unique=None, default=None)
3667 3676 repo_group = relationship('RepoGroup', lazy='joined')
3668 3677
3669 3678 @property
3670 3679 def scope(self):
3671 3680 if self.repo:
3672 3681 return repr(self.repo)
3673 3682 if self.repo_group:
3674 3683 if self.child_repos_only:
3675 3684 return repr(self.repo_group) + ' (child repos only)'
3676 3685 else:
3677 3686 return repr(self.repo_group) + ' (recursive)'
3678 3687 if self.child_repos_only:
3679 3688 return 'root_repos'
3680 3689 return 'global'
3681 3690
3682 3691 def __repr__(self):
3683 3692 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
3684 3693
3685 3694
3686 3695 class RepoReviewRuleUser(Base, BaseModel):
3687 3696 __tablename__ = 'repo_review_rules_users'
3688 3697 __table_args__ = (
3689 3698 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3690 3699 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3691 3700 )
3692 3701 repo_review_rule_user_id = Column(
3693 3702 'repo_review_rule_user_id', Integer(), primary_key=True)
3694 3703 repo_review_rule_id = Column("repo_review_rule_id",
3695 3704 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3696 3705 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'),
3697 3706 nullable=False)
3698 3707 user = relationship('User')
3699 3708
3700 3709
3701 3710 class RepoReviewRuleUserGroup(Base, BaseModel):
3702 3711 __tablename__ = 'repo_review_rules_users_groups'
3703 3712 __table_args__ = (
3704 3713 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3705 3714 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3706 3715 )
3707 3716 repo_review_rule_users_group_id = Column(
3708 3717 'repo_review_rule_users_group_id', Integer(), primary_key=True)
3709 3718 repo_review_rule_id = Column("repo_review_rule_id",
3710 3719 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3711 3720 users_group_id = Column("users_group_id", Integer(),
3712 3721 ForeignKey('users_groups.users_group_id'), nullable=False)
3713 3722 users_group = relationship('UserGroup')
3714 3723
3715 3724
3716 3725 class RepoReviewRule(Base, BaseModel):
3717 3726 __tablename__ = 'repo_review_rules'
3718 3727 __table_args__ = (
3719 3728 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3720 3729 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3721 3730 )
3722 3731
3723 3732 repo_review_rule_id = Column(
3724 3733 'repo_review_rule_id', Integer(), primary_key=True)
3725 3734 repo_id = Column(
3726 3735 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
3727 3736 repo = relationship('Repository', backref='review_rules')
3728 3737
3729 3738 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3730 3739 default=u'*') # glob
3731 3740 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3732 3741 default=u'*') # glob
3733 3742
3734 3743 use_authors_for_review = Column("use_authors_for_review", Boolean(),
3735 3744 nullable=False, default=False)
3736 3745 rule_users = relationship('RepoReviewRuleUser')
3737 3746 rule_user_groups = relationship('RepoReviewRuleUserGroup')
3738 3747
3739 3748 @hybrid_property
3740 3749 def branch_pattern(self):
3741 3750 return self._branch_pattern or '*'
3742 3751
3743 3752 def _validate_glob(self, value):
3744 3753 re.compile('^' + glob2re(value) + '$')
3745 3754
3746 3755 @branch_pattern.setter
3747 3756 def branch_pattern(self, value):
3748 3757 self._validate_glob(value)
3749 3758 self._branch_pattern = value or '*'
3750 3759
3751 3760 @hybrid_property
3752 3761 def file_pattern(self):
3753 3762 return self._file_pattern or '*'
3754 3763
3755 3764 @file_pattern.setter
3756 3765 def file_pattern(self, value):
3757 3766 self._validate_glob(value)
3758 3767 self._file_pattern = value or '*'
3759 3768
3760 3769 def matches(self, branch, files_changed):
3761 3770 """
3762 3771 Check if this review rule matches a branch/files in a pull request
3763 3772
3764 3773 :param branch: branch name for the commit
3765 3774 :param files_changed: list of file paths changed in the pull request
3766 3775 """
3767 3776
3768 3777 branch = branch or ''
3769 3778 files_changed = files_changed or []
3770 3779
3771 3780 branch_matches = True
3772 3781 if branch:
3773 3782 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
3774 3783 branch_matches = bool(branch_regex.search(branch))
3775 3784
3776 3785 files_matches = True
3777 3786 if self.file_pattern != '*':
3778 3787 files_matches = False
3779 3788 file_regex = re.compile(glob2re(self.file_pattern))
3780 3789 for filename in files_changed:
3781 3790 if file_regex.search(filename):
3782 3791 files_matches = True
3783 3792 break
3784 3793
3785 3794 return branch_matches and files_matches
3786 3795
3787 3796 @property
3788 3797 def review_users(self):
3789 3798 """ Returns the users which this rule applies to """
3790 3799
3791 3800 users = set()
3792 3801 users |= set([
3793 3802 rule_user.user for rule_user in self.rule_users
3794 3803 if rule_user.user.active])
3795 3804 users |= set(
3796 3805 member.user
3797 3806 for rule_user_group in self.rule_user_groups
3798 3807 for member in rule_user_group.users_group.members
3799 3808 if member.user.active
3800 3809 )
3801 3810 return users
3802 3811
3803 3812 def __repr__(self):
3804 3813 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
3805 3814 self.repo_review_rule_id, self.repo)
3806 3815
3807 3816
3808 3817 class DbMigrateVersion(Base, BaseModel):
3809 3818 __tablename__ = 'db_migrate_version'
3810 3819 __table_args__ = (
3811 3820 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3812 3821 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3813 3822 )
3814 3823 repository_id = Column('repository_id', String(250), primary_key=True)
3815 3824 repository_path = Column('repository_path', Text)
3816 3825 version = Column('version', Integer)
3817 3826
3818 3827
3819 3828 class DbSession(Base, BaseModel):
3820 3829 __tablename__ = 'db_session'
3821 3830 __table_args__ = (
3822 3831 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3823 3832 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3824 3833 )
3825 3834
3826 3835 def __repr__(self):
3827 3836 return '<DB:DbSession({})>'.format(self.id)
3828 3837
3829 3838 id = Column('id', Integer())
3830 3839 namespace = Column('namespace', String(255), primary_key=True)
3831 3840 accessed = Column('accessed', DateTime, nullable=False)
3832 3841 created = Column('created', DateTime, nullable=False)
3833 3842 data = Column('data', PickleType, nullable=False)
@@ -1,547 +1,547 b''
1 1 // comments.less
2 2 // For use in RhodeCode applications;
3 3 // see style guide documentation for guidelines.
4 4
5 5
6 6 // Comments
7 7 .comments {
8 8 width: 100%;
9 9 }
10 10
11 11 tr.inline-comments div {
12 12 max-width: 100%;
13 13
14 14 p {
15 15 white-space: normal;
16 16 }
17 17
18 18 code, pre, .code, dd {
19 19 overflow-x: auto;
20 20 width: 1062px;
21 21 }
22 22
23 23 dd {
24 24 width: auto;
25 25 }
26 26 }
27 27
28 28 #injected_page_comments {
29 29 .comment-previous-link,
30 30 .comment-next-link,
31 31 .comment-links-divider {
32 32 display: none;
33 33 }
34 34 }
35 35
36 36 .add-comment {
37 37 margin-bottom: 10px;
38 38 }
39 39 .hide-comment-button .add-comment {
40 40 display: none;
41 41 }
42 42
43 43 .comment-bubble {
44 44 color: @grey4;
45 45 margin-top: 4px;
46 46 margin-right: 30px;
47 47 visibility: hidden;
48 48 }
49 49
50 50 .comment-label {
51 51 float: left;
52 52
53 53 padding: 0.4em 0.4em;
54 margin: 2px 5px 0px -10px;
54 margin: 3px 5px 0px -10px;
55 55 display: inline-block;
56 56 min-height: 0;
57 57
58 58 text-align: center;
59 59 font-size: 10px;
60 60 line-height: .8em;
61 61
62 62 font-family: @text-italic;
63 63 background: #fff none;
64 64 color: @grey4;
65 65 border: 1px solid @grey4;
66 66 white-space: nowrap;
67 67
68 68 text-transform: uppercase;
69 69 min-width: 40px;
70 70
71 71 &.todo {
72 72 color: @color5;
73 73 font-family: @text-bold-italic;
74 74 }
75 75
76 76 .resolve {
77 77 cursor: pointer;
78 78 text-decoration: underline;
79 79 }
80 80
81 81 .resolved {
82 82 text-decoration: line-through;
83 83 color: @color1;
84 84 }
85 85 .resolved a {
86 86 text-decoration: line-through;
87 87 color: @color1;
88 88 }
89 89 .resolve-text {
90 90 color: @color1;
91 91 margin: 2px 8px;
92 92 font-family: @text-italic;
93 93 }
94 94
95 95 }
96 96
97 97
98 98 .comment {
99 99
100 100 &.comment-general {
101 101 border: 1px solid @grey5;
102 102 padding: 5px 5px 5px 5px;
103 103 }
104 104
105 105 margin: @padding 0;
106 106 padding: 4px 0 0 0;
107 107 line-height: 1em;
108 108
109 109 .rc-user {
110 110 min-width: 0;
111 111 margin: 0px .5em 0 0;
112 112
113 113 .user {
114 114 display: inline;
115 115 }
116 116 }
117 117
118 118 .meta {
119 119 position: relative;
120 120 width: 100%;
121 121 border-bottom: 1px solid @grey5;
122 122 margin: -5px 0px;
123 123 line-height: 24px;
124 124
125 125 &:hover .permalink {
126 126 visibility: visible;
127 127 color: @rcblue;
128 128 }
129 129 }
130 130
131 131 .author,
132 132 .date {
133 133 display: inline;
134 134
135 135 &:after {
136 136 content: ' | ';
137 137 color: @grey5;
138 138 }
139 139 }
140 140
141 141 .author-general img {
142 142 top: 3px;
143 143 }
144 144 .author-inline img {
145 145 top: 3px;
146 146 }
147 147
148 148 .status-change,
149 149 .permalink,
150 150 .changeset-status-lbl {
151 151 display: inline;
152 152 }
153 153
154 154 .permalink {
155 155 visibility: hidden;
156 156 }
157 157
158 158 .comment-links-divider {
159 159 display: inline;
160 160 }
161 161
162 162 .comment-links-block {
163 163 float:right;
164 164 text-align: right;
165 165 min-width: 85px;
166 166
167 167 [class^="icon-"]:before,
168 168 [class*=" icon-"]:before {
169 169 margin-left: 0;
170 170 margin-right: 0;
171 171 }
172 172 }
173 173
174 174 .comment-previous-link {
175 175 display: inline-block;
176 176
177 177 .arrow_comment_link{
178 178 cursor: pointer;
179 179 i {
180 180 font-size:10px;
181 181 }
182 182 }
183 183 .arrow_comment_link.disabled {
184 184 cursor: default;
185 185 color: @grey5;
186 186 }
187 187 }
188 188
189 189 .comment-next-link {
190 190 display: inline-block;
191 191
192 192 .arrow_comment_link{
193 193 cursor: pointer;
194 194 i {
195 195 font-size:10px;
196 196 }
197 197 }
198 198 .arrow_comment_link.disabled {
199 199 cursor: default;
200 200 color: @grey5;
201 201 }
202 202 }
203 203
204 204 .flag_status {
205 205 display: inline-block;
206 206 margin: -2px .5em 0 .25em
207 207 }
208 208
209 209 .delete-comment {
210 210 display: inline-block;
211 211 color: @rcblue;
212 212
213 213 &:hover {
214 214 cursor: pointer;
215 215 }
216 216 }
217 217
218 218 .text {
219 219 clear: both;
220 220 .border-radius(@border-radius);
221 221 .box-sizing(border-box);
222 222
223 223 .markdown-block p,
224 224 .rst-block p {
225 225 margin: .5em 0 !important;
226 226 // TODO: lisa: This is needed because of other rst !important rules :[
227 227 }
228 228 }
229 229
230 230 .pr-version {
231 231 float: left;
232 232 margin: 0px 4px;
233 233 }
234 234 .pr-version-inline {
235 235 float: left;
236 236 margin: 0px 4px;
237 237 }
238 238 .pr-version-num {
239 239 font-size: 10px;
240 240 }
241 241
242 242 }
243 243
244 244 @comment-padding: 5px;
245 245
246 246 .inline-comments {
247 247 border-radius: @border-radius;
248 248 .comment {
249 249 margin: 0;
250 250 border-radius: @border-radius;
251 251 }
252 252 .comment-outdated {
253 253 opacity: 0.5;
254 254 }
255 255
256 256 .comment-inline {
257 257 background: white;
258 258 padding: @comment-padding @comment-padding;
259 259 border: @comment-padding solid @grey6;
260 260
261 261 .text {
262 262 border: none;
263 263 }
264 264 .meta {
265 265 border-bottom: 1px solid @grey6;
266 266 margin: -5px 0px;
267 267 line-height: 24px;
268 268 }
269 269 }
270 270 .comment-selected {
271 271 border-left: 6px solid @comment-highlight-color;
272 272 }
273 273 .comment-inline-form {
274 274 padding: @comment-padding;
275 275 display: none;
276 276 }
277 277 .cb-comment-add-button {
278 278 margin: @comment-padding;
279 279 }
280 280 /* hide add comment button when form is open */
281 281 .comment-inline-form-open ~ .cb-comment-add-button {
282 282 display: none;
283 283 }
284 284 .comment-inline-form-open {
285 285 display: block;
286 286 }
287 287 /* hide add comment button when form but no comments */
288 288 .comment-inline-form:first-child + .cb-comment-add-button {
289 289 display: none;
290 290 }
291 291 /* hide add comment button when no comments or form */
292 292 .cb-comment-add-button:first-child {
293 293 display: none;
294 294 }
295 295 /* hide add comment button when only comment is being deleted */
296 296 .comment-deleting:first-child + .cb-comment-add-button {
297 297 display: none;
298 298 }
299 299 }
300 300
301 301
302 302 .show-outdated-comments {
303 303 display: inline;
304 304 color: @rcblue;
305 305 }
306 306
307 307 // Comment Form
308 308 div.comment-form {
309 309 margin-top: 20px;
310 310 }
311 311
312 312 .comment-form strong {
313 313 display: block;
314 314 margin-bottom: 15px;
315 315 }
316 316
317 317 .comment-form textarea {
318 318 width: 100%;
319 319 height: 100px;
320 320 font-family: 'Monaco', 'Courier', 'Courier New', monospace;
321 321 }
322 322
323 323 form.comment-form {
324 324 margin-top: 10px;
325 325 margin-left: 10px;
326 326 }
327 327
328 328 .comment-inline-form .comment-block-ta,
329 329 .comment-form .comment-block-ta,
330 330 .comment-form .preview-box {
331 331 .border-radius(@border-radius);
332 332 .box-sizing(border-box);
333 333 background-color: white;
334 334 }
335 335
336 336 .comment-form-submit {
337 337 margin-top: 5px;
338 338 margin-left: 525px;
339 339 }
340 340
341 341 .file-comments {
342 342 display: none;
343 343 }
344 344
345 345 .comment-form .preview-box.unloaded,
346 346 .comment-inline-form .preview-box.unloaded {
347 347 height: 50px;
348 348 text-align: center;
349 349 padding: 20px;
350 350 background-color: white;
351 351 }
352 352
353 353 .comment-footer {
354 354 position: relative;
355 355 width: 100%;
356 356 min-height: 42px;
357 357
358 358 .status_box,
359 359 .cancel-button {
360 360 float: left;
361 361 display: inline-block;
362 362 }
363 363
364 364 .action-buttons {
365 365 float: right;
366 366 display: inline-block;
367 367 }
368 368 }
369 369
370 370 .comment-form {
371 371
372 372 .comment {
373 373 margin-left: 10px;
374 374 }
375 375
376 376 .comment-help {
377 377 color: @grey4;
378 378 padding: 5px 0 5px 0;
379 379 }
380 380
381 381 .comment-title {
382 382 padding: 5px 0 5px 0;
383 383 }
384 384
385 385 .comment-button {
386 386 display: inline-block;
387 387 }
388 388
389 389 .comment-button-input {
390 390 margin-right: 0;
391 391 }
392 392
393 393 .comment-footer {
394 394 margin-bottom: 110px;
395 395 margin-top: 10px;
396 396 }
397 397 }
398 398
399 399
400 400 .comment-form-login {
401 401 .comment-help {
402 402 padding: 0.9em; //same as the button
403 403 }
404 404
405 405 div.clearfix {
406 406 clear: both;
407 407 width: 100%;
408 408 display: block;
409 409 }
410 410 }
411 411
412 412 .comment-type {
413 413 margin: 0px;
414 414 border-radius: inherit;
415 415 border-color: @grey6;
416 416 }
417 417
418 418 .preview-box {
419 419 min-height: 105px;
420 420 margin-bottom: 15px;
421 421 background-color: white;
422 422 .border-radius(@border-radius);
423 423 .box-sizing(border-box);
424 424 }
425 425
426 426 .add-another-button {
427 427 margin-left: 10px;
428 428 margin-top: 10px;
429 429 margin-bottom: 10px;
430 430 }
431 431
432 432 .comment .buttons {
433 433 float: right;
434 434 margin: -1px 0px 0px 0px;
435 435 }
436 436
437 437 // Inline Comment Form
438 438 .injected_diff .comment-inline-form,
439 439 .comment-inline-form {
440 440 background-color: white;
441 441 margin-top: 10px;
442 442 margin-bottom: 20px;
443 443 }
444 444
445 445 .inline-form {
446 446 padding: 10px 7px;
447 447 }
448 448
449 449 .inline-form div {
450 450 max-width: 100%;
451 451 }
452 452
453 453 .overlay {
454 454 display: none;
455 455 position: absolute;
456 456 width: 100%;
457 457 text-align: center;
458 458 vertical-align: middle;
459 459 font-size: 16px;
460 460 background: none repeat scroll 0 0 white;
461 461
462 462 &.submitting {
463 463 display: block;
464 464 opacity: 0.5;
465 465 z-index: 100;
466 466 }
467 467 }
468 468 .comment-inline-form .overlay.submitting .overlay-text {
469 469 margin-top: 5%;
470 470 }
471 471
472 472 .comment-inline-form .clearfix,
473 473 .comment-form .clearfix {
474 474 .border-radius(@border-radius);
475 475 margin: 0px;
476 476 }
477 477
478 478 .comment-inline-form .comment-footer {
479 479 margin: 10px 0px 0px 0px;
480 480 }
481 481
482 482 .hide-inline-form-button {
483 483 margin-left: 5px;
484 484 }
485 485 .comment-button .hide-inline-form {
486 486 background: white;
487 487 }
488 488
489 489 .comment-area {
490 490 padding: 8px 12px;
491 491 border: 1px solid @grey5;
492 492 .border-radius(@border-radius);
493 493 }
494 494
495 495 .comment-area-header .nav-links {
496 496 display: flex;
497 497 flex-flow: row wrap;
498 498 -webkit-flex-flow: row wrap;
499 499 width: 100%;
500 500 }
501 501
502 502 .comment-area-footer {
503 503 display: flex;
504 504 }
505 505
506 506 .comment-footer .toolbar {
507 507
508 508 }
509 509
510 510 .nav-links {
511 511 padding: 0;
512 512 margin: 0;
513 513 list-style: none;
514 514 height: auto;
515 515 border-bottom: 1px solid @grey5;
516 516 }
517 517 .nav-links li {
518 518 display: inline-block;
519 519 }
520 520 .nav-links li:before {
521 521 content: "";
522 522 }
523 523 .nav-links li a.disabled {
524 524 cursor: not-allowed;
525 525 }
526 526
527 527 .nav-links li.active a {
528 528 border-bottom: 2px solid @rcblue;
529 529 color: #000;
530 530 font-weight: 600;
531 531 }
532 532 .nav-links li a {
533 533 display: inline-block;
534 534 padding: 0px 10px 5px 10px;
535 535 margin-bottom: -1px;
536 536 font-size: 14px;
537 537 line-height: 28px;
538 538 color: #8f8f8f;
539 539 border-bottom: 2px solid transparent;
540 540 }
541 541
542 542 .toolbar-text {
543 543 float: left;
544 544 margin: -5px 0px 0px 0px;
545 545 font-size: 12px;
546 546 }
547 547
@@ -1,314 +1,314 b''
1 1 ## -*- coding: utf-8 -*-
2 2
3 3 <%inherit file="/base/base.mako"/>
4 4 <%namespace name="diff_block" file="/changeset/diff_block.mako"/>
5 5
6 6 <%def name="title()">
7 7 ${_('%s Commit') % c.repo_name} - ${h.show_id(c.commit)}
8 8 %if c.rhodecode_name:
9 9 &middot; ${h.branding(c.rhodecode_name)}
10 10 %endif
11 11 </%def>
12 12
13 13 <%def name="menu_bar_nav()">
14 14 ${self.menu_items(active='repositories')}
15 15 </%def>
16 16
17 17 <%def name="menu_bar_subnav()">
18 18 ${self.repo_menu(active='changelog')}
19 19 </%def>
20 20
21 21 <%def name="main()">
22 22 <script>
23 23 // TODO: marcink switch this to pyroutes
24 24 AJAX_COMMENT_DELETE_URL = "${url('changeset_comment_delete',repo_name=c.repo_name,comment_id='__COMMENT_ID__')}";
25 25 templateContext.commit_data.commit_id = "${c.commit.raw_id}";
26 26 </script>
27 27 <div class="box">
28 28 <div class="title">
29 29 ${self.repo_page_title(c.rhodecode_db_repo)}
30 30 </div>
31 31
32 32 <div id="changeset_compare_view_content" class="summary changeset">
33 33 <div class="summary-detail">
34 34 <div class="summary-detail-header">
35 35 <span class="breadcrumbs files_location">
36 36 <h4>${_('Commit')}
37 37 <code>
38 38 ${h.show_id(c.commit)}
39 39 </code>
40 40 </h4>
41 41 </span>
42 42 <span id="parent_link">
43 43 <a href="#" title="${_('Parent Commit')}">${_('Parent')}</a>
44 44 </span>
45 45 |
46 46 <span id="child_link">
47 47 <a href="#" title="${_('Child Commit')}">${_('Child')}</a>
48 48 </span>
49 49 </div>
50 50
51 51 <div class="fieldset">
52 52 <div class="left-label">
53 53 ${_('Description')}:
54 54 </div>
55 55 <div class="right-content">
56 56 <div id="trimmed_message_box" class="commit">${h.urlify_commit_message(c.commit.message,c.repo_name)}</div>
57 57 <div id="message_expand" style="display:none;">
58 58 ${_('Expand')}
59 59 </div>
60 60 </div>
61 61 </div>
62 62
63 63 %if c.statuses:
64 64 <div class="fieldset">
65 65 <div class="left-label">
66 66 ${_('Commit status')}:
67 67 </div>
68 68 <div class="right-content">
69 69 <div class="changeset-status-ico">
70 70 <div class="${'flag_status %s' % c.statuses[0]} pull-left"></div>
71 71 </div>
72 72 <div title="${_('Commit status')}" class="changeset-status-lbl">[${h.commit_status_lbl(c.statuses[0])}]</div>
73 73 </div>
74 74 </div>
75 75 %endif
76 76
77 77 <div class="fieldset">
78 78 <div class="left-label">
79 79 ${_('References')}:
80 80 </div>
81 81 <div class="right-content">
82 82 <div class="tags">
83 83
84 84 %if c.commit.merge:
85 85 <span class="mergetag tag">
86 86 <i class="icon-merge"></i>${_('merge')}
87 87 </span>
88 88 %endif
89 89
90 90 %if h.is_hg(c.rhodecode_repo):
91 91 %for book in c.commit.bookmarks:
92 92 <span class="booktag tag" title="${_('Bookmark %s') % book}">
93 93 <a href="${h.url('files_home',repo_name=c.repo_name,revision=c.commit.raw_id)}"><i class="icon-bookmark"></i>${h.shorter(book)}</a>
94 94 </span>
95 95 %endfor
96 96 %endif
97 97
98 98 %for tag in c.commit.tags:
99 99 <span class="tagtag tag" title="${_('Tag %s') % tag}">
100 100 <a href="${h.url('files_home',repo_name=c.repo_name,revision=c.commit.raw_id)}"><i class="icon-tag"></i>${tag}</a>
101 101 </span>
102 102 %endfor
103 103
104 104 %if c.commit.branch:
105 105 <span class="branchtag tag" title="${_('Branch %s') % c.commit.branch}">
106 106 <a href="${h.url('files_home',repo_name=c.repo_name,revision=c.commit.raw_id)}"><i class="icon-code-fork"></i>${h.shorter(c.commit.branch)}</a>
107 107 </span>
108 108 %endif
109 109 </div>
110 110 </div>
111 111 </div>
112 112
113 113 <div class="fieldset">
114 114 <div class="left-label">
115 115 ${_('Diff options')}:
116 116 </div>
117 117 <div class="right-content">
118 118 <div class="diff-actions">
119 119 <a href="${h.url('changeset_raw_home',repo_name=c.repo_name,revision=c.commit.raw_id)}" class="tooltip" title="${h.tooltip(_('Raw diff'))}">
120 120 ${_('Raw Diff')}
121 121 </a>
122 122 |
123 123 <a href="${h.url('changeset_patch_home',repo_name=c.repo_name,revision=c.commit.raw_id)}" class="tooltip" title="${h.tooltip(_('Patch diff'))}">
124 124 ${_('Patch Diff')}
125 125 </a>
126 126 |
127 127 <a href="${h.url('changeset_download_home',repo_name=c.repo_name,revision=c.commit.raw_id,diff='download')}" class="tooltip" title="${h.tooltip(_('Download diff'))}">
128 128 ${_('Download Diff')}
129 129 </a>
130 130 |
131 131 ${c.ignorews_url(request.GET)}
132 132 |
133 133 ${c.context_url(request.GET)}
134 134 </div>
135 135 </div>
136 136 </div>
137 137
138 138 <div class="fieldset">
139 139 <div class="left-label">
140 140 ${_('Comments')}:
141 141 </div>
142 142 <div class="right-content">
143 143 <div class="comments-number">
144 144 %if c.comments:
145 145 <a href="#comments">${ungettext("%d Commit comment", "%d Commit comments", len(c.comments)) % len(c.comments)}</a>,
146 146 %else:
147 147 ${ungettext("%d Commit comment", "%d Commit comments", len(c.comments)) % len(c.comments)}
148 148 %endif
149 149 %if c.inline_cnt:
150 150 <a href="#" onclick="return Rhodecode.comments.nextComment();" id="inline-comments-counter">${ungettext("%d Inline Comment", "%d Inline Comments", c.inline_cnt) % c.inline_cnt}</a>
151 151 %else:
152 152 ${ungettext("%d Inline Comment", "%d Inline Comments", c.inline_cnt) % c.inline_cnt}
153 153 %endif
154 154 </div>
155 155 </div>
156 156 </div>
157 157
158 158 </div> <!-- end summary-detail -->
159 159
160 160 <div id="commit-stats" class="sidebar-right">
161 161 <div class="summary-detail-header">
162 162 <h4 class="item">
163 163 ${_('Author')}
164 164 </h4>
165 165 </div>
166 166 <div class="sidebar-right-content">
167 167 ${self.gravatar_with_user(c.commit.author)}
168 168 <div class="user-inline-data">- ${h.age_component(c.commit.date)}</div>
169 169 </div>
170 170 </div><!-- end sidebar -->
171 171 </div> <!-- end summary -->
172 172 <div class="cs_files">
173 173 <%namespace name="cbdiffs" file="/codeblocks/diffs.mako"/>
174 174 ${cbdiffs.render_diffset_menu()}
175 175 ${cbdiffs.render_diffset(
176 176 c.changes[c.commit.raw_id], commit=c.commit, use_comments=True)}
177 177 </div>
178 178
179 179 ## template for inline comment form
180 180 <%namespace name="comment" file="/changeset/changeset_file_comment.mako"/>
181 181
182 182 ## render comments
183 ${comment.generate_comments()}
183 ${comment.generate_comments(c.comments)}
184 184
185 185 ## main comment form and it status
186 186 ${comment.comments(h.url('changeset_comment', repo_name=c.repo_name, revision=c.commit.raw_id),
187 187 h.commit_status(c.rhodecode_db_repo, c.commit.raw_id))}
188 188 </div>
189 189
190 190 ## FORM FOR MAKING JS ACTION AS CHANGESET COMMENTS
191 191 <script type="text/javascript">
192 192
193 193 $(document).ready(function() {
194 194
195 195 var boxmax = parseInt($('#trimmed_message_box').css('max-height'), 10);
196 196 if($('#trimmed_message_box').height() === boxmax){
197 197 $('#message_expand').show();
198 198 }
199 199
200 200 $('#message_expand').on('click', function(e){
201 201 $('#trimmed_message_box').css('max-height', 'none');
202 202 $(this).hide();
203 203 });
204 204
205 205 $('.show-inline-comments').on('click', function(e){
206 206 var boxid = $(this).attr('data-comment-id');
207 207 var button = $(this);
208 208
209 209 if(button.hasClass("comments-visible")) {
210 210 $('#{0} .inline-comments'.format(boxid)).each(function(index){
211 211 $(this).hide();
212 212 });
213 213 button.removeClass("comments-visible");
214 214 } else {
215 215 $('#{0} .inline-comments'.format(boxid)).each(function(index){
216 216 $(this).show();
217 217 });
218 218 button.addClass("comments-visible");
219 219 }
220 220 });
221 221
222 222
223 223 // next links
224 224 $('#child_link').on('click', function(e){
225 225 // fetch via ajax what is going to be the next link, if we have
226 226 // >1 links show them to user to choose
227 227 if(!$('#child_link').hasClass('disabled')){
228 228 $.ajax({
229 229 url: '${h.url('changeset_children',repo_name=c.repo_name, revision=c.commit.raw_id)}',
230 230 success: function(data) {
231 231 if(data.results.length === 0){
232 232 $('#child_link').html("${_('No Child Commits')}").addClass('disabled');
233 233 }
234 234 if(data.results.length === 1){
235 235 var commit = data.results[0];
236 236 window.location = pyroutes.url('changeset_home', {'repo_name': '${c.repo_name}','revision': commit.raw_id});
237 237 }
238 238 else if(data.results.length === 2){
239 239 $('#child_link').addClass('disabled');
240 240 $('#child_link').addClass('double');
241 241 var _html = '';
242 242 _html +='<a title="__title__" href="__url__">__rev__</a> '
243 243 .replace('__rev__','r{0}:{1}'.format(data.results[0].revision, data.results[0].raw_id.substr(0,6)))
244 244 .replace('__title__', data.results[0].message)
245 245 .replace('__url__', pyroutes.url('changeset_home', {'repo_name': '${c.repo_name}','revision': data.results[0].raw_id}));
246 246 _html +=' | ';
247 247 _html +='<a title="__title__" href="__url__">__rev__</a> '
248 248 .replace('__rev__','r{0}:{1}'.format(data.results[1].revision, data.results[1].raw_id.substr(0,6)))
249 249 .replace('__title__', data.results[1].message)
250 250 .replace('__url__', pyroutes.url('changeset_home', {'repo_name': '${c.repo_name}','revision': data.results[1].raw_id}));
251 251 $('#child_link').html(_html);
252 252 }
253 253 }
254 254 });
255 255 e.preventDefault();
256 256 }
257 257 });
258 258
259 259 // prev links
260 260 $('#parent_link').on('click', function(e){
261 261 // fetch via ajax what is going to be the next link, if we have
262 262 // >1 links show them to user to choose
263 263 if(!$('#parent_link').hasClass('disabled')){
264 264 $.ajax({
265 265 url: '${h.url("changeset_parents",repo_name=c.repo_name, revision=c.commit.raw_id)}',
266 266 success: function(data) {
267 267 if(data.results.length === 0){
268 268 $('#parent_link').html('${_('No Parent Commits')}').addClass('disabled');
269 269 }
270 270 if(data.results.length === 1){
271 271 var commit = data.results[0];
272 272 window.location = pyroutes.url('changeset_home', {'repo_name': '${c.repo_name}','revision': commit.raw_id});
273 273 }
274 274 else if(data.results.length === 2){
275 275 $('#parent_link').addClass('disabled');
276 276 $('#parent_link').addClass('double');
277 277 var _html = '';
278 278 _html +='<a title="__title__" href="__url__">Parent __rev__</a>'
279 279 .replace('__rev__','r{0}:{1}'.format(data.results[0].revision, data.results[0].raw_id.substr(0,6)))
280 280 .replace('__title__', data.results[0].message)
281 281 .replace('__url__', pyroutes.url('changeset_home', {'repo_name': '${c.repo_name}','revision': data.results[0].raw_id}));
282 282 _html +=' | ';
283 283 _html +='<a title="__title__" href="__url__">Parent __rev__</a>'
284 284 .replace('__rev__','r{0}:{1}'.format(data.results[1].revision, data.results[1].raw_id.substr(0,6)))
285 285 .replace('__title__', data.results[1].message)
286 286 .replace('__url__', pyroutes.url('changeset_home', {'repo_name': '${c.repo_name}','revision': data.results[1].raw_id}));
287 287 $('#parent_link').html(_html);
288 288 }
289 289 }
290 290 });
291 291 e.preventDefault();
292 292 }
293 293 });
294 294
295 295 if (location.hash) {
296 296 var result = splitDelimitedHash(location.hash);
297 297 var line = $('html').find(result.loc);
298 298 if (line.length > 0){
299 299 offsetScroll(line, 70);
300 300 }
301 301 }
302 302
303 303 // browse tree @ revision
304 304 $('#files_link').on('click', function(e){
305 305 window.location = '${h.url('files_home',repo_name=c.repo_name, revision=c.commit.raw_id, f_path='')}';
306 306 e.preventDefault();
307 307 });
308 308
309 309 // inject comments into their proper positions
310 310 var file_comments = $('.inline-comment-placeholder');
311 311 })
312 312 </script>
313 313
314 314 </%def>
@@ -1,400 +1,408 b''
1 1 ## -*- coding: utf-8 -*-
2 2 ## usage:
3 3 ## <%namespace name="comment" file="/changeset/changeset_file_comment.mako"/>
4 4 ## ${comment.comment_block(comment)}
5 5 ##
6 6 <%namespace name="base" file="/base/base.mako"/>
7 7
8 8 <%def name="comment_block(comment, inline=False)">
9 <% outdated_at_ver = comment.outdated_at_version(getattr(c, 'at_version', None)) %>
10 9 <% pr_index_ver = comment.get_index_version(getattr(c, 'versions', [])) %>
10 % if inline:
11 <% outdated_at_ver = comment.outdated_at_version(getattr(c, 'at_version_num', None)) %>
12 % else:
13 <% outdated_at_ver = comment.older_than_version(getattr(c, 'at_version_num', None)) %>
14 % endif
15
11 16
12 17 <div class="comment
13 18 ${'comment-inline' if inline else 'comment-general'}
14 19 ${'comment-outdated' if outdated_at_ver else 'comment-current'}"
15 20 id="comment-${comment.comment_id}"
16 21 line="${comment.line_no}"
17 22 data-comment-id="${comment.comment_id}"
18 23 data-comment-type="${comment.comment_type}"
19 24 data-comment-inline=${h.json.dumps(inline)}
20 25 style="${'display: none;' if outdated_at_ver else ''}">
21 26
22 27 <div class="meta">
23 28 <div class="comment-type-label">
24 29 <div class="comment-label ${comment.comment_type or 'note'}" id="comment-label-${comment.comment_id}">
25 30 % if comment.comment_type == 'todo':
26 31 % if comment.resolved:
27 32 <div class="resolved tooltip" title="${_('Resolved by comment #{}').format(comment.resolved.comment_id)}">
28 33 <a href="#comment-${comment.resolved.comment_id}">${comment.comment_type}</a>
29 34 </div>
30 35 % else:
31 36 <div class="resolved tooltip" style="display: none">
32 37 <span>${comment.comment_type}</span>
33 38 </div>
34 39 <div class="resolve tooltip" onclick="return Rhodecode.comments.createResolutionComment(${comment.comment_id});" title="${_('Click to resolve this comment')}">
35 40 ${comment.comment_type}
36 41 </div>
37 42 % endif
38 43 % else:
39 44 % if comment.resolved_comment:
40 45 fix
41 46 % else:
42 47 ${comment.comment_type or 'note'}
43 48 % endif
44 49 % endif
45 50 </div>
46 51 </div>
47 52
48 53 <div class="author ${'author-inline' if inline else 'author-general'}">
49 54 ${base.gravatar_with_user(comment.author.email, 16)}
50 55 </div>
51 56 <div class="date">
52 57 ${h.age_component(comment.modified_at, time_is_local=True)}
53 58 </div>
54 59 % if inline:
55 60 <span></span>
56 61 % else:
57 62 <div class="status-change">
58 63 % if comment.pull_request:
59 64 <a href="${h.url('pullrequest_show',repo_name=comment.pull_request.target_repo.repo_name,pull_request_id=comment.pull_request.pull_request_id)}">
60 65 % if comment.status_change:
61 66 ${_('pull request #%s') % comment.pull_request.pull_request_id}:
62 67 % else:
63 68 ${_('pull request #%s') % comment.pull_request.pull_request_id}
64 69 % endif
65 70 </a>
66 71 % else:
67 72 % if comment.status_change:
68 73 ${_('Status change on commit')}:
69 74 % endif
70 75 % endif
71 76 </div>
72 77 % endif
73 78
74 79 % if comment.status_change:
75 80 <div class="${'flag_status %s' % comment.status_change[0].status}"></div>
76 81 <div title="${_('Commit status')}" class="changeset-status-lbl">
77 82 ${comment.status_change[0].status_lbl}
78 83 </div>
79 84 % endif
80 85
81 86 <a class="permalink" href="#comment-${comment.comment_id}"> &para;</a>
82 87
83 88 <div class="comment-links-block">
84 89
85 90 % if inline:
86 % if outdated_at_ver:
87 91 <div class="pr-version-inline">
88 92 <a href="${h.url.current(version=comment.pull_request_version_id, anchor='comment-{}'.format(comment.comment_id))}">
89 <code class="pr-version-num">
90 outdated ${'v{}'.format(pr_index_ver)}
91 </code>
93 % if outdated_at_ver:
94 <code class="pr-version-num" title="${_('Outdated comment from pull request version {0}').format(pr_index_ver)}">
95 outdated ${'v{}'.format(pr_index_ver)} |
96 </code>
97 % elif pr_index_ver:
98 <code class="pr-version-num" title="${_('Comment from pull request version {0}').format(pr_index_ver)}">
99 ${'v{}'.format(pr_index_ver)} |
100 </code>
101 % endif
92 102 </a>
93 103 </div>
94 |
95 % endif
96 104 % else:
97 105 % if comment.pull_request_version_id and pr_index_ver:
98 106 |
99 107 <div class="pr-version">
100 108 % if comment.outdated:
101 109 <a href="?version=${comment.pull_request_version_id}#comment-${comment.comment_id}">
102 110 ${_('Outdated comment from pull request version {}').format(pr_index_ver)}
103 111 </a>
104 112 % else:
105 <div class="tooltip" title="${_('Comment from pull request version {0}').format(pr_index_ver)}">
113 <div title="${_('Comment from pull request version {0}').format(pr_index_ver)}">
106 114 <a href="${h.url('pullrequest_show',repo_name=comment.pull_request.target_repo.repo_name,pull_request_id=comment.pull_request.pull_request_id, version=comment.pull_request_version_id)}">
107 115 <code class="pr-version-num">
108 116 ${'v{}'.format(pr_index_ver)}
109 117 </code>
110 118 </a>
111 119 </div>
112 120 % endif
113 121 </div>
114 122 % endif
115 123 % endif
116 124
117 125 ## show delete comment if it's not a PR (regular comments) or it's PR that is not closed
118 126 ## only super-admin, repo admin OR comment owner can delete, also hide delete if currently viewed comment is outdated
119 127 %if not outdated_at_ver and (not comment.pull_request or (comment.pull_request and not comment.pull_request.is_closed())):
120 128 ## permissions to delete
121 129 %if h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or comment.author.user_id == c.rhodecode_user.user_id:
122 130 ## TODO: dan: add edit comment here
123 131 <a onclick="return Rhodecode.comments.deleteComment(this);" class="delete-comment"> ${_('Delete')}</a>
124 132 %else:
125 133 <button class="btn-link" disabled="disabled"> ${_('Delete')}</button>
126 134 %endif
127 135 %else:
128 136 <button class="btn-link" disabled="disabled"> ${_('Delete')}</button>
129 137 %endif
130 138
131 139 %if not outdated_at_ver:
132 140 | <a onclick="return Rhodecode.comments.prevComment(this);" class="prev-comment"> ${_('Prev')}</a>
133 141 | <a onclick="return Rhodecode.comments.nextComment(this);" class="next-comment"> ${_('Next')}</a>
134 142 %endif
135 143
136 144 </div>
137 145 </div>
138 146 <div class="text">
139 147 ${comment.render(mentions=True)|n}
140 148 </div>
141 149
142 150 </div>
143 151 </%def>
144 152
145 153 ## generate main comments
146 <%def name="generate_comments(include_pull_request=False, is_pull_request=False)">
154 <%def name="generate_comments(comments, include_pull_request=False, is_pull_request=False)">
147 155 <div id="comments">
148 %for comment in c.comments:
156 %for comment in comments:
149 157 <div id="comment-tr-${comment.comment_id}">
150 158 ## only render comments that are not from pull request, or from
151 159 ## pull request and a status change
152 160 %if not comment.pull_request or (comment.pull_request and comment.status_change) or include_pull_request:
153 161 ${comment_block(comment)}
154 162 %endif
155 163 </div>
156 164 %endfor
157 165 ## to anchor ajax comments
158 166 <div id="injected_page_comments"></div>
159 167 </div>
160 168 </%def>
161 169
162 170
163 171 <%def name="comments(post_url, cur_status, is_pull_request=False, is_compare=False, change_status=True, form_extras=None)">
164 172
165 173 ## merge status, and merge action
166 174 %if is_pull_request:
167 175 <div class="pull-request-merge">
168 176 %if c.allowed_to_merge:
169 177 <div class="pull-request-wrap">
170 178 <div class="pull-right">
171 179 ${h.secure_form(url('pullrequest_merge', repo_name=c.repo_name, pull_request_id=c.pull_request.pull_request_id), id='merge_pull_request_form')}
172 180 <span data-role="merge-message">${c.pr_merge_msg} ${c.approval_msg if c.approval_msg else ''}</span>
173 181 <% merge_disabled = ' disabled' if c.pr_merge_status is False else '' %>
174 182 <input type="submit" id="merge_pull_request" value="${_('Merge Pull Request')}" class="btn${merge_disabled}"${merge_disabled}>
175 183 ${h.end_form()}
176 184 </div>
177 185 </div>
178 186 %else:
179 187 <div class="pull-request-wrap">
180 188 <div class="pull-right">
181 189 <span>${c.pr_merge_msg} ${c.approval_msg if c.approval_msg else ''}</span>
182 190 </div>
183 191 </div>
184 192 %endif
185 193 </div>
186 194 %endif
187 195
188 196 <div class="comments">
189 197 <%
190 198 if is_pull_request:
191 199 placeholder = _('Leave a comment on this Pull Request.')
192 200 elif is_compare:
193 201 placeholder = _('Leave a comment on {} commits in this range.').format(len(form_extras))
194 202 else:
195 203 placeholder = _('Leave a comment on this Commit.')
196 204 %>
197 205
198 206 % if c.rhodecode_user.username != h.DEFAULT_USER:
199 207 <div class="js-template" id="cb-comment-general-form-template">
200 208 ## template generated for injection
201 209 ${comment_form(form_type='general', review_statuses=c.commit_statuses, form_extras=form_extras)}
202 210 </div>
203 211
204 212 <div id="cb-comment-general-form-placeholder" class="comment-form ac">
205 213 ## inject form here
206 214 </div>
207 215 <script type="text/javascript">
208 216 var lineNo = 'general';
209 217 var resolvesCommentId = null;
210 218 var generalCommentForm = Rhodecode.comments.createGeneralComment(
211 219 lineNo, "${placeholder}", resolvesCommentId);
212 220
213 221 // set custom success callback on rangeCommit
214 222 % if is_compare:
215 223 generalCommentForm.setHandleFormSubmit(function(o) {
216 224 var self = generalCommentForm;
217 225
218 226 var text = self.cm.getValue();
219 227 var status = self.getCommentStatus();
220 228 var commentType = self.getCommentType();
221 229
222 230 if (text === "" && !status) {
223 231 return;
224 232 }
225 233
226 234 // we can pick which commits we want to make the comment by
227 235 // selecting them via click on preview pane, this will alter the hidden inputs
228 236 var cherryPicked = $('#changeset_compare_view_content .compare_select.hl').length > 0;
229 237
230 238 var commitIds = [];
231 239 $('#changeset_compare_view_content .compare_select').each(function(el) {
232 240 var commitId = this.id.replace('row-', '');
233 241 if ($(this).hasClass('hl') || !cherryPicked) {
234 242 $("input[data-commit-id='{0}']".format(commitId)).val(commitId);
235 243 commitIds.push(commitId);
236 244 } else {
237 245 $("input[data-commit-id='{0}']".format(commitId)).val('')
238 246 }
239 247 });
240 248
241 249 self.setActionButtonsDisabled(true);
242 250 self.cm.setOption("readOnly", true);
243 251 var postData = {
244 252 'text': text,
245 253 'changeset_status': status,
246 254 'comment_type': commentType,
247 255 'commit_ids': commitIds,
248 256 'csrf_token': CSRF_TOKEN
249 257 };
250 258
251 259 var submitSuccessCallback = function(o) {
252 260 location.reload(true);
253 261 };
254 262 var submitFailCallback = function(){
255 263 self.resetCommentFormState(text)
256 264 };
257 265 self.submitAjaxPOST(
258 266 self.submitUrl, postData, submitSuccessCallback, submitFailCallback);
259 267 });
260 268 % endif
261 269
262 270
263 271 </script>
264 272 % else:
265 273 ## form state when not logged in
266 274 <div class="comment-form ac">
267 275
268 276 <div class="comment-area">
269 277 <div class="comment-area-header">
270 278 <ul class="nav-links clearfix">
271 279 <li class="active">
272 280 <a class="disabled" href="#edit-btn" disabled="disabled" onclick="return false">${_('Write')}</a>
273 281 </li>
274 282 <li class="">
275 283 <a class="disabled" href="#preview-btn" disabled="disabled" onclick="return false">${_('Preview')}</a>
276 284 </li>
277 285 </ul>
278 286 </div>
279 287
280 288 <div class="comment-area-write" style="display: block;">
281 289 <div id="edit-container">
282 290 <div style="padding: 40px 0">
283 291 ${_('You need to be logged in to leave comments.')}
284 292 <a href="${h.route_path('login', _query={'came_from': h.url.current()})}">${_('Login now')}</a>
285 293 </div>
286 294 </div>
287 295 <div id="preview-container" class="clearfix" style="display: none;">
288 296 <div id="preview-box" class="preview-box"></div>
289 297 </div>
290 298 </div>
291 299
292 300 <div class="comment-area-footer">
293 301 <div class="toolbar">
294 302 <div class="toolbar-text">
295 303 </div>
296 304 </div>
297 305 </div>
298 306 </div>
299 307
300 308 <div class="comment-footer">
301 309 </div>
302 310
303 311 </div>
304 312 % endif
305 313
306 314 <script type="text/javascript">
307 315 bindToggleButtons();
308 316 </script>
309 317 </div>
310 318 </%def>
311 319
312 320
313 321 <%def name="comment_form(form_type, form_id='', lineno_id='{1}', review_statuses=None, form_extras=None)">
314 322 ## comment injected based on assumption that user is logged in
315 323
316 324 <form ${'id="{}"'.format(form_id) if form_id else '' |n} action="#" method="GET">
317 325
318 326 <div class="comment-area">
319 327 <div class="comment-area-header">
320 328 <ul class="nav-links clearfix">
321 329 <li class="active">
322 330 <a href="#edit-btn" tabindex="-1" id="edit-btn_${lineno_id}">${_('Write')}</a>
323 331 </li>
324 332 <li class="">
325 333 <a href="#preview-btn" tabindex="-1" id="preview-btn_${lineno_id}">${_('Preview')}</a>
326 334 </li>
327 335 <li class="pull-right">
328 336 <select class="comment-type" id="comment_type_${lineno_id}" name="comment_type">
329 337 % for val in c.visual.comment_types:
330 338 <option value="${val}">${val.upper()}</option>
331 339 % endfor
332 340 </select>
333 341 </li>
334 342 </ul>
335 343 </div>
336 344
337 345 <div class="comment-area-write" style="display: block;">
338 346 <div id="edit-container_${lineno_id}">
339 347 <textarea id="text_${lineno_id}" name="text" class="comment-block-ta ac-input"></textarea>
340 348 </div>
341 349 <div id="preview-container_${lineno_id}" class="clearfix" style="display: none;">
342 350 <div id="preview-box_${lineno_id}" class="preview-box"></div>
343 351 </div>
344 352 </div>
345 353
346 354 <div class="comment-area-footer">
347 355 <div class="toolbar">
348 356 <div class="toolbar-text">
349 357 ${(_('Comments parsed using %s syntax with %s support.') % (
350 358 ('<a href="%s">%s</a>' % (h.url('%s_help' % c.visual.default_renderer), c.visual.default_renderer.upper())),
351 359 ('<span class="tooltip" title="%s">@mention</span>' % _('Use @username inside this text to send notification to this RhodeCode user'))
352 360 )
353 361 )|n}
354 362 </div>
355 363 </div>
356 364 </div>
357 365 </div>
358 366
359 367 <div class="comment-footer">
360 368
361 369 % if review_statuses:
362 370 <div class="status_box">
363 371 <select id="change_status_${lineno_id}" name="changeset_status">
364 372 <option></option> ## Placeholder
365 373 % for status, lbl in review_statuses:
366 374 <option value="${status}" data-status="${status}">${lbl}</option>
367 375 %if is_pull_request and change_status and status in ('approved', 'rejected'):
368 376 <option value="${status}_closed" data-status="${status}">${lbl} & ${_('Closed')}</option>
369 377 %endif
370 378 % endfor
371 379 </select>
372 380 </div>
373 381 % endif
374 382
375 383 ## inject extra inputs into the form
376 384 % if form_extras and isinstance(form_extras, (list, tuple)):
377 385 <div id="comment_form_extras">
378 386 % for form_ex_el in form_extras:
379 387 ${form_ex_el|n}
380 388 % endfor
381 389 </div>
382 390 % endif
383 391
384 392 <div class="action-buttons">
385 393 ## inline for has a file, and line-number together with cancel hide button.
386 394 % if form_type == 'inline':
387 395 <input type="hidden" name="f_path" value="{0}">
388 396 <input type="hidden" name="line" value="${lineno_id}">
389 397 <button type="button" class="cb-comment-cancel" onclick="return Rhodecode.comments.cancelComment(this);">
390 398 ${_('Cancel')}
391 399 </button>
392 400 % endif
393 401 ${h.submit('save', _('Comment'), class_='btn btn-success comment-button-input')}
394 402
395 403 </div>
396 404 </div>
397 405
398 406 </form>
399 407
400 408 </%def> No newline at end of file
@@ -1,647 +1,692 b''
1 1 <%inherit file="/base/base.mako"/>
2 2
3 3 <%def name="title()">
4 4 ${_('%s Pull Request #%s') % (c.repo_name, c.pull_request.pull_request_id)}
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()">
11 11 <span id="pr-title">
12 12 ${c.pull_request.title}
13 13 %if c.pull_request.is_closed():
14 14 (${_('Closed')})
15 15 %endif
16 16 </span>
17 17 <div id="pr-title-edit" class="input" style="display: none;">
18 18 ${h.text('pullrequest_title', id_="pr-title-input", class_="large", value=c.pull_request.title)}
19 19 </div>
20 20 </%def>
21 21
22 22 <%def name="menu_bar_nav()">
23 23 ${self.menu_items(active='repositories')}
24 24 </%def>
25 25
26 26 <%def name="menu_bar_subnav()">
27 27 ${self.repo_menu(active='showpullrequest')}
28 28 </%def>
29 29
30 30 <%def name="main()">
31 31
32 32 <script type="text/javascript">
33 33 // TODO: marcink switch this to pyroutes
34 34 AJAX_COMMENT_DELETE_URL = "${url('pullrequest_comment_delete',repo_name=c.repo_name,comment_id='__COMMENT_ID__')}";
35 35 templateContext.pull_request_data.pull_request_id = ${c.pull_request.pull_request_id};
36 36 </script>
37 37 <div class="box">
38
38 39 <div class="title">
39 40 ${self.repo_page_title(c.rhodecode_db_repo)}
40 41 </div>
41 42
42 43 ${self.breadcrumbs()}
43 44
44 45 <div class="box pr-summary">
46
45 47 <div class="summary-details block-left">
46 48 <% summary = lambda n:{False:'summary-short'}.get(n) %>
47 49 <div class="pr-details-title">
48 50 <a href="${h.url('pull_requests_global', pull_request_id=c.pull_request.pull_request_id)}">${_('Pull request #%s') % c.pull_request.pull_request_id}</a> ${_('From')} ${h.format_date(c.pull_request.created_on)}
49 51 %if c.allowed_to_update:
50 52 <div id="delete_pullrequest" class="pull-right action_button ${'' if c.allowed_to_delete else 'disabled' }" style="clear:inherit;padding: 0">
51 53 % if c.allowed_to_delete:
52 54 ${h.secure_form(url('pullrequest_delete', repo_name=c.pull_request.target_repo.repo_name, pull_request_id=c.pull_request.pull_request_id),method='delete')}
53 55 ${h.submit('remove_%s' % c.pull_request.pull_request_id, _('Delete'),
54 56 class_="btn btn-link btn-danger",onclick="return confirm('"+_('Confirm to delete this pull request')+"');")}
55 57 ${h.end_form()}
56 58 % else:
57 59 ${_('Delete')}
58 60 % endif
59 61 </div>
60 62 <div id="open_edit_pullrequest" class="pull-right action_button">${_('Edit')}</div>
61 63 <div id="close_edit_pullrequest" class="pull-right action_button" style="display: none;padding: 0">${_('Cancel')}</div>
62 64 %endif
63 65 </div>
64 66
65 67 <div id="summary" class="fields pr-details-content">
66 68 <div class="field">
67 69 <div class="label-summary">
68 70 <label>${_('Origin')}:</label>
69 71 </div>
70 72 <div class="input">
71 73 <div class="pr-origininfo">
72 74 ## branch link is only valid if it is a branch
73 75 <span class="tag">
74 76 %if c.pull_request.source_ref_parts.type == 'branch':
75 77 <a href="${h.url('changelog_home', repo_name=c.pull_request.source_repo.repo_name, branch=c.pull_request.source_ref_parts.name)}">${c.pull_request.source_ref_parts.type}: ${c.pull_request.source_ref_parts.name}</a>
76 78 %else:
77 79 ${c.pull_request.source_ref_parts.type}: ${c.pull_request.source_ref_parts.name}
78 80 %endif
79 81 </span>
80 82 <span class="clone-url">
81 83 <a href="${h.url('summary_home', repo_name=c.pull_request.source_repo.repo_name)}">${c.pull_request.source_repo.clone_url()}</a>
82 84 </span>
83 85 </div>
84 86 <div class="pr-pullinfo">
85 87 %if h.is_hg(c.pull_request.source_repo):
86 88 <input type="text" value="hg pull -r ${h.short_id(c.source_ref)} ${c.pull_request.source_repo.clone_url()}" readonly="readonly">
87 89 %elif h.is_git(c.pull_request.source_repo):
88 90 <input type="text" value="git pull ${c.pull_request.source_repo.clone_url()} ${c.pull_request.source_ref_parts.name}" readonly="readonly">
89 91 %endif
90 92 </div>
91 93 </div>
92 94 </div>
93 95 <div class="field">
94 96 <div class="label-summary">
95 97 <label>${_('Target')}:</label>
96 98 </div>
97 99 <div class="input">
98 100 <div class="pr-targetinfo">
99 101 ## branch link is only valid if it is a branch
100 102 <span class="tag">
101 103 %if c.pull_request.target_ref_parts.type == 'branch':
102 104 <a href="${h.url('changelog_home', repo_name=c.pull_request.target_repo.repo_name, branch=c.pull_request.target_ref_parts.name)}">${c.pull_request.target_ref_parts.type}: ${c.pull_request.target_ref_parts.name}</a>
103 105 %else:
104 106 ${c.pull_request.target_ref_parts.type}: ${c.pull_request.target_ref_parts.name}
105 107 %endif
106 108 </span>
107 109 <span class="clone-url">
108 110 <a href="${h.url('summary_home', repo_name=c.pull_request.target_repo.repo_name)}">${c.pull_request.target_repo.clone_url()}</a>
109 111 </span>
110 112 </div>
111 113 </div>
112 114 </div>
113 115
114 116 ## Link to the shadow repository.
115 117 <div class="field">
116 118 <div class="label-summary">
117 119 <label>${_('Merge')}:</label>
118 120 </div>
119 121 <div class="input">
120 122 % if not c.pull_request.is_closed() and c.pull_request.shadow_merge_ref:
121 123 <div class="pr-mergeinfo">
122 124 %if h.is_hg(c.pull_request.target_repo):
123 125 <input type="text" value="hg clone -u ${c.pull_request.shadow_merge_ref.name} ${c.shadow_clone_url} pull-request-${c.pull_request.pull_request_id}" readonly="readonly">
124 126 %elif h.is_git(c.pull_request.target_repo):
125 127 <input type="text" value="git clone --branch ${c.pull_request.shadow_merge_ref.name} ${c.shadow_clone_url} pull-request-${c.pull_request.pull_request_id}" readonly="readonly">
126 128 %endif
127 129 </div>
128 130 % else:
129 131 <div class="">
130 132 ${_('Shadow repository data not available')}.
131 133 </div>
132 134 % endif
133 135 </div>
134 136 </div>
135 137
136 138 <div class="field">
137 139 <div class="label-summary">
138 140 <label>${_('Review')}:</label>
139 141 </div>
140 142 <div class="input">
141 143 %if c.pull_request_review_status:
142 144 <div class="${'flag_status %s' % c.pull_request_review_status} tooltip pull-left"></div>
143 145 <span class="changeset-status-lbl tooltip">
144 146 %if c.pull_request.is_closed():
145 147 ${_('Closed')},
146 148 %endif
147 149 ${h.commit_status_lbl(c.pull_request_review_status)}
148 150 </span>
149 151 - ${ungettext('calculated based on %s reviewer vote', 'calculated based on %s reviewers votes', len(c.pull_request_reviewers)) % len(c.pull_request_reviewers)}
150 152 %endif
151 153 </div>
152 154 </div>
153 155 <div class="field">
154 156 <div class="pr-description-label label-summary">
155 157 <label>${_('Description')}:</label>
156 158 </div>
157 159 <div id="pr-desc" class="input">
158 160 <div class="pr-description">${h.urlify_commit_message(c.pull_request.description, c.repo_name)}</div>
159 161 </div>
160 162 <div id="pr-desc-edit" class="input textarea editor" style="display: none;">
161 163 <textarea id="pr-description-input" size="30">${c.pull_request.description}</textarea>
162 164 </div>
163 165 </div>
164 166
165 167 <div class="field">
166 168 <div class="label-summary">
167 169 <label>${_('Versions')} (${len(c.versions)+1}):</label>
168 170 </div>
169 171
170 172 <div class="pr-versions">
171 173 % if c.show_version_changes:
172 174 <table>
173 175 ## CURRENTLY SELECT PR VERSION
174 176 <tr class="version-pr" style="display: ${'' if c.at_version_num is None else 'none'}">
175 177 <td>
176 % if c.at_version in [None, 'latest']:
178 % if c.at_version_num is None:
177 179 <i class="icon-ok link"></i>
178 180 % else:
179 <i class="icon-comment"></i> <code>${len(c.inline_versions[None])}</code>
181 <i class="icon-comment"></i>
182 <code>
183 ${len(c.comment_versions[None]['at'])}/${len(c.inline_versions[None]['at'])}
184 </code>
180 185 % endif
181 186 </td>
182 187 <td>
183 188 <code>
184 189 % if c.versions:
185 190 <a href="${h.url.current(version='latest')}">${_('latest')}</a>
186 191 % else:
187 192 ${_('initial')}
188 193 % endif
189 194 </code>
190 195 </td>
191 196 <td>
192 197 <code>${c.pull_request_latest.source_ref_parts.commit_id[:6]}</code>
193 198 </td>
194 199 <td>
195 200 ${_('created')} ${h.age_component(c.pull_request_latest.updated_on)}
196 201 </td>
197 202 <td align="right">
198 203 % if c.versions and c.at_version_num in [None, 'latest']:
199 204 <span id="show-pr-versions" class="btn btn-link" onclick="$('.version-pr').show(); $(this).hide(); return false">${_('Show all versions')}</span>
200 205 % endif
201 206 </td>
202 207 </tr>
203 208
204 209 ## SHOW ALL VERSIONS OF PR
205 210 <% ver_pr = None %>
211
206 212 % for data in reversed(list(enumerate(c.versions, 1))):
207 <% ver_pos = data[0] %>
208 <% ver = data[1] %>
209 <% ver_pr = ver.pull_request_version_id %>
213 <% ver_pos = data[0] %>
214 <% ver = data[1] %>
215 <% ver_pr = ver.pull_request_version_id %>
210 216
211 <tr class="version-pr" style="display: ${'' if c.at_version == ver_pr else 'none'}">
212 <td>
213 % if c.at_version == ver_pr:
214 <i class="icon-ok link"></i>
215 % else:
216 <i class="icon-comment"></i> <code>${len(c.inline_versions[ver_pr])}</code>
217 % endif
218 </td>
219 <td>
220 <code class="tooltip" title="${_('Comment from pull request version {0}').format(ver_pos)}">
221 <a href="${h.url.current(version=ver_pr)}">v${ver_pos}</a>
222 </code>
223 </td>
224 <td>
225 <code>${ver.source_ref_parts.commit_id[:6]}</code>
226 </td>
227 <td>
228 ${_('created')} ${h.age_component(ver.updated_on)}
229 </td>
230 <td align="right">
231 % if c.at_version == ver_pr:
232 <span id="show-pr-versions" class="btn btn-link" onclick="$('.version-pr').show(); $(this).hide(); return false">${_('Show all versions')}</span>
233 % endif
234 </td>
235 </tr>
217 <tr class="version-pr" style="display: ${'' if c.at_version_num == ver_pr else 'none'}">
218 <td>
219 % if c.at_version_num == ver_pr:
220 <i class="icon-ok link"></i>
221 % else:
222 <i class="icon-comment"></i>
223 <code class="tooltip" title="${_('Comment from pull request version {0}, general:{1} inline{2}').format(ver_pos, len(c.comment_versions[ver_pr]['at']), len(c.inline_versions[ver_pr]['at']))}">
224 ${len(c.comment_versions[ver_pr]['at'])}/${len(c.inline_versions[ver_pr]['at'])}
225 </code>
226 % endif
227 </td>
228 <td>
229 <code>
230 <a href="${h.url.current(version=ver_pr)}">v${ver_pos}</a>
231 </code>
232 </td>
233 <td>
234 <code>${ver.source_ref_parts.commit_id[:6]}</code>
235 </td>
236 <td>
237 ${_('created')} ${h.age_component(ver.updated_on)}
238 </td>
239 <td align="right">
240 % if c.at_version_num == ver_pr:
241 <span id="show-pr-versions" class="btn btn-link" onclick="$('.version-pr').show(); $(this).hide(); return false">${_('Show all versions')}</span>
242 % endif
243 </td>
244 </tr>
236 245 % endfor
237 246
238 247 ## show comment/inline comments summary
239 248 <tr>
240 249 <td>
241 250 </td>
242 251
243 <% inline_comm_count_ver = len(c.inline_versions[ver_pr])%>
244 252 <td colspan="4" style="border-top: 1px dashed #dbd9da">
245 ${_('Comments for this version')}:
246 %if c.comments:
247 <a href="#comments">${_("%d General ") % len(c.comments)}</a>
253 <% outdated_comm_count_ver = len(c.inline_versions[c.at_version_num]['outdated']) %>
254 <% general_outdated_comm_count_ver = len(c.comment_versions[c.at_version_num]['outdated']) %>
255
256
257 % if c.at_version:
258 <% inline_comm_count_ver = len(c.inline_versions[c.at_version_num]['display']) %>
259 <% general_comm_count_ver = len(c.comment_versions[c.at_version_num]['display']) %>
260 ${_('Comments at this version')}:
261 % else:
262 <% inline_comm_count_ver = len(c.inline_versions[c.at_version_num]['until']) %>
263 <% general_comm_count_ver = len(c.comment_versions[c.at_version_num]['until']) %>
264 ${_('Comments for this pull request')}:
265 % endif
266
267 %if general_comm_count_ver:
268 <a href="#comments">${_("%d General ") % general_comm_count_ver}</a>
248 269 %else:
249 ${_("%d General ") % len(c.comments)}
270 ${_("%d General ") % general_comm_count_ver}
250 271 %endif
251 272
252 <% inline_comm_count_ver = len(c.inline_versions[c.at_version_num])%>
253 273 %if inline_comm_count_ver:
254 274 , <a href="#" onclick="return Rhodecode.comments.nextComment();" id="inline-comments-counter">${_("%d Inline") % inline_comm_count_ver}</a>
255 275 %else:
256 276 , ${_("%d Inline") % inline_comm_count_ver}
257 277 %endif
258 278
259 %if c.outdated_cnt:
260 , <a href="#" onclick="showOutdated(); Rhodecode.comments.nextOutdatedComment(); return false;">${_("%d Outdated") % c.outdated_cnt}</a>
279 %if outdated_comm_count_ver:
280 , <a href="#" onclick="showOutdated(); Rhodecode.comments.nextOutdatedComment(); return false;">${_("%d Outdated") % outdated_comm_count_ver}</a>
261 281 <a href="#" class="showOutdatedComments" onclick="showOutdated(this); return false;"> | ${_('show outdated comments')}</a>
262 282 <a href="#" class="hideOutdatedComments" style="display: none" onclick="hideOutdated(this); return false;"> | ${_('hide outdated comments')}</a>
263 283 %else:
264 , ${_("%d Outdated") % c.outdated_cnt}
284 , ${_("%d Outdated") % outdated_comm_count_ver}
265 285 %endif
266 286 </td>
267 287 </tr>
268 288
269 289 <tr>
270 290 <td></td>
271 291 <td colspan="4">
272 292 % if c.at_version:
273 293 <pre>
274 294 Changed commits:
275 295 * added: ${len(c.changes.added)}
276 296 * removed: ${len(c.changes.removed)}
277 297
278 298 % if not (c.file_changes.added+c.file_changes.modified+c.file_changes.removed):
279 299 No file changes found
280 300 % else:
281 301 Changed files:
282 302 %for file_name in c.file_changes.added:
283 303 * A <a href="#${'a_' + h.FID('', file_name)}">${file_name}</a>
284 304 %endfor
285 305 %for file_name in c.file_changes.modified:
286 306 * M <a href="#${'a_' + h.FID('', file_name)}">${file_name}</a>
287 307 %endfor
288 308 %for file_name in c.file_changes.removed:
289 309 * R ${file_name}
290 310 %endfor
291 311 % endif
292 312 </pre>
293 313 % endif
294 314 </td>
295 315 </tr>
296 316 </table>
297 317 % else:
298 318 ${_('Pull request versions not available')}.
299 319 % endif
300 320 </div>
301 321 </div>
302 322
303 323 <div id="pr-save" class="field" style="display: none;">
304 324 <div class="label-summary"></div>
305 325 <div class="input">
306 326 <span id="edit_pull_request" class="btn btn-small">${_('Save Changes')}</span>
307 327 </div>
308 328 </div>
309 329 </div>
310 330 </div>
311 331 <div>
312 332 ## AUTHOR
313 333 <div class="reviewers-title block-right">
314 334 <div class="pr-details-title">
315 335 ${_('Author')}
316 336 </div>
317 337 </div>
318 338 <div class="block-right pr-details-content reviewers">
319 339 <ul class="group_members">
320 340 <li>
321 341 ${self.gravatar_with_user(c.pull_request.author.email, 16)}
322 342 </li>
323 343 </ul>
324 344 </div>
325 345 ## REVIEWERS
326 346 <div class="reviewers-title block-right">
327 347 <div class="pr-details-title">
328 348 ${_('Pull request reviewers')}
329 349 %if c.allowed_to_update:
330 350 <span id="open_edit_reviewers" class="block-right action_button">${_('Edit')}</span>
331 351 <span id="close_edit_reviewers" class="block-right action_button" style="display: none;">${_('Close')}</span>
332 352 %endif
333 353 </div>
334 354 </div>
335 355 <div id="reviewers" class="block-right pr-details-content reviewers">
336 356 ## members goes here !
337 357 <input type="hidden" name="__start__" value="review_members:sequence">
338 358 <ul id="review_members" class="group_members">
339 359 %for member,reasons,status in c.pull_request_reviewers:
340 360 <li id="reviewer_${member.user_id}">
341 361 <div class="reviewers_member">
342 362 <div class="reviewer_status tooltip" title="${h.tooltip(h.commit_status_lbl(status[0][1].status if status else 'not_reviewed'))}">
343 363 <div class="${'flag_status %s' % (status[0][1].status if status else 'not_reviewed')} pull-left reviewer_member_status"></div>
344 364 </div>
345 365 <div id="reviewer_${member.user_id}_name" class="reviewer_name">
346 366 ${self.gravatar_with_user(member.email, 16)}
347 367 </div>
348 368 <input type="hidden" name="__start__" value="reviewer:mapping">
349 369 <input type="hidden" name="__start__" value="reasons:sequence">
350 370 %for reason in reasons:
351 371 <div class="reviewer_reason">- ${reason}</div>
352 372 <input type="hidden" name="reason" value="${reason}">
353 373
354 374 %endfor
355 375 <input type="hidden" name="__end__" value="reasons:sequence">
356 376 <input id="reviewer_${member.user_id}_input" type="hidden" value="${member.user_id}" name="user_id" />
357 377 <input type="hidden" name="__end__" value="reviewer:mapping">
358 378 %if c.allowed_to_update:
359 379 <div class="reviewer_member_remove action_button" onclick="removeReviewMember(${member.user_id}, true)" style="visibility: hidden;">
360 380 <i class="icon-remove-sign" ></i>
361 381 </div>
362 382 %endif
363 383 </div>
364 384 </li>
365 385 %endfor
366 386 </ul>
367 387 <input type="hidden" name="__end__" value="review_members:sequence">
368 388 %if not c.pull_request.is_closed():
369 389 <div id="add_reviewer_input" class='ac' style="display: none;">
370 390 %if c.allowed_to_update:
371 391 <div class="reviewer_ac">
372 392 ${h.text('user', class_='ac-input', placeholder=_('Add reviewer'))}
373 393 <div id="reviewers_container"></div>
374 394 </div>
375 395 <div>
376 396 <span id="update_pull_request" class="btn btn-small">${_('Save Changes')}</span>
377 397 </div>
378 398 %endif
379 399 </div>
380 400 %endif
381 401 </div>
382 402 </div>
383 403 </div>
384 404 <div class="box">
385 405 ##DIFF
386 406 <div class="table" >
387 407 <div id="changeset_compare_view_content">
388 408 ##CS
389 409 % if c.missing_requirements:
390 410 <div class="box">
391 411 <div class="alert alert-warning">
392 412 <div>
393 413 <strong>${_('Missing requirements:')}</strong>
394 414 ${_('These commits cannot be displayed, because this repository uses the Mercurial largefiles extension, which was not enabled.')}
395 415 </div>
396 416 </div>
397 417 </div>
398 418 % elif c.missing_commits:
399 419 <div class="box">
400 420 <div class="alert alert-warning">
401 421 <div>
402 422 <strong>${_('Missing commits')}:</strong>
403 423 ${_('This pull request cannot be displayed, because one or more commits no longer exist in the source repository.')}
404 424 ${_('Please update this pull request, push the commits back into the source repository, or consider closing this pull request.')}
405 425 </div>
406 426 </div>
407 427 </div>
408 428 % endif
409 429 <div class="compare_view_commits_title">
410 430
411 431 <div class="pull-left">
412 432 <div class="btn-group">
413 433 <a
414 434 class="btn"
415 435 href="#"
416 436 onclick="$('.compare_select').show();$('.compare_select_hidden').hide(); return false">
417 437 ${ungettext('Expand %s commit','Expand %s commits', len(c.commit_ranges)) % len(c.commit_ranges)}
418 438 </a>
419 439 <a
420 440 class="btn"
421 441 href="#"
422 442 onclick="$('.compare_select').hide();$('.compare_select_hidden').show(); return false">
423 443 ${ungettext('Collapse %s commit','Collapse %s commits', len(c.commit_ranges)) % len(c.commit_ranges)}
424 444 </a>
425 445 </div>
426 446 </div>
427 447
428 448 <div class="pull-right">
429 449 % if c.allowed_to_update and not c.pull_request.is_closed():
430 450 <a id="update_commits" class="btn btn-primary pull-right">${_('Update commits')}</a>
431 451 % else:
432 452 <a class="tooltip btn disabled pull-right" disabled="disabled" title="${_('Update is disabled for current view')}">${_('Update commits')}</a>
433 453 % endif
434 454
435 455 </div>
436 456
437 457 </div>
438 458
439 459 % if not c.missing_commits:
440 460 <%include file="/compare/compare_commits.mako" />
441 461 <div class="cs_files">
442 462 <%namespace name="cbdiffs" file="/codeblocks/diffs.mako"/>
443 463 ${cbdiffs.render_diffset_menu()}
444 464 ${cbdiffs.render_diffset(
445 465 c.diffset, use_comments=True,
446 466 collapse_when_files_over=30,
447 467 disable_new_comments=not c.allowed_to_comment,
448 468 deleted_files_comments=c.deleted_files_comments)}
449 469 </div>
450 470 % else:
451 471 ## skipping commits we need to clear the view for missing commits
452 472 <div style="clear:both;"></div>
453 473 % endif
454 474
455 475 </div>
456 476 </div>
457 477
458 478 ## template for inline comment form
459 479 <%namespace name="comment" file="/changeset/changeset_file_comment.mako"/>
460 480
461 481 ## render general comments
462 ${comment.generate_comments(include_pull_request=True, is_pull_request=True)}
482
483 <div id="comment-tr-show">
484 <div class="comment">
485 <div class="meta">
486 % if general_outdated_comm_count_ver:
487 % if general_outdated_comm_count_ver == 1:
488 ${_('there is {num} general comment from older versions').format(num=general_outdated_comm_count_ver)},
489 <a href="#" onclick="$('.comment-general.comment-outdated').show(); $(this).parent().hide(); return false;">${_('show it')}</a>
490 % else:
491 ${_('there are {num} general comments from older versions').format(num=general_outdated_comm_count_ver)},
492 <a href="#" onclick="$('.comment-general.comment-outdated').show(); $(this).parent().hide(); return false;">${_('show them')}</a>
493 % endif
494 % endif
495 </div>
496 </div>
497 </div>
498
499 ${comment.generate_comments(c.comments, include_pull_request=True, is_pull_request=True)}
463 500
464 501 % if not c.pull_request.is_closed():
465 502 ## main comment form and it status
466 503 ${comment.comments(h.url('pullrequest_comment', repo_name=c.repo_name,
467 504 pull_request_id=c.pull_request.pull_request_id),
468 505 c.pull_request_review_status,
469 506 is_pull_request=True, change_status=c.allowed_to_change_status)}
470 507 %endif
471 508
472 509 <script type="text/javascript">
473 510 if (location.hash) {
474 511 var result = splitDelimitedHash(location.hash);
475 var line = $('html').find(result.loc);
512 var line = $('html').find(result.loc);
513 // show hidden comments if we use location.hash
514 if (line.hasClass('comment-general')) {
515 $(line).show();
516 } else if (line.hasClass('comment-inline')) {
517 $(line).show();
518 var $cb = $(line).closest('.cb');
519 $cb.removeClass('cb-collapsed')
520 }
476 521 if (line.length > 0){
477 522 offsetScroll(line, 70);
478 523 }
479 524 }
525
480 526 $(function(){
481 527 ReviewerAutoComplete('user');
482 528 // custom code mirror
483 529 var codeMirrorInstance = initPullRequestsCodeMirror('#pr-description-input');
484 530
485 531 var PRDetails = {
486 532 editButton: $('#open_edit_pullrequest'),
487 533 closeButton: $('#close_edit_pullrequest'),
488 534 deleteButton: $('#delete_pullrequest'),
489 535 viewFields: $('#pr-desc, #pr-title'),
490 536 editFields: $('#pr-desc-edit, #pr-title-edit, #pr-save'),
491 537
492 538 init: function() {
493 539 var that = this;
494 540 this.editButton.on('click', function(e) { that.edit(); });
495 541 this.closeButton.on('click', function(e) { that.view(); });
496 542 },
497 543
498 544 edit: function(event) {
499 545 this.viewFields.hide();
500 546 this.editButton.hide();
501 547 this.deleteButton.hide();
502 548 this.closeButton.show();
503 549 this.editFields.show();
504 550 codeMirrorInstance.refresh();
505 551 },
506 552
507 553 view: function(event) {
508 554 this.editButton.show();
509 555 this.deleteButton.show();
510 556 this.editFields.hide();
511 557 this.closeButton.hide();
512 558 this.viewFields.show();
513 559 }
514 560 };
515 561
516 562 var ReviewersPanel = {
517 563 editButton: $('#open_edit_reviewers'),
518 564 closeButton: $('#close_edit_reviewers'),
519 565 addButton: $('#add_reviewer_input'),
520 566 removeButtons: $('.reviewer_member_remove'),
521 567
522 568 init: function() {
523 569 var that = this;
524 570 this.editButton.on('click', function(e) { that.edit(); });
525 571 this.closeButton.on('click', function(e) { that.close(); });
526 572 },
527 573
528 574 edit: function(event) {
529 575 this.editButton.hide();
530 576 this.closeButton.show();
531 577 this.addButton.show();
532 578 this.removeButtons.css('visibility', 'visible');
533 579 },
534 580
535 581 close: function(event) {
536 582 this.editButton.show();
537 583 this.closeButton.hide();
538 584 this.addButton.hide();
539 585 this.removeButtons.css('visibility', 'hidden');
540 586 }
541 587 };
542 588
543 589 PRDetails.init();
544 590 ReviewersPanel.init();
545 591
546 592 showOutdated = function(self){
547 $('.comment-outdated').show();
593 $('.comment-inline.comment-outdated').show();
548 594 $('.filediff-outdated').show();
549 595 $('.showOutdatedComments').hide();
550 596 $('.hideOutdatedComments').show();
551
552 597 };
553 598
554 599 hideOutdated = function(self){
555 $('.comment-outdated').hide();
600 $('.comment-inline.comment-outdated').hide();
556 601 $('.filediff-outdated').hide();
557 602 $('.hideOutdatedComments').hide();
558 603 $('.showOutdatedComments').show();
559 604 };
560 605
561 606 $('#show-outdated-comments').on('click', function(e){
562 607 var button = $(this);
563 608 var outdated = $('.comment-outdated');
564 609
565 610 if (button.html() === "(Show)") {
566 611 button.html("(Hide)");
567 612 outdated.show();
568 613 } else {
569 614 button.html("(Show)");
570 615 outdated.hide();
571 616 }
572 617 });
573 618
574 619 $('.show-inline-comments').on('change', function(e){
575 620 var show = 'none';
576 621 var target = e.currentTarget;
577 622 if(target.checked){
578 623 show = ''
579 624 }
580 625 var boxid = $(target).attr('id_for');
581 626 var comments = $('#{0} .inline-comments'.format(boxid));
582 627 var fn_display = function(idx){
583 628 $(this).css('display', show);
584 629 };
585 630 $(comments).each(fn_display);
586 631 var btns = $('#{0} .inline-comments-button'.format(boxid));
587 632 $(btns).each(fn_display);
588 633 });
589 634
590 635 $('#merge_pull_request_form').submit(function() {
591 636 if (!$('#merge_pull_request').attr('disabled')) {
592 637 $('#merge_pull_request').attr('disabled', 'disabled');
593 638 }
594 639 return true;
595 640 });
596 641
597 642 $('#edit_pull_request').on('click', function(e){
598 643 var title = $('#pr-title-input').val();
599 644 var description = codeMirrorInstance.getValue();
600 645 editPullRequest(
601 646 "${c.repo_name}", "${c.pull_request.pull_request_id}",
602 647 title, description);
603 648 });
604 649
605 650 $('#update_pull_request').on('click', function(e){
606 651 updateReviewers(undefined, "${c.repo_name}", "${c.pull_request.pull_request_id}");
607 652 });
608 653
609 654 $('#update_commits').on('click', function(e){
610 655 var isDisabled = !$(e.currentTarget).attr('disabled');
611 656 $(e.currentTarget).text(_gettext('Updating...'));
612 657 $(e.currentTarget).attr('disabled', 'disabled');
613 658 if(isDisabled){
614 659 updateCommits("${c.repo_name}", "${c.pull_request.pull_request_id}");
615 660 }
616 661
617 662 });
618 663 // fixing issue with caches on firefox
619 664 $('#update_commits').removeAttr("disabled");
620 665
621 666 $('#close_pull_request').on('click', function(e){
622 667 closePullRequest("${c.repo_name}", "${c.pull_request.pull_request_id}");
623 668 });
624 669
625 670 $('.show-inline-comments').on('click', function(e){
626 671 var boxid = $(this).attr('data-comment-id');
627 672 var button = $(this);
628 673
629 674 if(button.hasClass("comments-visible")) {
630 675 $('#{0} .inline-comments'.format(boxid)).each(function(index){
631 676 $(this).hide();
632 677 });
633 678 button.removeClass("comments-visible");
634 679 } else {
635 680 $('#{0} .inline-comments'.format(boxid)).each(function(index){
636 681 $(this).show();
637 682 });
638 683 button.addClass("comments-visible");
639 684 }
640 685 });
641 686 })
642 687 </script>
643 688
644 689 </div>
645 690 </div>
646 691
647 692 </%def>
General Comments 0
You need to be logged in to leave comments. Login now