##// END OF EJS Templates
pull-requests: expose version browsing of pull requests....
marcink -
r1255:952cdf08 default
parent child Browse files
Show More
@@ -1,983 +1,1003 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2012-2016 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 import types
24 25
25 26 import peppercorn
26 27 import formencode
27 28 import logging
28 29
30
29 31 from webob.exc import HTTPNotFound, HTTPForbidden, HTTPBadRequest
30 32 from pylons import request, tmpl_context as c, url
31 33 from pylons.controllers.util import redirect
32 34 from pylons.i18n.translation import _
33 35 from pyramid.threadlocal import get_current_registry
34 36 from sqlalchemy.sql import func
35 37 from sqlalchemy.sql.expression import or_
36 38
37 39 from rhodecode import events
38 40 from rhodecode.lib import auth, diffs, helpers as h, codeblocks
39 41 from rhodecode.lib.ext_json import json
40 42 from rhodecode.lib.base import (
41 43 BaseRepoController, render, vcs_operation_context)
42 44 from rhodecode.lib.auth import (
43 45 LoginRequired, HasRepoPermissionAnyDecorator, NotAnonymous,
44 46 HasAcceptedRepoType, XHRRequired)
45 47 from rhodecode.lib.channelstream import channelstream_request
46 48 from rhodecode.lib.compat import OrderedDict
47 49 from rhodecode.lib.utils import jsonify
48 50 from rhodecode.lib.utils2 import (
49 safe_int, safe_str, str2bool, safe_unicode, StrictAttributeDict)
50 from rhodecode.lib.vcs.backends.base import EmptyCommit, UpdateFailureReason
51 safe_int, safe_str, str2bool, safe_unicode)
52 from rhodecode.lib.vcs.backends.base import (
53 EmptyCommit, UpdateFailureReason, EmptyRepository)
51 54 from rhodecode.lib.vcs.exceptions import (
52 55 EmptyRepositoryError, CommitDoesNotExistError, RepositoryRequirementError,
53 56 NodeDoesNotExistError)
54 57
55 58 from rhodecode.model.changeset_status import ChangesetStatusModel
56 59 from rhodecode.model.comment import ChangesetCommentsModel
57 60 from rhodecode.model.db import (PullRequest, ChangesetStatus, ChangesetComment,
58 61 Repository, PullRequestVersion)
59 62 from rhodecode.model.forms import PullRequestForm
60 63 from rhodecode.model.meta import Session
61 64 from rhodecode.model.pull_request import PullRequestModel
62 65
63 66 log = logging.getLogger(__name__)
64 67
65 68
66 69 class PullrequestsController(BaseRepoController):
67 70 def __before__(self):
68 71 super(PullrequestsController, self).__before__()
69 72
70 73 def _load_compare_data(self, pull_request, inline_comments, enable_comments=True):
71 74 """
72 75 Load context data needed for generating compare diff
73 76
74 77 :param pull_request: object related to the request
75 78 :param enable_comments: flag to determine if comments are included
76 79 """
77 80 source_repo = pull_request.source_repo
78 81 source_ref_id = pull_request.source_ref_parts.commit_id
79 82
80 83 target_repo = pull_request.target_repo
81 84 target_ref_id = pull_request.target_ref_parts.commit_id
82 85
83 86 # despite opening commits for bookmarks/branches/tags, we always
84 87 # convert this to rev to prevent changes after bookmark or branch change
85 88 c.source_ref_type = 'rev'
86 89 c.source_ref = source_ref_id
87 90
88 91 c.target_ref_type = 'rev'
89 92 c.target_ref = target_ref_id
90 93
91 94 c.source_repo = source_repo
92 95 c.target_repo = target_repo
93 96
94 97 c.fulldiff = bool(request.GET.get('fulldiff'))
95 98
96 99 # diff_limit is the old behavior, will cut off the whole diff
97 100 # if the limit is applied otherwise will just hide the
98 101 # big files from the front-end
99 102 diff_limit = self.cut_off_limit_diff
100 103 file_limit = self.cut_off_limit_file
101 104
102 105 pre_load = ["author", "branch", "date", "message"]
103 106
104 107 c.commit_ranges = []
105 108 source_commit = EmptyCommit()
106 109 target_commit = EmptyCommit()
107 110 c.missing_requirements = False
108 111 try:
109 112 c.commit_ranges = [
110 113 source_repo.get_commit(commit_id=rev, pre_load=pre_load)
111 114 for rev in pull_request.revisions]
112 115
113 116 c.statuses = source_repo.statuses(
114 117 [x.raw_id for x in c.commit_ranges])
115 118
116 119 target_commit = source_repo.get_commit(
117 120 commit_id=safe_str(target_ref_id))
118 121 source_commit = source_repo.get_commit(
119 122 commit_id=safe_str(source_ref_id))
120 123 except RepositoryRequirementError:
121 124 c.missing_requirements = True
122 125
123 126 c.changes = {}
124 127 c.missing_commits = False
125 128 if (c.missing_requirements or
126 129 isinstance(source_commit, EmptyCommit) or
127 130 source_commit == target_commit):
128 131 _parsed = []
129 132 c.missing_commits = True
130 133 else:
131 134 vcs_diff = PullRequestModel().get_diff(pull_request)
132 135 diff_processor = diffs.DiffProcessor(
133 136 vcs_diff, format='newdiff', diff_limit=diff_limit,
134 137 file_limit=file_limit, show_full_diff=c.fulldiff)
135 138 _parsed = diff_processor.prepare()
136 139
137 140 commit_changes = OrderedDict()
138 141 _parsed = diff_processor.prepare()
139 142 c.limited_diff = isinstance(_parsed, diffs.LimitedDiffContainer)
140 143
141 144 _parsed = diff_processor.prepare()
142 145
143 146 def _node_getter(commit):
144 147 def get_node(fname):
145 148 try:
146 149 return commit.get_node(fname)
147 150 except NodeDoesNotExistError:
148 151 return None
149 152 return get_node
150 153
151 154 c.diffset = codeblocks.DiffSet(
152 155 repo_name=c.repo_name,
153 156 source_repo_name=c.source_repo.repo_name,
154 157 source_node_getter=_node_getter(target_commit),
155 158 target_node_getter=_node_getter(source_commit),
156 159 comments=inline_comments
157 160 ).render_patchset(_parsed, target_commit.raw_id, source_commit.raw_id)
158 161
159 162 c.included_files = []
160 163 c.deleted_files = []
161 164
162 165 for f in _parsed:
163 166 st = f['stats']
164 167 fid = h.FID('', f['filename'])
165 168 c.included_files.append(f['filename'])
166 169
167 170 def _extract_ordering(self, request):
168 171 column_index = safe_int(request.GET.get('order[0][column]'))
169 172 order_dir = request.GET.get('order[0][dir]', 'desc')
170 173 order_by = request.GET.get(
171 174 'columns[%s][data][sort]' % column_index, 'name_raw')
172 175 return order_by, order_dir
173 176
174 177 @LoginRequired()
175 178 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
176 179 'repository.admin')
177 180 @HasAcceptedRepoType('git', 'hg')
178 181 def show_all(self, repo_name):
179 182 # filter types
180 183 c.active = 'open'
181 184 c.source = str2bool(request.GET.get('source'))
182 185 c.closed = str2bool(request.GET.get('closed'))
183 186 c.my = str2bool(request.GET.get('my'))
184 187 c.awaiting_review = str2bool(request.GET.get('awaiting_review'))
185 188 c.awaiting_my_review = str2bool(request.GET.get('awaiting_my_review'))
186 189 c.repo_name = repo_name
187 190
188 191 opened_by = None
189 192 if c.my:
190 193 c.active = 'my'
191 194 opened_by = [c.rhodecode_user.user_id]
192 195
193 196 statuses = [PullRequest.STATUS_NEW, PullRequest.STATUS_OPEN]
194 197 if c.closed:
195 198 c.active = 'closed'
196 199 statuses = [PullRequest.STATUS_CLOSED]
197 200
198 201 if c.awaiting_review and not c.source:
199 202 c.active = 'awaiting'
200 203 if c.source and not c.awaiting_review:
201 204 c.active = 'source'
202 205 if c.awaiting_my_review:
203 206 c.active = 'awaiting_my'
204 207
205 208 data = self._get_pull_requests_list(
206 209 repo_name=repo_name, opened_by=opened_by, statuses=statuses)
207 210 if not request.is_xhr:
208 211 c.data = json.dumps(data['data'])
209 212 c.records_total = data['recordsTotal']
210 213 return render('/pullrequests/pullrequests.html')
211 214 else:
212 215 return json.dumps(data)
213 216
214 217 def _get_pull_requests_list(self, repo_name, opened_by, statuses):
215 218 # pagination
216 219 start = safe_int(request.GET.get('start'), 0)
217 220 length = safe_int(request.GET.get('length'), c.visual.dashboard_items)
218 221 order_by, order_dir = self._extract_ordering(request)
219 222
220 223 if c.awaiting_review:
221 224 pull_requests = PullRequestModel().get_awaiting_review(
222 225 repo_name, source=c.source, opened_by=opened_by,
223 226 statuses=statuses, offset=start, length=length,
224 227 order_by=order_by, order_dir=order_dir)
225 228 pull_requests_total_count = PullRequestModel(
226 229 ).count_awaiting_review(
227 230 repo_name, source=c.source, statuses=statuses,
228 231 opened_by=opened_by)
229 232 elif c.awaiting_my_review:
230 233 pull_requests = PullRequestModel().get_awaiting_my_review(
231 234 repo_name, source=c.source, opened_by=opened_by,
232 235 user_id=c.rhodecode_user.user_id, statuses=statuses,
233 236 offset=start, length=length, order_by=order_by,
234 237 order_dir=order_dir)
235 238 pull_requests_total_count = PullRequestModel(
236 239 ).count_awaiting_my_review(
237 240 repo_name, source=c.source, user_id=c.rhodecode_user.user_id,
238 241 statuses=statuses, opened_by=opened_by)
239 242 else:
240 243 pull_requests = PullRequestModel().get_all(
241 244 repo_name, source=c.source, opened_by=opened_by,
242 245 statuses=statuses, offset=start, length=length,
243 246 order_by=order_by, order_dir=order_dir)
244 247 pull_requests_total_count = PullRequestModel().count_all(
245 248 repo_name, source=c.source, statuses=statuses,
246 249 opened_by=opened_by)
247 250
248 251 from rhodecode.lib.utils import PartialRenderer
249 252 _render = PartialRenderer('data_table/_dt_elements.html')
250 253 data = []
251 254 for pr in pull_requests:
252 255 comments = ChangesetCommentsModel().get_all_comments(
253 256 c.rhodecode_db_repo.repo_id, pull_request=pr)
254 257
255 258 data.append({
256 259 'name': _render('pullrequest_name',
257 260 pr.pull_request_id, pr.target_repo.repo_name),
258 261 'name_raw': pr.pull_request_id,
259 262 'status': _render('pullrequest_status',
260 263 pr.calculated_review_status()),
261 264 'title': _render(
262 265 'pullrequest_title', pr.title, pr.description),
263 266 'description': h.escape(pr.description),
264 267 'updated_on': _render('pullrequest_updated_on',
265 268 h.datetime_to_time(pr.updated_on)),
266 269 'updated_on_raw': h.datetime_to_time(pr.updated_on),
267 270 'created_on': _render('pullrequest_updated_on',
268 271 h.datetime_to_time(pr.created_on)),
269 272 'created_on_raw': h.datetime_to_time(pr.created_on),
270 273 'author': _render('pullrequest_author',
271 274 pr.author.full_contact, ),
272 275 'author_raw': pr.author.full_name,
273 276 'comments': _render('pullrequest_comments', len(comments)),
274 277 'comments_raw': len(comments),
275 278 'closed': pr.is_closed(),
276 279 })
277 280 # json used to render the grid
278 281 data = ({
279 282 'data': data,
280 283 'recordsTotal': pull_requests_total_count,
281 284 'recordsFiltered': pull_requests_total_count,
282 285 })
283 286 return data
284 287
285 288 @LoginRequired()
286 289 @NotAnonymous()
287 290 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
288 291 'repository.admin')
289 292 @HasAcceptedRepoType('git', 'hg')
290 293 def index(self):
291 294 source_repo = c.rhodecode_db_repo
292 295
293 296 try:
294 297 source_repo.scm_instance().get_commit()
295 298 except EmptyRepositoryError:
296 299 h.flash(h.literal(_('There are no commits yet')),
297 300 category='warning')
298 301 redirect(url('summary_home', repo_name=source_repo.repo_name))
299 302
300 303 commit_id = request.GET.get('commit')
301 304 branch_ref = request.GET.get('branch')
302 305 bookmark_ref = request.GET.get('bookmark')
303 306
304 307 try:
305 308 source_repo_data = PullRequestModel().generate_repo_data(
306 309 source_repo, commit_id=commit_id,
307 310 branch=branch_ref, bookmark=bookmark_ref)
308 311 except CommitDoesNotExistError as e:
309 312 log.exception(e)
310 313 h.flash(_('Commit does not exist'), 'error')
311 314 redirect(url('pullrequest_home', repo_name=source_repo.repo_name))
312 315
313 316 default_target_repo = source_repo
314 317
315 318 if source_repo.parent:
316 319 parent_vcs_obj = source_repo.parent.scm_instance()
317 320 if parent_vcs_obj and not parent_vcs_obj.is_empty():
318 321 # change default if we have a parent repo
319 322 default_target_repo = source_repo.parent
320 323
321 324 target_repo_data = PullRequestModel().generate_repo_data(
322 325 default_target_repo)
323 326
324 327 selected_source_ref = source_repo_data['refs']['selected_ref']
325 328
326 329 title_source_ref = selected_source_ref.split(':', 2)[1]
327 330 c.default_title = PullRequestModel().generate_pullrequest_title(
328 331 source=source_repo.repo_name,
329 332 source_ref=title_source_ref,
330 333 target=default_target_repo.repo_name
331 334 )
332 335
333 336 c.default_repo_data = {
334 337 'source_repo_name': source_repo.repo_name,
335 338 'source_refs_json': json.dumps(source_repo_data),
336 339 'target_repo_name': default_target_repo.repo_name,
337 340 'target_refs_json': json.dumps(target_repo_data),
338 341 }
339 342 c.default_source_ref = selected_source_ref
340 343
341 344 return render('/pullrequests/pullrequest.html')
342 345
343 346 @LoginRequired()
344 347 @NotAnonymous()
345 348 @XHRRequired()
346 349 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
347 350 'repository.admin')
348 351 @jsonify
349 352 def get_repo_refs(self, repo_name, target_repo_name):
350 353 repo = Repository.get_by_repo_name(target_repo_name)
351 354 if not repo:
352 355 raise HTTPNotFound
353 356 return PullRequestModel().generate_repo_data(repo)
354 357
355 358 @LoginRequired()
356 359 @NotAnonymous()
357 360 @XHRRequired()
358 361 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
359 362 'repository.admin')
360 363 @jsonify
361 364 def get_repo_destinations(self, repo_name):
362 365 repo = Repository.get_by_repo_name(repo_name)
363 366 if not repo:
364 367 raise HTTPNotFound
365 368 filter_query = request.GET.get('query')
366 369
367 370 query = Repository.query() \
368 371 .order_by(func.length(Repository.repo_name)) \
369 372 .filter(or_(
370 373 Repository.repo_name == repo.repo_name,
371 374 Repository.fork_id == repo.repo_id))
372 375
373 376 if filter_query:
374 377 ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
375 378 query = query.filter(
376 379 Repository.repo_name.ilike(ilike_expression))
377 380
378 381 add_parent = False
379 382 if repo.parent:
380 383 if filter_query in repo.parent.repo_name:
381 384 parent_vcs_obj = repo.parent.scm_instance()
382 385 if parent_vcs_obj and not parent_vcs_obj.is_empty():
383 386 add_parent = True
384 387
385 388 limit = 20 - 1 if add_parent else 20
386 389 all_repos = query.limit(limit).all()
387 390 if add_parent:
388 391 all_repos += [repo.parent]
389 392
390 393 repos = []
391 394 for obj in self.scm_model.get_repos(all_repos):
392 395 repos.append({
393 396 'id': obj['name'],
394 397 'text': obj['name'],
395 398 'type': 'repo',
396 399 'obj': obj['dbrepo']
397 400 })
398 401
399 402 data = {
400 403 'more': False,
401 404 'results': [{
402 405 'text': _('Repositories'),
403 406 'children': repos
404 407 }] if repos else []
405 408 }
406 409 return data
407 410
408 411 @LoginRequired()
409 412 @NotAnonymous()
410 413 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
411 414 'repository.admin')
412 415 @HasAcceptedRepoType('git', 'hg')
413 416 @auth.CSRFRequired()
414 417 def create(self, repo_name):
415 418 repo = Repository.get_by_repo_name(repo_name)
416 419 if not repo:
417 420 raise HTTPNotFound
418 421
419 422 controls = peppercorn.parse(request.POST.items())
420 423
421 424 try:
422 425 _form = PullRequestForm(repo.repo_id)().to_python(controls)
423 426 except formencode.Invalid as errors:
424 427 if errors.error_dict.get('revisions'):
425 428 msg = 'Revisions: %s' % errors.error_dict['revisions']
426 429 elif errors.error_dict.get('pullrequest_title'):
427 430 msg = _('Pull request requires a title with min. 3 chars')
428 431 else:
429 432 msg = _('Error creating pull request: {}').format(errors)
430 433 log.exception(msg)
431 434 h.flash(msg, 'error')
432 435
433 436 # would rather just go back to form ...
434 437 return redirect(url('pullrequest_home', repo_name=repo_name))
435 438
436 439 source_repo = _form['source_repo']
437 440 source_ref = _form['source_ref']
438 441 target_repo = _form['target_repo']
439 442 target_ref = _form['target_ref']
440 443 commit_ids = _form['revisions'][::-1]
441 444 reviewers = [
442 445 (r['user_id'], r['reasons']) for r in _form['review_members']]
443 446
444 447 # find the ancestor for this pr
445 448 source_db_repo = Repository.get_by_repo_name(_form['source_repo'])
446 449 target_db_repo = Repository.get_by_repo_name(_form['target_repo'])
447 450
448 451 source_scm = source_db_repo.scm_instance()
449 452 target_scm = target_db_repo.scm_instance()
450 453
451 454 source_commit = source_scm.get_commit(source_ref.split(':')[-1])
452 455 target_commit = target_scm.get_commit(target_ref.split(':')[-1])
453 456
454 457 ancestor = source_scm.get_common_ancestor(
455 458 source_commit.raw_id, target_commit.raw_id, target_scm)
456 459
457 460 target_ref_type, target_ref_name, __ = _form['target_ref'].split(':')
458 461 target_ref = ':'.join((target_ref_type, target_ref_name, ancestor))
459 462
460 463 pullrequest_title = _form['pullrequest_title']
461 464 title_source_ref = source_ref.split(':', 2)[1]
462 465 if not pullrequest_title:
463 466 pullrequest_title = PullRequestModel().generate_pullrequest_title(
464 467 source=source_repo,
465 468 source_ref=title_source_ref,
466 469 target=target_repo
467 470 )
468 471
469 472 description = _form['pullrequest_desc']
470 473 try:
471 474 pull_request = PullRequestModel().create(
472 475 c.rhodecode_user.user_id, source_repo, source_ref, target_repo,
473 476 target_ref, commit_ids, reviewers, pullrequest_title,
474 477 description
475 478 )
476 479 Session().commit()
477 480 h.flash(_('Successfully opened new pull request'),
478 481 category='success')
479 482 except Exception as e:
480 483 msg = _('Error occurred during sending pull request')
481 484 log.exception(msg)
482 485 h.flash(msg, category='error')
483 486 return redirect(url('pullrequest_home', repo_name=repo_name))
484 487
485 488 return redirect(url('pullrequest_show', repo_name=target_repo,
486 489 pull_request_id=pull_request.pull_request_id))
487 490
488 491 @LoginRequired()
489 492 @NotAnonymous()
490 493 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
491 494 'repository.admin')
492 495 @auth.CSRFRequired()
493 496 @jsonify
494 497 def update(self, repo_name, pull_request_id):
495 498 pull_request_id = safe_int(pull_request_id)
496 499 pull_request = PullRequest.get_or_404(pull_request_id)
497 500 # only owner or admin can update it
498 501 allowed_to_update = PullRequestModel().check_user_update(
499 502 pull_request, c.rhodecode_user)
500 503 if allowed_to_update:
501 504 controls = peppercorn.parse(request.POST.items())
502 505
503 506 if 'review_members' in controls:
504 507 self._update_reviewers(
505 508 pull_request_id, controls['review_members'])
506 509 elif str2bool(request.POST.get('update_commits', 'false')):
507 510 self._update_commits(pull_request)
508 511 elif str2bool(request.POST.get('close_pull_request', 'false')):
509 512 self._reject_close(pull_request)
510 513 elif str2bool(request.POST.get('edit_pull_request', 'false')):
511 514 self._edit_pull_request(pull_request)
512 515 else:
513 516 raise HTTPBadRequest()
514 517 return True
515 518 raise HTTPForbidden()
516 519
517 520 def _edit_pull_request(self, pull_request):
518 521 try:
519 522 PullRequestModel().edit(
520 523 pull_request, request.POST.get('title'),
521 524 request.POST.get('description'))
522 525 except ValueError:
523 526 msg = _(u'Cannot update closed pull requests.')
524 527 h.flash(msg, category='error')
525 528 return
526 529 else:
527 530 Session().commit()
528 531
529 532 msg = _(u'Pull request title & description updated.')
530 533 h.flash(msg, category='success')
531 534 return
532 535
533 536 def _update_commits(self, pull_request):
534 537 resp = PullRequestModel().update_commits(pull_request)
535 538
536 539 if resp.executed:
537 540 msg = _(
538 541 u'Pull request updated to "{source_commit_id}" with '
539 542 u'{count_added} added, {count_removed} removed commits.')
540 543 msg = msg.format(
541 544 source_commit_id=pull_request.source_ref_parts.commit_id,
542 545 count_added=len(resp.changes.added),
543 546 count_removed=len(resp.changes.removed))
544 547 h.flash(msg, category='success')
545 548
546 549 registry = get_current_registry()
547 550 rhodecode_plugins = getattr(registry, 'rhodecode_plugins', {})
548 551 channelstream_config = rhodecode_plugins.get('channelstream', {})
549 552 if channelstream_config.get('enabled'):
550 553 message = msg + (
551 554 ' - <a onclick="window.location.reload()">'
552 555 '<strong>{}</strong></a>'.format(_('Reload page')))
553 556 channel = '/repo${}$/pr/{}'.format(
554 557 pull_request.target_repo.repo_name,
555 558 pull_request.pull_request_id
556 559 )
557 560 payload = {
558 561 'type': 'message',
559 562 'user': 'system',
560 563 'exclude_users': [request.user.username],
561 564 'channel': channel,
562 565 'message': {
563 566 'message': message,
564 567 'level': 'success',
565 568 'topic': '/notifications'
566 569 }
567 570 }
568 571 channelstream_request(
569 572 channelstream_config, [payload], '/message',
570 573 raise_exc=False)
571 574 else:
572 575 msg = PullRequestModel.UPDATE_STATUS_MESSAGES[resp.reason]
573 576 warning_reasons = [
574 577 UpdateFailureReason.NO_CHANGE,
575 578 UpdateFailureReason.WRONG_REF_TPYE,
576 579 ]
577 580 category = 'warning' if resp.reason in warning_reasons else 'error'
578 581 h.flash(msg, category=category)
579 582
580 583 @auth.CSRFRequired()
581 584 @LoginRequired()
582 585 @NotAnonymous()
583 586 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
584 587 'repository.admin')
585 588 def merge(self, repo_name, pull_request_id):
586 589 """
587 590 POST /{repo_name}/pull-request/{pull_request_id}
588 591
589 592 Merge will perform a server-side merge of the specified
590 593 pull request, if the pull request is approved and mergeable.
591 594 After succesfull merging, the pull request is automatically
592 595 closed, with a relevant comment.
593 596 """
594 597 pull_request_id = safe_int(pull_request_id)
595 598 pull_request = PullRequest.get_or_404(pull_request_id)
596 599 user = c.rhodecode_user
597 600
598 601 if self._meets_merge_pre_conditions(pull_request, user):
599 602 log.debug("Pre-conditions checked, trying to merge.")
600 603 extras = vcs_operation_context(
601 604 request.environ, repo_name=pull_request.target_repo.repo_name,
602 605 username=user.username, action='push',
603 606 scm=pull_request.target_repo.repo_type)
604 607 self._merge_pull_request(pull_request, user, extras)
605 608
606 609 return redirect(url(
607 610 'pullrequest_show',
608 611 repo_name=pull_request.target_repo.repo_name,
609 612 pull_request_id=pull_request.pull_request_id))
610 613
611 614 def _meets_merge_pre_conditions(self, pull_request, user):
612 615 if not PullRequestModel().check_user_merge(pull_request, user):
613 616 raise HTTPForbidden()
614 617
615 618 merge_status, msg = PullRequestModel().merge_status(pull_request)
616 619 if not merge_status:
617 620 log.debug("Cannot merge, not mergeable.")
618 621 h.flash(msg, category='error')
619 622 return False
620 623
621 624 if (pull_request.calculated_review_status()
622 625 is not ChangesetStatus.STATUS_APPROVED):
623 626 log.debug("Cannot merge, approval is pending.")
624 627 msg = _('Pull request reviewer approval is pending.')
625 628 h.flash(msg, category='error')
626 629 return False
627 630 return True
628 631
629 632 def _merge_pull_request(self, pull_request, user, extras):
630 633 merge_resp = PullRequestModel().merge(
631 634 pull_request, user, extras=extras)
632 635
633 636 if merge_resp.executed:
634 637 log.debug("The merge was successful, closing the pull request.")
635 638 PullRequestModel().close_pull_request(
636 639 pull_request.pull_request_id, user)
637 640 Session().commit()
638 641 msg = _('Pull request was successfully merged and closed.')
639 642 h.flash(msg, category='success')
640 643 else:
641 644 log.debug(
642 645 "The merge was not successful. Merge response: %s",
643 646 merge_resp)
644 647 msg = PullRequestModel().merge_status_message(
645 648 merge_resp.failure_reason)
646 649 h.flash(msg, category='error')
647 650
648 651 def _update_reviewers(self, pull_request_id, review_members):
649 652 reviewers = [
650 653 (int(r['user_id']), r['reasons']) for r in review_members]
651 654 PullRequestModel().update_reviewers(pull_request_id, reviewers)
652 655 Session().commit()
653 656
654 657 def _reject_close(self, pull_request):
655 658 if pull_request.is_closed():
656 659 raise HTTPForbidden()
657 660
658 661 PullRequestModel().close_pull_request_with_comment(
659 662 pull_request, c.rhodecode_user, c.rhodecode_db_repo)
660 663 Session().commit()
661 664
662 665 @LoginRequired()
663 666 @NotAnonymous()
664 667 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
665 668 'repository.admin')
666 669 @auth.CSRFRequired()
667 670 @jsonify
668 671 def delete(self, repo_name, pull_request_id):
669 672 pull_request_id = safe_int(pull_request_id)
670 673 pull_request = PullRequest.get_or_404(pull_request_id)
671 674 # only owner can delete it !
672 675 if pull_request.author.user_id == c.rhodecode_user.user_id:
673 676 PullRequestModel().delete(pull_request)
674 677 Session().commit()
675 678 h.flash(_('Successfully deleted pull request'),
676 679 category='success')
677 680 return redirect(url('my_account_pullrequests'))
678 681 raise HTTPForbidden()
679 682
680 683 def _get_pr_version(self, pull_request_id, version=None):
681 684 pull_request_id = safe_int(pull_request_id)
682 685 at_version = None
683 if version:
686
687 if version and version == 'latest':
688 pull_request_ver = PullRequest.get(pull_request_id)
689 pull_request_obj = pull_request_ver
690 _org_pull_request_obj = pull_request_obj
691 at_version = 'latest'
692 elif version:
684 693 pull_request_ver = PullRequestVersion.get_or_404(version)
685 694 pull_request_obj = pull_request_ver
686 695 _org_pull_request_obj = pull_request_ver.pull_request
687 696 at_version = pull_request_ver.pull_request_version_id
688 697 else:
689 698 _org_pull_request_obj = pull_request_obj = PullRequest.get_or_404(pull_request_id)
690 699
691 class PullRequestDisplay(object):
692 """
693 Special object wrapper for showing PullRequest data via Versions
694 It mimics PR object as close as possible. This is read only object
695 just for display
696 """
697 def __init__(self, attrs):
698 self.attrs = attrs
699 # internal have priority over the given ones via attrs
700 self.internal = ['versions']
701
702 def __getattr__(self, item):
703 if item in self.internal:
704 return getattr(self, item)
705 try:
706 return self.attrs[item]
707 except KeyError:
708 raise AttributeError(
709 '%s object has no attribute %s' % (self, item))
710
711 def versions(self):
712 return pull_request_obj.versions.order_by(
713 PullRequestVersion.pull_request_version_id).all()
714
715 def is_closed(self):
716 return pull_request_obj.is_closed()
717
718 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
719
720 attrs.author = StrictAttributeDict(
721 pull_request_obj.author.get_api_data())
722 if pull_request_obj.target_repo:
723 attrs.target_repo = StrictAttributeDict(
724 pull_request_obj.target_repo.get_api_data())
725 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
726
727 if pull_request_obj.source_repo:
728 attrs.source_repo = StrictAttributeDict(
729 pull_request_obj.source_repo.get_api_data())
730 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
731
732 attrs.source_ref_parts = pull_request_obj.source_ref_parts
733 attrs.target_ref_parts = pull_request_obj.target_ref_parts
734
735 attrs.shadow_merge_ref = _org_pull_request_obj.shadow_merge_ref
736
737 pull_request_display_obj = PullRequestDisplay(attrs)
738
700 pull_request_display_obj = PullRequest.get_pr_display_object(
701 pull_request_obj, _org_pull_request_obj)
739 702 return _org_pull_request_obj, pull_request_obj, \
740 703 pull_request_display_obj, at_version
741 704
705 def _get_pr_version_changes(self, version, pull_request_latest):
706 """
707 Generate changes commits, and diff data based on the current pr version
708 """
709
710 #TODO(marcink): save those changes as JSON metadata for chaching later.
711
712 # fake the version to add the "initial" state object
713 pull_request_initial = PullRequest.get_pr_display_object(
714 pull_request_latest, pull_request_latest,
715 internal_methods=['get_commit', 'versions'])
716 pull_request_initial.revisions = []
717 pull_request_initial.source_repo.get_commit = types.MethodType(
718 lambda *a, **k: EmptyCommit(), pull_request_initial)
719 pull_request_initial.source_repo.scm_instance = types.MethodType(
720 lambda *a, **k: EmptyRepository(), pull_request_initial)
721
722 _changes_versions = [pull_request_latest] + \
723 list(reversed(c.versions)) + \
724 [pull_request_initial]
725
726 if version == 'latest':
727 index = 0
728 else:
729 for pos, prver in enumerate(_changes_versions):
730 ver = getattr(prver, 'pull_request_version_id', -1)
731 if ver == safe_int(version):
732 index = pos
733 break
734 else:
735 index = 0
736
737 cur_obj = _changes_versions[index]
738 prev_obj = _changes_versions[index + 1]
739
740 old_commit_ids = set(prev_obj.revisions)
741 new_commit_ids = set(cur_obj.revisions)
742
743 changes = PullRequestModel()._calculate_commit_id_changes(
744 old_commit_ids, new_commit_ids)
745
746 old_diff_data, new_diff_data = PullRequestModel()._generate_update_diffs(
747 cur_obj, prev_obj)
748 file_changes = PullRequestModel()._calculate_file_changes(
749 old_diff_data, new_diff_data)
750 return changes, file_changes
751
742 752 @LoginRequired()
743 753 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
744 754 'repository.admin')
745 755 def show(self, repo_name, pull_request_id):
746 756 pull_request_id = safe_int(pull_request_id)
747 757 version = request.GET.get('version')
748 758
749 759 (pull_request_latest,
750 760 pull_request_at_ver,
751 761 pull_request_display_obj,
752 762 at_version) = self._get_pr_version(pull_request_id, version=version)
753 763
754 764 c.template_context['pull_request_data']['pull_request_id'] = \
755 765 pull_request_id
756 766
757 767 # pull_requests repo_name we opened it against
758 768 # ie. target_repo must match
759 769 if repo_name != pull_request_at_ver.target_repo.repo_name:
760 770 raise HTTPNotFound
761 771
762 772 c.shadow_clone_url = PullRequestModel().get_shadow_clone_url(
763 773 pull_request_at_ver)
764 774
765 775 pr_closed = pull_request_latest.is_closed()
766 if at_version:
776 if at_version and not at_version == 'latest':
767 777 c.allowed_to_change_status = False
768 778 c.allowed_to_update = False
769 779 c.allowed_to_merge = False
770 780 c.allowed_to_delete = False
771 781 c.allowed_to_comment = False
772 782 else:
773 783 c.allowed_to_change_status = PullRequestModel(). \
774 784 check_user_change_status(pull_request_at_ver, c.rhodecode_user)
775 785 c.allowed_to_update = PullRequestModel().check_user_update(
776 786 pull_request_latest, c.rhodecode_user) and not pr_closed
777 787 c.allowed_to_merge = PullRequestModel().check_user_merge(
778 788 pull_request_latest, c.rhodecode_user) and not pr_closed
779 789 c.allowed_to_delete = PullRequestModel().check_user_delete(
780 790 pull_request_latest, c.rhodecode_user) and not pr_closed
781 791 c.allowed_to_comment = not pr_closed
782 792
783 793 cc_model = ChangesetCommentsModel()
784 794
785 795 c.pull_request_reviewers = pull_request_at_ver.reviewers_statuses()
786 796 c.pull_request_review_status = pull_request_at_ver.calculated_review_status()
787 797 c.pr_merge_status, c.pr_merge_msg = PullRequestModel().merge_status(
788 798 pull_request_at_ver)
789 799 c.approval_msg = None
790 800 if c.pull_request_review_status != ChangesetStatus.STATUS_APPROVED:
791 801 c.approval_msg = _('Reviewer approval is pending.')
792 802 c.pr_merge_status = False
793 803
794 804 # inline comments
795 805 c.inline_comments = cc_model.get_inline_comments(
796 806 c.rhodecode_db_repo.repo_id,
797 807 pull_request=pull_request_id)
798 808
799 809 c.inline_cnt = cc_model.get_inline_comments_count(
800 810 c.inline_comments, version=at_version)
801 811
802 812 # load compare data into template context
803 813 enable_comments = not pr_closed
804 814 self._load_compare_data(
805 815 pull_request_at_ver,
806 816 c.inline_comments, enable_comments=enable_comments)
807 817
808 818 # outdated comments
809 819 c.outdated_comments = {}
810 820 c.outdated_cnt = 0
811 821
812 822 if ChangesetCommentsModel.use_outdated_comments(pull_request_latest):
813 823 c.outdated_comments = cc_model.get_outdated_comments(
814 824 c.rhodecode_db_repo.repo_id,
815 825 pull_request=pull_request_at_ver)
816 826
817 827 # Count outdated comments and check for deleted files
818 828 for file_name, lines in c.outdated_comments.iteritems():
819 829 for comments in lines.values():
820 830 comments = [comm for comm in comments
821 831 if comm.outdated_at_version(at_version)]
822 832 c.outdated_cnt += len(comments)
823 833 if file_name not in c.included_files:
824 834 c.deleted_files.append(file_name)
825 835
826 836 # this is a hack to properly display links, when creating PR, the
827 837 # compare view and others uses different notation, and
828 838 # compare_commits.html renders links based on the target_repo.
829 839 # We need to swap that here to generate it properly on the html side
830 840 c.target_repo = c.source_repo
831 841
832 842 # comments
833 843 c.comments = cc_model.get_comments(c.rhodecode_db_repo.repo_id,
834 844 pull_request=pull_request_id)
835 845
836 846 if c.allowed_to_update:
837 847 force_close = ('forced_closed', _('Close Pull Request'))
838 848 statuses = ChangesetStatus.STATUSES + [force_close]
839 849 else:
840 850 statuses = ChangesetStatus.STATUSES
841 851 c.commit_statuses = statuses
842 852
843 c.ancestor = None # TODO: add ancestor here
853 c.ancestor = None # TODO: add ancestor here
844 854 c.pull_request = pull_request_display_obj
845 855 c.pull_request_latest = pull_request_latest
846 856 c.at_version = at_version
847 857
858 c.versions = pull_request_display_obj.versions()
859 c.changes = None
860 c.file_changes = None
861
862 c.show_version_changes = 1
863
864 if at_version and c.show_version_changes:
865 c.changes, c.file_changes = self._get_pr_version_changes(
866 version, pull_request_latest)
867
848 868 return render('/pullrequests/pullrequest_show.html')
849 869
850 870 @LoginRequired()
851 871 @NotAnonymous()
852 872 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
853 873 'repository.admin')
854 874 @auth.CSRFRequired()
855 875 @jsonify
856 876 def comment(self, repo_name, pull_request_id):
857 877 pull_request_id = safe_int(pull_request_id)
858 878 pull_request = PullRequest.get_or_404(pull_request_id)
859 879 if pull_request.is_closed():
860 880 raise HTTPForbidden()
861 881
862 882 # TODO: johbo: Re-think this bit, "approved_closed" does not exist
863 883 # as a changeset status, still we want to send it in one value.
864 884 status = request.POST.get('changeset_status', None)
865 885 text = request.POST.get('text')
866 886 if status and '_closed' in status:
867 887 close_pr = True
868 888 status = status.replace('_closed', '')
869 889 else:
870 890 close_pr = False
871 891
872 892 forced = (status == 'forced')
873 893 if forced:
874 894 status = 'rejected'
875 895
876 896 allowed_to_change_status = PullRequestModel().check_user_change_status(
877 897 pull_request, c.rhodecode_user)
878 898
879 899 if status and allowed_to_change_status:
880 900 message = (_('Status change %(transition_icon)s %(status)s')
881 901 % {'transition_icon': '>',
882 902 'status': ChangesetStatus.get_status_lbl(status)})
883 903 if close_pr:
884 904 message = _('Closing with') + ' ' + message
885 905 text = text or message
886 906 comm = ChangesetCommentsModel().create(
887 907 text=text,
888 908 repo=c.rhodecode_db_repo.repo_id,
889 909 user=c.rhodecode_user.user_id,
890 910 pull_request=pull_request_id,
891 911 f_path=request.POST.get('f_path'),
892 912 line_no=request.POST.get('line'),
893 913 status_change=(ChangesetStatus.get_status_lbl(status)
894 914 if status and allowed_to_change_status else None),
895 915 status_change_type=(status
896 916 if status and allowed_to_change_status else None),
897 917 closing_pr=close_pr
898 918 )
899 919
900 920 if allowed_to_change_status:
901 921 old_calculated_status = pull_request.calculated_review_status()
902 922 # get status if set !
903 923 if status:
904 924 ChangesetStatusModel().set_status(
905 925 c.rhodecode_db_repo.repo_id,
906 926 status,
907 927 c.rhodecode_user.user_id,
908 928 comm,
909 929 pull_request=pull_request_id
910 930 )
911 931
912 932 Session().flush()
913 933 events.trigger(events.PullRequestCommentEvent(pull_request, comm))
914 934 # we now calculate the status of pull request, and based on that
915 935 # calculation we set the commits status
916 936 calculated_status = pull_request.calculated_review_status()
917 937 if old_calculated_status != calculated_status:
918 938 PullRequestModel()._trigger_pull_request_hook(
919 939 pull_request, c.rhodecode_user, 'review_status_change')
920 940
921 941 calculated_status_lbl = ChangesetStatus.get_status_lbl(
922 942 calculated_status)
923 943
924 944 if close_pr:
925 945 status_completed = (
926 946 calculated_status in [ChangesetStatus.STATUS_APPROVED,
927 947 ChangesetStatus.STATUS_REJECTED])
928 948 if forced or status_completed:
929 949 PullRequestModel().close_pull_request(
930 950 pull_request_id, c.rhodecode_user)
931 951 else:
932 952 h.flash(_('Closing pull request on other statuses than '
933 953 'rejected or approved is forbidden. '
934 954 'Calculated status from all reviewers '
935 955 'is currently: %s') % calculated_status_lbl,
936 956 category='warning')
937 957
938 958 Session().commit()
939 959
940 960 if not request.is_xhr:
941 961 return redirect(h.url('pullrequest_show', repo_name=repo_name,
942 962 pull_request_id=pull_request_id))
943 963
944 964 data = {
945 965 'target_id': h.safeid(h.safe_unicode(request.POST.get('f_path'))),
946 966 }
947 967 if comm:
948 968 c.co = comm
949 969 data.update(comm.get_dict())
950 970 data.update({'rendered_text':
951 971 render('changeset/changeset_comment_block.html')})
952 972
953 973 return data
954 974
955 975 @LoginRequired()
956 976 @NotAnonymous()
957 977 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
958 978 'repository.admin')
959 979 @auth.CSRFRequired()
960 980 @jsonify
961 981 def delete_comment(self, repo_name, comment_id):
962 982 return self._delete_comment(comment_id)
963 983
964 984 def _delete_comment(self, comment_id):
965 985 comment_id = safe_int(comment_id)
966 986 co = ChangesetComment.get_or_404(comment_id)
967 987 if co.pull_request.is_closed():
968 988 # don't allow deleting comments on closed pull request
969 989 raise HTTPForbidden()
970 990
971 991 is_owner = co.author.user_id == c.rhodecode_user.user_id
972 992 is_repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name)
973 993 if h.HasPermissionAny('hg.admin')() or is_repo_admin or is_owner:
974 994 old_calculated_status = co.pull_request.calculated_review_status()
975 995 ChangesetCommentsModel().delete(comment=co)
976 996 Session().commit()
977 997 calculated_status = co.pull_request.calculated_review_status()
978 998 if old_calculated_status != calculated_status:
979 999 PullRequestModel()._trigger_pull_request_hook(
980 1000 co.pull_request, c.rhodecode_user, 'review_status_change')
981 1001 return True
982 1002 else:
983 1003 raise HTTPForbidden()
@@ -1,950 +1,951 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2016 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 """
23 23 Some simple helper functions
24 24 """
25 25
26 26
27 27 import collections
28 28 import datetime
29 29 import dateutil.relativedelta
30 30 import hashlib
31 31 import logging
32 32 import re
33 33 import sys
34 34 import time
35 35 import threading
36 36 import urllib
37 37 import urlobject
38 38 import uuid
39 39
40 40 import pygments.lexers
41 41 import sqlalchemy
42 42 import sqlalchemy.engine.url
43 43 import webob
44 44 import routes.util
45 45
46 46 import rhodecode
47 47
48 48
49 49 def md5(s):
50 50 return hashlib.md5(s).hexdigest()
51 51
52 52
53 53 def md5_safe(s):
54 54 return md5(safe_str(s))
55 55
56 56
57 57 def __get_lem(extra_mapping=None):
58 58 """
59 59 Get language extension map based on what's inside pygments lexers
60 60 """
61 61 d = collections.defaultdict(lambda: [])
62 62
63 63 def __clean(s):
64 64 s = s.lstrip('*')
65 65 s = s.lstrip('.')
66 66
67 67 if s.find('[') != -1:
68 68 exts = []
69 69 start, stop = s.find('['), s.find(']')
70 70
71 71 for suffix in s[start + 1:stop]:
72 72 exts.append(s[:s.find('[')] + suffix)
73 73 return [e.lower() for e in exts]
74 74 else:
75 75 return [s.lower()]
76 76
77 77 for lx, t in sorted(pygments.lexers.LEXERS.items()):
78 78 m = map(__clean, t[-2])
79 79 if m:
80 80 m = reduce(lambda x, y: x + y, m)
81 81 for ext in m:
82 82 desc = lx.replace('Lexer', '')
83 83 d[ext].append(desc)
84 84
85 85 data = dict(d)
86 86
87 87 extra_mapping = extra_mapping or {}
88 88 if extra_mapping:
89 89 for k, v in extra_mapping.items():
90 90 if k not in data:
91 91 # register new mapping2lexer
92 92 data[k] = [v]
93 93
94 94 return data
95 95
96 96
97 97 def str2bool(_str):
98 98 """
99 99 returns True/False value from given string, it tries to translate the
100 100 string into boolean
101 101
102 102 :param _str: string value to translate into boolean
103 103 :rtype: boolean
104 104 :returns: boolean from given string
105 105 """
106 106 if _str is None:
107 107 return False
108 108 if _str in (True, False):
109 109 return _str
110 110 _str = str(_str).strip().lower()
111 111 return _str in ('t', 'true', 'y', 'yes', 'on', '1')
112 112
113 113
114 114 def aslist(obj, sep=None, strip=True):
115 115 """
116 116 Returns given string separated by sep as list
117 117
118 118 :param obj:
119 119 :param sep:
120 120 :param strip:
121 121 """
122 122 if isinstance(obj, (basestring,)):
123 123 lst = obj.split(sep)
124 124 if strip:
125 125 lst = [v.strip() for v in lst]
126 126 return lst
127 127 elif isinstance(obj, (list, tuple)):
128 128 return obj
129 129 elif obj is None:
130 130 return []
131 131 else:
132 132 return [obj]
133 133
134 134
135 135 def convert_line_endings(line, mode):
136 136 """
137 137 Converts a given line "line end" accordingly to given mode
138 138
139 139 Available modes are::
140 140 0 - Unix
141 141 1 - Mac
142 142 2 - DOS
143 143
144 144 :param line: given line to convert
145 145 :param mode: mode to convert to
146 146 :rtype: str
147 147 :return: converted line according to mode
148 148 """
149 149 if mode == 0:
150 150 line = line.replace('\r\n', '\n')
151 151 line = line.replace('\r', '\n')
152 152 elif mode == 1:
153 153 line = line.replace('\r\n', '\r')
154 154 line = line.replace('\n', '\r')
155 155 elif mode == 2:
156 156 line = re.sub('\r(?!\n)|(?<!\r)\n', '\r\n', line)
157 157 return line
158 158
159 159
160 160 def detect_mode(line, default):
161 161 """
162 162 Detects line break for given line, if line break couldn't be found
163 163 given default value is returned
164 164
165 165 :param line: str line
166 166 :param default: default
167 167 :rtype: int
168 168 :return: value of line end on of 0 - Unix, 1 - Mac, 2 - DOS
169 169 """
170 170 if line.endswith('\r\n'):
171 171 return 2
172 172 elif line.endswith('\n'):
173 173 return 0
174 174 elif line.endswith('\r'):
175 175 return 1
176 176 else:
177 177 return default
178 178
179 179
180 180 def safe_int(val, default=None):
181 181 """
182 182 Returns int() of val if val is not convertable to int use default
183 183 instead
184 184
185 185 :param val:
186 186 :param default:
187 187 """
188 188
189 189 try:
190 190 val = int(val)
191 191 except (ValueError, TypeError):
192 192 val = default
193 193
194 194 return val
195 195
196 196
197 197 def safe_unicode(str_, from_encoding=None):
198 198 """
199 199 safe unicode function. Does few trick to turn str_ into unicode
200 200
201 201 In case of UnicodeDecode error, we try to return it with encoding detected
202 202 by chardet library if it fails fallback to unicode with errors replaced
203 203
204 204 :param str_: string to decode
205 205 :rtype: unicode
206 206 :returns: unicode object
207 207 """
208 208 if isinstance(str_, unicode):
209 209 return str_
210 210
211 211 if not from_encoding:
212 212 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
213 213 'utf8'), sep=',')
214 214 from_encoding = DEFAULT_ENCODINGS
215 215
216 216 if not isinstance(from_encoding, (list, tuple)):
217 217 from_encoding = [from_encoding]
218 218
219 219 try:
220 220 return unicode(str_)
221 221 except UnicodeDecodeError:
222 222 pass
223 223
224 224 for enc in from_encoding:
225 225 try:
226 226 return unicode(str_, enc)
227 227 except UnicodeDecodeError:
228 228 pass
229 229
230 230 try:
231 231 import chardet
232 232 encoding = chardet.detect(str_)['encoding']
233 233 if encoding is None:
234 234 raise Exception()
235 235 return str_.decode(encoding)
236 236 except (ImportError, UnicodeDecodeError, Exception):
237 237 return unicode(str_, from_encoding[0], 'replace')
238 238
239 239
240 240 def safe_str(unicode_, to_encoding=None):
241 241 """
242 242 safe str function. Does few trick to turn unicode_ into string
243 243
244 244 In case of UnicodeEncodeError, we try to return it with encoding detected
245 245 by chardet library if it fails fallback to string with errors replaced
246 246
247 247 :param unicode_: unicode to encode
248 248 :rtype: str
249 249 :returns: str object
250 250 """
251 251
252 252 # if it's not basestr cast to str
253 253 if not isinstance(unicode_, basestring):
254 254 return str(unicode_)
255 255
256 256 if isinstance(unicode_, str):
257 257 return unicode_
258 258
259 259 if not to_encoding:
260 260 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
261 261 'utf8'), sep=',')
262 262 to_encoding = DEFAULT_ENCODINGS
263 263
264 264 if not isinstance(to_encoding, (list, tuple)):
265 265 to_encoding = [to_encoding]
266 266
267 267 for enc in to_encoding:
268 268 try:
269 269 return unicode_.encode(enc)
270 270 except UnicodeEncodeError:
271 271 pass
272 272
273 273 try:
274 274 import chardet
275 275 encoding = chardet.detect(unicode_)['encoding']
276 276 if encoding is None:
277 277 raise UnicodeEncodeError()
278 278
279 279 return unicode_.encode(encoding)
280 280 except (ImportError, UnicodeEncodeError):
281 281 return unicode_.encode(to_encoding[0], 'replace')
282 282
283 283
284 284 def remove_suffix(s, suffix):
285 285 if s.endswith(suffix):
286 286 s = s[:-1 * len(suffix)]
287 287 return s
288 288
289 289
290 290 def remove_prefix(s, prefix):
291 291 if s.startswith(prefix):
292 292 s = s[len(prefix):]
293 293 return s
294 294
295 295
296 296 def find_calling_context(ignore_modules=None):
297 297 """
298 298 Look through the calling stack and return the frame which called
299 299 this function and is part of core module ( ie. rhodecode.* )
300 300
301 301 :param ignore_modules: list of modules to ignore eg. ['rhodecode.lib']
302 302 """
303 303
304 304 ignore_modules = ignore_modules or []
305 305
306 306 f = sys._getframe(2)
307 307 while f.f_back is not None:
308 308 name = f.f_globals.get('__name__')
309 309 if name and name.startswith(__name__.split('.')[0]):
310 310 if name not in ignore_modules:
311 311 return f
312 312 f = f.f_back
313 313 return None
314 314
315 315
316 316 def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs):
317 317 """Custom engine_from_config functions."""
318 318 log = logging.getLogger('sqlalchemy.engine')
319 319 engine = sqlalchemy.engine_from_config(configuration, prefix, **kwargs)
320 320
321 321 def color_sql(sql):
322 322 color_seq = '\033[1;33m' # This is yellow: code 33
323 323 normal = '\x1b[0m'
324 324 return ''.join([color_seq, sql, normal])
325 325
326 326 if configuration['debug']:
327 327 # attach events only for debug configuration
328 328
329 329 def before_cursor_execute(conn, cursor, statement,
330 330 parameters, context, executemany):
331 331 setattr(conn, 'query_start_time', time.time())
332 332 log.info(color_sql(">>>>> STARTING QUERY >>>>>"))
333 333 calling_context = find_calling_context(ignore_modules=[
334 334 'rhodecode.lib.caching_query',
335 335 'rhodecode.model.settings',
336 336 ])
337 337 if calling_context:
338 338 log.info(color_sql('call context %s:%s' % (
339 339 calling_context.f_code.co_filename,
340 340 calling_context.f_lineno,
341 341 )))
342 342
343 343 def after_cursor_execute(conn, cursor, statement,
344 344 parameters, context, executemany):
345 345 delattr(conn, 'query_start_time')
346 346
347 347 sqlalchemy.event.listen(engine, "before_cursor_execute",
348 348 before_cursor_execute)
349 349 sqlalchemy.event.listen(engine, "after_cursor_execute",
350 350 after_cursor_execute)
351 351
352 352 return engine
353 353
354 354
355 355 def get_encryption_key(config):
356 356 secret = config.get('rhodecode.encrypted_values.secret')
357 357 default = config['beaker.session.secret']
358 358 return secret or default
359 359
360 360
361 361 def age(prevdate, now=None, show_short_version=False, show_suffix=True,
362 362 short_format=False):
363 363 """
364 364 Turns a datetime into an age string.
365 365 If show_short_version is True, this generates a shorter string with
366 366 an approximate age; ex. '1 day ago', rather than '1 day and 23 hours ago'.
367 367
368 368 * IMPORTANT*
369 369 Code of this function is written in special way so it's easier to
370 370 backport it to javascript. If you mean to update it, please also update
371 371 `jquery.timeago-extension.js` file
372 372
373 373 :param prevdate: datetime object
374 374 :param now: get current time, if not define we use
375 375 `datetime.datetime.now()`
376 376 :param show_short_version: if it should approximate the date and
377 377 return a shorter string
378 378 :param show_suffix:
379 379 :param short_format: show short format, eg 2D instead of 2 days
380 380 :rtype: unicode
381 381 :returns: unicode words describing age
382 382 """
383 383 from pylons.i18n.translation import _, ungettext
384 384
385 385 def _get_relative_delta(now, prevdate):
386 386 base = dateutil.relativedelta.relativedelta(now, prevdate)
387 387 return {
388 388 'year': base.years,
389 389 'month': base.months,
390 390 'day': base.days,
391 391 'hour': base.hours,
392 392 'minute': base.minutes,
393 393 'second': base.seconds,
394 394 }
395 395
396 396 def _is_leap_year(year):
397 397 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
398 398
399 399 def get_month(prevdate):
400 400 return prevdate.month
401 401
402 402 def get_year(prevdate):
403 403 return prevdate.year
404 404
405 405 now = now or datetime.datetime.now()
406 406 order = ['year', 'month', 'day', 'hour', 'minute', 'second']
407 407 deltas = {}
408 408 future = False
409 409
410 410 if prevdate > now:
411 411 now_old = now
412 412 now = prevdate
413 413 prevdate = now_old
414 414 future = True
415 415 if future:
416 416 prevdate = prevdate.replace(microsecond=0)
417 417 # Get date parts deltas
418 418 for part in order:
419 419 rel_delta = _get_relative_delta(now, prevdate)
420 420 deltas[part] = rel_delta[part]
421 421
422 422 # Fix negative offsets (there is 1 second between 10:59:59 and 11:00:00,
423 423 # not 1 hour, -59 minutes and -59 seconds)
424 424 offsets = [[5, 60], [4, 60], [3, 24]]
425 425 for element in offsets: # seconds, minutes, hours
426 426 num = element[0]
427 427 length = element[1]
428 428
429 429 part = order[num]
430 430 carry_part = order[num - 1]
431 431
432 432 if deltas[part] < 0:
433 433 deltas[part] += length
434 434 deltas[carry_part] -= 1
435 435
436 436 # Same thing for days except that the increment depends on the (variable)
437 437 # number of days in the month
438 438 month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
439 439 if deltas['day'] < 0:
440 440 if get_month(prevdate) == 2 and _is_leap_year(get_year(prevdate)):
441 441 deltas['day'] += 29
442 442 else:
443 443 deltas['day'] += month_lengths[get_month(prevdate) - 1]
444 444
445 445 deltas['month'] -= 1
446 446
447 447 if deltas['month'] < 0:
448 448 deltas['month'] += 12
449 449 deltas['year'] -= 1
450 450
451 451 # Format the result
452 452 if short_format:
453 453 fmt_funcs = {
454 454 'year': lambda d: u'%dy' % d,
455 455 'month': lambda d: u'%dm' % d,
456 456 'day': lambda d: u'%dd' % d,
457 457 'hour': lambda d: u'%dh' % d,
458 458 'minute': lambda d: u'%dmin' % d,
459 459 'second': lambda d: u'%dsec' % d,
460 460 }
461 461 else:
462 462 fmt_funcs = {
463 463 'year': lambda d: ungettext(u'%d year', '%d years', d) % d,
464 464 'month': lambda d: ungettext(u'%d month', '%d months', d) % d,
465 465 'day': lambda d: ungettext(u'%d day', '%d days', d) % d,
466 466 'hour': lambda d: ungettext(u'%d hour', '%d hours', d) % d,
467 467 'minute': lambda d: ungettext(u'%d minute', '%d minutes', d) % d,
468 468 'second': lambda d: ungettext(u'%d second', '%d seconds', d) % d,
469 469 }
470 470
471 471 i = 0
472 472 for part in order:
473 473 value = deltas[part]
474 474 if value != 0:
475 475
476 476 if i < 5:
477 477 sub_part = order[i + 1]
478 478 sub_value = deltas[sub_part]
479 479 else:
480 480 sub_value = 0
481 481
482 482 if sub_value == 0 or show_short_version:
483 483 _val = fmt_funcs[part](value)
484 484 if future:
485 485 if show_suffix:
486 486 return _(u'in %s') % _val
487 487 else:
488 488 return _val
489 489
490 490 else:
491 491 if show_suffix:
492 492 return _(u'%s ago') % _val
493 493 else:
494 494 return _val
495 495
496 496 val = fmt_funcs[part](value)
497 497 val_detail = fmt_funcs[sub_part](sub_value)
498 498
499 499 if short_format:
500 500 datetime_tmpl = u'%s, %s'
501 501 if show_suffix:
502 502 datetime_tmpl = _(u'%s, %s ago')
503 503 if future:
504 504 datetime_tmpl = _(u'in %s, %s')
505 505 else:
506 506 datetime_tmpl = _(u'%s and %s')
507 507 if show_suffix:
508 508 datetime_tmpl = _(u'%s and %s ago')
509 509 if future:
510 510 datetime_tmpl = _(u'in %s and %s')
511 511
512 512 return datetime_tmpl % (val, val_detail)
513 513 i += 1
514 514 return _(u'just now')
515 515
516 516
517 517 def uri_filter(uri):
518 518 """
519 519 Removes user:password from given url string
520 520
521 521 :param uri:
522 522 :rtype: unicode
523 523 :returns: filtered list of strings
524 524 """
525 525 if not uri:
526 526 return ''
527 527
528 528 proto = ''
529 529
530 530 for pat in ('https://', 'http://'):
531 531 if uri.startswith(pat):
532 532 uri = uri[len(pat):]
533 533 proto = pat
534 534 break
535 535
536 536 # remove passwords and username
537 537 uri = uri[uri.find('@') + 1:]
538 538
539 539 # get the port
540 540 cred_pos = uri.find(':')
541 541 if cred_pos == -1:
542 542 host, port = uri, None
543 543 else:
544 544 host, port = uri[:cred_pos], uri[cred_pos + 1:]
545 545
546 546 return filter(None, [proto, host, port])
547 547
548 548
549 549 def credentials_filter(uri):
550 550 """
551 551 Returns a url with removed credentials
552 552
553 553 :param uri:
554 554 """
555 555
556 556 uri = uri_filter(uri)
557 557 # check if we have port
558 558 if len(uri) > 2 and uri[2]:
559 559 uri[2] = ':' + uri[2]
560 560
561 561 return ''.join(uri)
562 562
563 563
564 564 def get_clone_url(uri_tmpl, qualifed_home_url, repo_name, repo_id, **override):
565 565 parsed_url = urlobject.URLObject(qualifed_home_url)
566 566 decoded_path = safe_unicode(urllib.unquote(parsed_url.path.rstrip('/')))
567 567 args = {
568 568 'scheme': parsed_url.scheme,
569 569 'user': '',
570 570 # path if we use proxy-prefix
571 571 'netloc': parsed_url.netloc+decoded_path,
572 572 'prefix': decoded_path,
573 573 'repo': repo_name,
574 574 'repoid': str(repo_id)
575 575 }
576 576 args.update(override)
577 577 args['user'] = urllib.quote(safe_str(args['user']))
578 578
579 579 for k, v in args.items():
580 580 uri_tmpl = uri_tmpl.replace('{%s}' % k, v)
581 581
582 582 # remove leading @ sign if it's present. Case of empty user
583 583 url_obj = urlobject.URLObject(uri_tmpl)
584 584 url = url_obj.with_netloc(url_obj.netloc.lstrip('@'))
585 585
586 586 return safe_unicode(url)
587 587
588 588
589 589 def get_commit_safe(repo, commit_id=None, commit_idx=None, pre_load=None):
590 590 """
591 591 Safe version of get_commit if this commit doesn't exists for a
592 592 repository it returns a Dummy one instead
593 593
594 594 :param repo: repository instance
595 595 :param commit_id: commit id as str
596 596 :param pre_load: optional list of commit attributes to load
597 597 """
598 598 # TODO(skreft): remove these circular imports
599 599 from rhodecode.lib.vcs.backends.base import BaseRepository, EmptyCommit
600 600 from rhodecode.lib.vcs.exceptions import RepositoryError
601 601 if not isinstance(repo, BaseRepository):
602 602 raise Exception('You must pass an Repository '
603 603 'object as first argument got %s', type(repo))
604 604
605 605 try:
606 606 commit = repo.get_commit(
607 607 commit_id=commit_id, commit_idx=commit_idx, pre_load=pre_load)
608 608 except (RepositoryError, LookupError):
609 609 commit = EmptyCommit()
610 610 return commit
611 611
612 612
613 613 def datetime_to_time(dt):
614 614 if dt:
615 615 return time.mktime(dt.timetuple())
616 616
617 617
618 618 def time_to_datetime(tm):
619 619 if tm:
620 620 if isinstance(tm, basestring):
621 621 try:
622 622 tm = float(tm)
623 623 except ValueError:
624 624 return
625 625 return datetime.datetime.fromtimestamp(tm)
626 626
627 627
628 628 def time_to_utcdatetime(tm):
629 629 if tm:
630 630 if isinstance(tm, basestring):
631 631 try:
632 632 tm = float(tm)
633 633 except ValueError:
634 634 return
635 635 return datetime.datetime.utcfromtimestamp(tm)
636 636
637 637
638 638 MENTIONS_REGEX = re.compile(
639 639 # ^@ or @ without any special chars in front
640 640 r'(?:^@|[^a-zA-Z0-9\-\_\.]@)'
641 641 # main body starts with letter, then can be . - _
642 642 r'([a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+)',
643 643 re.VERBOSE | re.MULTILINE)
644 644
645 645
646 646 def extract_mentioned_users(s):
647 647 """
648 648 Returns unique usernames from given string s that have @mention
649 649
650 650 :param s: string to get mentions
651 651 """
652 652 usrs = set()
653 653 for username in MENTIONS_REGEX.findall(s):
654 654 usrs.add(username)
655 655
656 656 return sorted(list(usrs), key=lambda k: k.lower())
657 657
658 658
659 659 class StrictAttributeDict(dict):
660 660 """
661 661 Strict Version of Attribute dict which raises an Attribute error when
662 662 requested attribute is not set
663 663 """
664 664 def __getattr__(self, attr):
665 665 try:
666 666 return self[attr]
667 667 except KeyError:
668 raise AttributeError('%s object has no attribute %s' % (self, attr))
668 raise AttributeError('%s object has no attribute %s' % (
669 self.__class__, attr))
669 670 __setattr__ = dict.__setitem__
670 671 __delattr__ = dict.__delitem__
671 672
672 673
673 674 class AttributeDict(dict):
674 675 def __getattr__(self, attr):
675 676 return self.get(attr, None)
676 677 __setattr__ = dict.__setitem__
677 678 __delattr__ = dict.__delitem__
678 679
679 680
680 681 def fix_PATH(os_=None):
681 682 """
682 683 Get current active python path, and append it to PATH variable to fix
683 684 issues of subprocess calls and different python versions
684 685 """
685 686 if os_ is None:
686 687 import os
687 688 else:
688 689 os = os_
689 690
690 691 cur_path = os.path.split(sys.executable)[0]
691 692 if not os.environ['PATH'].startswith(cur_path):
692 693 os.environ['PATH'] = '%s:%s' % (cur_path, os.environ['PATH'])
693 694
694 695
695 696 def obfuscate_url_pw(engine):
696 697 _url = engine or ''
697 698 try:
698 699 _url = sqlalchemy.engine.url.make_url(engine)
699 700 if _url.password:
700 701 _url.password = 'XXXXX'
701 702 except Exception:
702 703 pass
703 704 return unicode(_url)
704 705
705 706
706 707 def get_server_url(environ):
707 708 req = webob.Request(environ)
708 709 return req.host_url + req.script_name
709 710
710 711
711 712 def unique_id(hexlen=32):
712 713 alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz"
713 714 return suuid(truncate_to=hexlen, alphabet=alphabet)
714 715
715 716
716 717 def suuid(url=None, truncate_to=22, alphabet=None):
717 718 """
718 719 Generate and return a short URL safe UUID.
719 720
720 721 If the url parameter is provided, set the namespace to the provided
721 722 URL and generate a UUID.
722 723
723 724 :param url to get the uuid for
724 725 :truncate_to: truncate the basic 22 UUID to shorter version
725 726
726 727 The IDs won't be universally unique any longer, but the probability of
727 728 a collision will still be very low.
728 729 """
729 730 # Define our alphabet.
730 731 _ALPHABET = alphabet or "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
731 732
732 733 # If no URL is given, generate a random UUID.
733 734 if url is None:
734 735 unique_id = uuid.uuid4().int
735 736 else:
736 737 unique_id = uuid.uuid3(uuid.NAMESPACE_URL, url).int
737 738
738 739 alphabet_length = len(_ALPHABET)
739 740 output = []
740 741 while unique_id > 0:
741 742 digit = unique_id % alphabet_length
742 743 output.append(_ALPHABET[digit])
743 744 unique_id = int(unique_id / alphabet_length)
744 745 return "".join(output)[:truncate_to]
745 746
746 747
747 748 def get_current_rhodecode_user():
748 749 """
749 750 Gets rhodecode user from threadlocal tmpl_context variable if it's
750 751 defined, else returns None.
751 752 """
752 753 from pylons import tmpl_context as c
753 754 if hasattr(c, 'rhodecode_user'):
754 755 return c.rhodecode_user
755 756
756 757 return None
757 758
758 759
759 760 def action_logger_generic(action, namespace=''):
760 761 """
761 762 A generic logger for actions useful to the system overview, tries to find
762 763 an acting user for the context of the call otherwise reports unknown user
763 764
764 765 :param action: logging message eg 'comment 5 deleted'
765 766 :param type: string
766 767
767 768 :param namespace: namespace of the logging message eg. 'repo.comments'
768 769 :param type: string
769 770
770 771 """
771 772
772 773 logger_name = 'rhodecode.actions'
773 774
774 775 if namespace:
775 776 logger_name += '.' + namespace
776 777
777 778 log = logging.getLogger(logger_name)
778 779
779 780 # get a user if we can
780 781 user = get_current_rhodecode_user()
781 782
782 783 logfunc = log.info
783 784
784 785 if not user:
785 786 user = '<unknown user>'
786 787 logfunc = log.warning
787 788
788 789 logfunc('Logging action by {}: {}'.format(user, action))
789 790
790 791
791 792 def escape_split(text, sep=',', maxsplit=-1):
792 793 r"""
793 794 Allows for escaping of the separator: e.g. arg='foo\, bar'
794 795
795 796 It should be noted that the way bash et. al. do command line parsing, those
796 797 single quotes are required.
797 798 """
798 799 escaped_sep = r'\%s' % sep
799 800
800 801 if escaped_sep not in text:
801 802 return text.split(sep, maxsplit)
802 803
803 804 before, _mid, after = text.partition(escaped_sep)
804 805 startlist = before.split(sep, maxsplit) # a regular split is fine here
805 806 unfinished = startlist[-1]
806 807 startlist = startlist[:-1]
807 808
808 809 # recurse because there may be more escaped separators
809 810 endlist = escape_split(after, sep, maxsplit)
810 811
811 812 # finish building the escaped value. we use endlist[0] becaue the first
812 813 # part of the string sent in recursion is the rest of the escaped value.
813 814 unfinished += sep + endlist[0]
814 815
815 816 return startlist + [unfinished] + endlist[1:] # put together all the parts
816 817
817 818
818 819 class OptionalAttr(object):
819 820 """
820 821 Special Optional Option that defines other attribute. Example::
821 822
822 823 def test(apiuser, userid=Optional(OAttr('apiuser')):
823 824 user = Optional.extract(userid)
824 825 # calls
825 826
826 827 """
827 828
828 829 def __init__(self, attr_name):
829 830 self.attr_name = attr_name
830 831
831 832 def __repr__(self):
832 833 return '<OptionalAttr:%s>' % self.attr_name
833 834
834 835 def __call__(self):
835 836 return self
836 837
837 838
838 839 # alias
839 840 OAttr = OptionalAttr
840 841
841 842
842 843 class Optional(object):
843 844 """
844 845 Defines an optional parameter::
845 846
846 847 param = param.getval() if isinstance(param, Optional) else param
847 848 param = param() if isinstance(param, Optional) else param
848 849
849 850 is equivalent of::
850 851
851 852 param = Optional.extract(param)
852 853
853 854 """
854 855
855 856 def __init__(self, type_):
856 857 self.type_ = type_
857 858
858 859 def __repr__(self):
859 860 return '<Optional:%s>' % self.type_.__repr__()
860 861
861 862 def __call__(self):
862 863 return self.getval()
863 864
864 865 def getval(self):
865 866 """
866 867 returns value from this Optional instance
867 868 """
868 869 if isinstance(self.type_, OAttr):
869 870 # use params name
870 871 return self.type_.attr_name
871 872 return self.type_
872 873
873 874 @classmethod
874 875 def extract(cls, val):
875 876 """
876 877 Extracts value from Optional() instance
877 878
878 879 :param val:
879 880 :return: original value if it's not Optional instance else
880 881 value of instance
881 882 """
882 883 if isinstance(val, cls):
883 884 return val.getval()
884 885 return val
885 886
886 887
887 888 def get_routes_generator_for_server_url(server_url):
888 889 parsed_url = urlobject.URLObject(server_url)
889 890 netloc = safe_str(parsed_url.netloc)
890 891 script_name = safe_str(parsed_url.path)
891 892
892 893 if ':' in netloc:
893 894 server_name, server_port = netloc.split(':')
894 895 else:
895 896 server_name = netloc
896 897 server_port = (parsed_url.scheme == 'https' and '443' or '80')
897 898
898 899 environ = {
899 900 'REQUEST_METHOD': 'GET',
900 901 'PATH_INFO': '/',
901 902 'SERVER_NAME': server_name,
902 903 'SERVER_PORT': server_port,
903 904 'SCRIPT_NAME': script_name,
904 905 }
905 906 if parsed_url.scheme == 'https':
906 907 environ['HTTPS'] = 'on'
907 908 environ['wsgi.url_scheme'] = 'https'
908 909
909 910 return routes.util.URLGenerator(rhodecode.CONFIG['routes.map'], environ)
910 911
911 912
912 913 def glob2re(pat):
913 914 """
914 915 Translate a shell PATTERN to a regular expression.
915 916
916 917 There is no way to quote meta-characters.
917 918 """
918 919
919 920 i, n = 0, len(pat)
920 921 res = ''
921 922 while i < n:
922 923 c = pat[i]
923 924 i = i+1
924 925 if c == '*':
925 926 #res = res + '.*'
926 927 res = res + '[^/]*'
927 928 elif c == '?':
928 929 #res = res + '.'
929 930 res = res + '[^/]'
930 931 elif c == '[':
931 932 j = i
932 933 if j < n and pat[j] == '!':
933 934 j = j+1
934 935 if j < n and pat[j] == ']':
935 936 j = j+1
936 937 while j < n and pat[j] != ']':
937 938 j = j+1
938 939 if j >= n:
939 940 res = res + '\\['
940 941 else:
941 942 stuff = pat[i:j].replace('\\','\\\\')
942 943 i = j+1
943 944 if stuff[0] == '!':
944 945 stuff = '^' + stuff[1:]
945 946 elif stuff[0] == '^':
946 947 stuff = '\\' + stuff
947 948 res = '%s[%s]' % (res, stuff)
948 949 else:
949 950 res = res + re.escape(c)
950 951 return res + '\Z(?ms)'
@@ -1,1567 +1,1576 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2014-2016 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Base module for all VCS systems
23 23 """
24 24
25 25 import collections
26 26 import datetime
27 27 import itertools
28 28 import logging
29 29 import os
30 30 import time
31 31 import warnings
32 32
33 33 from zope.cachedescriptors.property import Lazy as LazyProperty
34 34
35 35 from rhodecode.lib.utils2 import safe_str, safe_unicode
36 36 from rhodecode.lib.vcs import connection
37 37 from rhodecode.lib.vcs.utils import author_name, author_email
38 38 from rhodecode.lib.vcs.conf import settings
39 39 from rhodecode.lib.vcs.exceptions import (
40 40 CommitError, EmptyRepositoryError, NodeAlreadyAddedError,
41 41 NodeAlreadyChangedError, NodeAlreadyExistsError, NodeAlreadyRemovedError,
42 42 NodeDoesNotExistError, NodeNotChangedError, VCSError,
43 43 ImproperArchiveTypeError, BranchDoesNotExistError, CommitDoesNotExistError,
44 44 RepositoryError)
45 45
46 46
47 47 log = logging.getLogger(__name__)
48 48
49 49
50 50 FILEMODE_DEFAULT = 0100644
51 51 FILEMODE_EXECUTABLE = 0100755
52 52
53 53 Reference = collections.namedtuple('Reference', ('type', 'name', 'commit_id'))
54 54 MergeResponse = collections.namedtuple(
55 55 'MergeResponse',
56 56 ('possible', 'executed', 'merge_ref', 'failure_reason'))
57 57
58 58
59 59 class MergeFailureReason(object):
60 60 """
61 61 Enumeration with all the reasons why the server side merge could fail.
62 62
63 63 DO NOT change the number of the reasons, as they may be stored in the
64 64 database.
65 65
66 66 Changing the name of a reason is acceptable and encouraged to deprecate old
67 67 reasons.
68 68 """
69 69
70 70 # Everything went well.
71 71 NONE = 0
72 72
73 73 # An unexpected exception was raised. Check the logs for more details.
74 74 UNKNOWN = 1
75 75
76 76 # The merge was not successful, there are conflicts.
77 77 MERGE_FAILED = 2
78 78
79 79 # The merge succeeded but we could not push it to the target repository.
80 80 PUSH_FAILED = 3
81 81
82 82 # The specified target is not a head in the target repository.
83 83 TARGET_IS_NOT_HEAD = 4
84 84
85 85 # The source repository contains more branches than the target. Pushing
86 86 # the merge will create additional branches in the target.
87 87 HG_SOURCE_HAS_MORE_BRANCHES = 5
88 88
89 89 # The target reference has multiple heads. That does not allow to correctly
90 90 # identify the target location. This could only happen for mercurial
91 91 # branches.
92 92 HG_TARGET_HAS_MULTIPLE_HEADS = 6
93 93
94 94 # The target repository is locked
95 95 TARGET_IS_LOCKED = 7
96 96
97 97 # Deprecated, use MISSING_TARGET_REF or MISSING_SOURCE_REF instead.
98 98 # A involved commit could not be found.
99 99 _DEPRECATED_MISSING_COMMIT = 8
100 100
101 101 # The target repo reference is missing.
102 102 MISSING_TARGET_REF = 9
103 103
104 104 # The source repo reference is missing.
105 105 MISSING_SOURCE_REF = 10
106 106
107 107 # The merge was not successful, there are conflicts related to sub
108 108 # repositories.
109 109 SUBREPO_MERGE_FAILED = 11
110 110
111 111
112 112 class UpdateFailureReason(object):
113 113 """
114 114 Enumeration with all the reasons why the pull request update could fail.
115 115
116 116 DO NOT change the number of the reasons, as they may be stored in the
117 117 database.
118 118
119 119 Changing the name of a reason is acceptable and encouraged to deprecate old
120 120 reasons.
121 121 """
122 122
123 123 # Everything went well.
124 124 NONE = 0
125 125
126 126 # An unexpected exception was raised. Check the logs for more details.
127 127 UNKNOWN = 1
128 128
129 129 # The pull request is up to date.
130 130 NO_CHANGE = 2
131 131
132 132 # The pull request has a reference type that is not supported for update.
133 133 WRONG_REF_TPYE = 3
134 134
135 135 # Update failed because the target reference is missing.
136 136 MISSING_TARGET_REF = 4
137 137
138 138 # Update failed because the source reference is missing.
139 139 MISSING_SOURCE_REF = 5
140 140
141 141
142 142 class BaseRepository(object):
143 143 """
144 144 Base Repository for final backends
145 145
146 146 .. attribute:: DEFAULT_BRANCH_NAME
147 147
148 148 name of default branch (i.e. "trunk" for svn, "master" for git etc.
149 149
150 150 .. attribute:: commit_ids
151 151
152 152 list of all available commit ids, in ascending order
153 153
154 154 .. attribute:: path
155 155
156 156 absolute path to the repository
157 157
158 158 .. attribute:: bookmarks
159 159
160 160 Mapping from name to :term:`Commit ID` of the bookmark. Empty in case
161 161 there are no bookmarks or the backend implementation does not support
162 162 bookmarks.
163 163
164 164 .. attribute:: tags
165 165
166 166 Mapping from name to :term:`Commit ID` of the tag.
167 167
168 168 """
169 169
170 170 DEFAULT_BRANCH_NAME = None
171 171 DEFAULT_CONTACT = u"Unknown"
172 172 DEFAULT_DESCRIPTION = u"unknown"
173 173 EMPTY_COMMIT_ID = '0' * 40
174 174
175 175 path = None
176 176
177 177 def __init__(self, repo_path, config=None, create=False, **kwargs):
178 178 """
179 179 Initializes repository. Raises RepositoryError if repository could
180 180 not be find at the given ``repo_path`` or directory at ``repo_path``
181 181 exists and ``create`` is set to True.
182 182
183 183 :param repo_path: local path of the repository
184 184 :param config: repository configuration
185 185 :param create=False: if set to True, would try to create repository.
186 186 :param src_url=None: if set, should be proper url from which repository
187 187 would be cloned; requires ``create`` parameter to be set to True -
188 188 raises RepositoryError if src_url is set and create evaluates to
189 189 False
190 190 """
191 191 raise NotImplementedError
192 192
193 193 def __repr__(self):
194 194 return '<%s at %s>' % (self.__class__.__name__, self.path)
195 195
196 196 def __len__(self):
197 197 return self.count()
198 198
199 199 def __eq__(self, other):
200 200 same_instance = isinstance(other, self.__class__)
201 201 return same_instance and other.path == self.path
202 202
203 203 def __ne__(self, other):
204 204 return not self.__eq__(other)
205 205
206 206 @LazyProperty
207 207 def EMPTY_COMMIT(self):
208 208 return EmptyCommit(self.EMPTY_COMMIT_ID)
209 209
210 210 @LazyProperty
211 211 def alias(self):
212 212 for k, v in settings.BACKENDS.items():
213 213 if v.split('.')[-1] == str(self.__class__.__name__):
214 214 return k
215 215
216 216 @LazyProperty
217 217 def name(self):
218 218 return safe_unicode(os.path.basename(self.path))
219 219
220 220 @LazyProperty
221 221 def description(self):
222 222 raise NotImplementedError
223 223
224 224 def refs(self):
225 225 """
226 226 returns a `dict` with branches, bookmarks, tags, and closed_branches
227 227 for this repository
228 228 """
229 229 return dict(
230 230 branches=self.branches,
231 231 branches_closed=self.branches_closed,
232 232 tags=self.tags,
233 233 bookmarks=self.bookmarks
234 234 )
235 235
236 236 @LazyProperty
237 237 def branches(self):
238 238 """
239 239 A `dict` which maps branch names to commit ids.
240 240 """
241 241 raise NotImplementedError
242 242
243 243 @LazyProperty
244 244 def tags(self):
245 245 """
246 246 A `dict` which maps tags names to commit ids.
247 247 """
248 248 raise NotImplementedError
249 249
250 250 @LazyProperty
251 251 def size(self):
252 252 """
253 253 Returns combined size in bytes for all repository files
254 254 """
255 255 tip = self.get_commit()
256 256 return tip.size
257 257
258 258 def size_at_commit(self, commit_id):
259 259 commit = self.get_commit(commit_id)
260 260 return commit.size
261 261
262 262 def is_empty(self):
263 263 return not bool(self.commit_ids)
264 264
265 265 @staticmethod
266 266 def check_url(url, config):
267 267 """
268 268 Function will check given url and try to verify if it's a valid
269 269 link.
270 270 """
271 271 raise NotImplementedError
272 272
273 273 @staticmethod
274 274 def is_valid_repository(path):
275 275 """
276 276 Check if given `path` contains a valid repository of this backend
277 277 """
278 278 raise NotImplementedError
279 279
280 280 # ==========================================================================
281 281 # COMMITS
282 282 # ==========================================================================
283 283
284 284 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
285 285 """
286 286 Returns instance of `BaseCommit` class. If `commit_id` and `commit_idx`
287 287 are both None, most recent commit is returned.
288 288
289 289 :param pre_load: Optional. List of commit attributes to load.
290 290
291 291 :raises ``EmptyRepositoryError``: if there are no commits
292 292 """
293 293 raise NotImplementedError
294 294
295 295 def __iter__(self):
296 296 for commit_id in self.commit_ids:
297 297 yield self.get_commit(commit_id=commit_id)
298 298
299 299 def get_commits(
300 300 self, start_id=None, end_id=None, start_date=None, end_date=None,
301 301 branch_name=None, pre_load=None):
302 302 """
303 303 Returns iterator of `BaseCommit` objects from start to end
304 304 not inclusive. This should behave just like a list, ie. end is not
305 305 inclusive.
306 306
307 307 :param start_id: None or str, must be a valid commit id
308 308 :param end_id: None or str, must be a valid commit id
309 309 :param start_date:
310 310 :param end_date:
311 311 :param branch_name:
312 312 :param pre_load:
313 313 """
314 314 raise NotImplementedError
315 315
316 316 def __getitem__(self, key):
317 317 """
318 318 Allows index based access to the commit objects of this repository.
319 319 """
320 320 pre_load = ["author", "branch", "date", "message", "parents"]
321 321 if isinstance(key, slice):
322 322 return self._get_range(key, pre_load)
323 323 return self.get_commit(commit_idx=key, pre_load=pre_load)
324 324
325 325 def _get_range(self, slice_obj, pre_load):
326 326 for commit_id in self.commit_ids.__getitem__(slice_obj):
327 327 yield self.get_commit(commit_id=commit_id, pre_load=pre_load)
328 328
329 329 def count(self):
330 330 return len(self.commit_ids)
331 331
332 332 def tag(self, name, user, commit_id=None, message=None, date=None, **opts):
333 333 """
334 334 Creates and returns a tag for the given ``commit_id``.
335 335
336 336 :param name: name for new tag
337 337 :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>"
338 338 :param commit_id: commit id for which new tag would be created
339 339 :param message: message of the tag's commit
340 340 :param date: date of tag's commit
341 341
342 342 :raises TagAlreadyExistError: if tag with same name already exists
343 343 """
344 344 raise NotImplementedError
345 345
346 346 def remove_tag(self, name, user, message=None, date=None):
347 347 """
348 348 Removes tag with the given ``name``.
349 349
350 350 :param name: name of the tag to be removed
351 351 :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>"
352 352 :param message: message of the tag's removal commit
353 353 :param date: date of tag's removal commit
354 354
355 355 :raises TagDoesNotExistError: if tag with given name does not exists
356 356 """
357 357 raise NotImplementedError
358 358
359 359 def get_diff(
360 360 self, commit1, commit2, path=None, ignore_whitespace=False,
361 361 context=3, path1=None):
362 362 """
363 363 Returns (git like) *diff*, as plain text. Shows changes introduced by
364 364 `commit2` since `commit1`.
365 365
366 366 :param commit1: Entry point from which diff is shown. Can be
367 367 ``self.EMPTY_COMMIT`` - in this case, patch showing all
368 368 the changes since empty state of the repository until `commit2`
369 369 :param commit2: Until which commit changes should be shown.
370 370 :param path: Can be set to a path of a file to create a diff of that
371 371 file. If `path1` is also set, this value is only associated to
372 372 `commit2`.
373 373 :param ignore_whitespace: If set to ``True``, would not show whitespace
374 374 changes. Defaults to ``False``.
375 375 :param context: How many lines before/after changed lines should be
376 376 shown. Defaults to ``3``.
377 377 :param path1: Can be set to a path to associate with `commit1`. This
378 378 parameter works only for backends which support diff generation for
379 379 different paths. Other backends will raise a `ValueError` if `path1`
380 380 is set and has a different value than `path`.
381 381 """
382 382 raise NotImplementedError
383 383
384 384 def strip(self, commit_id, branch=None):
385 385 """
386 386 Strip given commit_id from the repository
387 387 """
388 388 raise NotImplementedError
389 389
390 390 def get_common_ancestor(self, commit_id1, commit_id2, repo2):
391 391 """
392 392 Return a latest common ancestor commit if one exists for this repo
393 393 `commit_id1` vs `commit_id2` from `repo2`.
394 394
395 395 :param commit_id1: Commit it from this repository to use as a
396 396 target for the comparison.
397 397 :param commit_id2: Source commit id to use for comparison.
398 398 :param repo2: Source repository to use for comparison.
399 399 """
400 400 raise NotImplementedError
401 401
402 402 def compare(self, commit_id1, commit_id2, repo2, merge, pre_load=None):
403 403 """
404 404 Compare this repository's revision `commit_id1` with `commit_id2`.
405 405
406 406 Returns a tuple(commits, ancestor) that would be merged from
407 407 `commit_id2`. Doing a normal compare (``merge=False``), ``None``
408 408 will be returned as ancestor.
409 409
410 410 :param commit_id1: Commit it from this repository to use as a
411 411 target for the comparison.
412 412 :param commit_id2: Source commit id to use for comparison.
413 413 :param repo2: Source repository to use for comparison.
414 414 :param merge: If set to ``True`` will do a merge compare which also
415 415 returns the common ancestor.
416 416 :param pre_load: Optional. List of commit attributes to load.
417 417 """
418 418 raise NotImplementedError
419 419
420 420 def merge(self, target_ref, source_repo, source_ref, workspace_id,
421 421 user_name='', user_email='', message='', dry_run=False,
422 422 use_rebase=False):
423 423 """
424 424 Merge the revisions specified in `source_ref` from `source_repo`
425 425 onto the `target_ref` of this repository.
426 426
427 427 `source_ref` and `target_ref` are named tupls with the following
428 428 fields `type`, `name` and `commit_id`.
429 429
430 430 Returns a MergeResponse named tuple with the following fields
431 431 'possible', 'executed', 'source_commit', 'target_commit',
432 432 'merge_commit'.
433 433
434 434 :param target_ref: `target_ref` points to the commit on top of which
435 435 the `source_ref` should be merged.
436 436 :param source_repo: The repository that contains the commits to be
437 437 merged.
438 438 :param source_ref: `source_ref` points to the topmost commit from
439 439 the `source_repo` which should be merged.
440 440 :param workspace_id: `workspace_id` unique identifier.
441 441 :param user_name: Merge commit `user_name`.
442 442 :param user_email: Merge commit `user_email`.
443 443 :param message: Merge commit `message`.
444 444 :param dry_run: If `True` the merge will not take place.
445 445 :param use_rebase: If `True` commits from the source will be rebased
446 446 on top of the target instead of being merged.
447 447 """
448 448 if dry_run:
449 449 message = message or 'dry_run_merge_message'
450 450 user_email = user_email or 'dry-run-merge@rhodecode.com'
451 451 user_name = user_name or 'Dry-Run User'
452 452 else:
453 453 if not user_name:
454 454 raise ValueError('user_name cannot be empty')
455 455 if not user_email:
456 456 raise ValueError('user_email cannot be empty')
457 457 if not message:
458 458 raise ValueError('message cannot be empty')
459 459
460 460 shadow_repository_path = self._maybe_prepare_merge_workspace(
461 461 workspace_id, target_ref)
462 462
463 463 try:
464 464 return self._merge_repo(
465 465 shadow_repository_path, target_ref, source_repo,
466 466 source_ref, message, user_name, user_email, dry_run=dry_run,
467 467 use_rebase=use_rebase)
468 468 except RepositoryError:
469 469 log.exception(
470 470 'Unexpected failure when running merge, dry-run=%s',
471 471 dry_run)
472 472 return MergeResponse(
473 473 False, False, None, MergeFailureReason.UNKNOWN)
474 474
475 475 def _merge_repo(self, shadow_repository_path, target_ref,
476 476 source_repo, source_ref, merge_message,
477 477 merger_name, merger_email, dry_run=False, use_rebase=False):
478 478 """Internal implementation of merge."""
479 479 raise NotImplementedError
480 480
481 481 def _maybe_prepare_merge_workspace(self, workspace_id, target_ref):
482 482 """
483 483 Create the merge workspace.
484 484
485 485 :param workspace_id: `workspace_id` unique identifier.
486 486 """
487 487 raise NotImplementedError
488 488
489 489 def cleanup_merge_workspace(self, workspace_id):
490 490 """
491 491 Remove merge workspace.
492 492
493 493 This function MUST not fail in case there is no workspace associated to
494 494 the given `workspace_id`.
495 495
496 496 :param workspace_id: `workspace_id` unique identifier.
497 497 """
498 498 raise NotImplementedError
499 499
500 500 # ========== #
501 501 # COMMIT API #
502 502 # ========== #
503 503
504 504 @LazyProperty
505 505 def in_memory_commit(self):
506 506 """
507 507 Returns :class:`InMemoryCommit` object for this repository.
508 508 """
509 509 raise NotImplementedError
510 510
511 511 # ======================== #
512 512 # UTILITIES FOR SUBCLASSES #
513 513 # ======================== #
514 514
515 515 def _validate_diff_commits(self, commit1, commit2):
516 516 """
517 517 Validates that the given commits are related to this repository.
518 518
519 519 Intended as a utility for sub classes to have a consistent validation
520 520 of input parameters in methods like :meth:`get_diff`.
521 521 """
522 522 self._validate_commit(commit1)
523 523 self._validate_commit(commit2)
524 524 if (isinstance(commit1, EmptyCommit) and
525 525 isinstance(commit2, EmptyCommit)):
526 526 raise ValueError("Cannot compare two empty commits")
527 527
528 528 def _validate_commit(self, commit):
529 529 if not isinstance(commit, BaseCommit):
530 530 raise TypeError(
531 531 "%s is not of type BaseCommit" % repr(commit))
532 532 if commit.repository != self and not isinstance(commit, EmptyCommit):
533 533 raise ValueError(
534 534 "Commit %s must be a valid commit from this repository %s, "
535 535 "related to this repository instead %s." %
536 536 (commit, self, commit.repository))
537 537
538 538 def _validate_commit_id(self, commit_id):
539 539 if not isinstance(commit_id, basestring):
540 540 raise TypeError("commit_id must be a string value")
541 541
542 542 def _validate_commit_idx(self, commit_idx):
543 543 if not isinstance(commit_idx, (int, long)):
544 544 raise TypeError("commit_idx must be a numeric value")
545 545
546 546 def _validate_branch_name(self, branch_name):
547 547 if branch_name and branch_name not in self.branches_all:
548 548 msg = ("Branch %s not found in %s" % (branch_name, self))
549 549 raise BranchDoesNotExistError(msg)
550 550
551 551 #
552 552 # Supporting deprecated API parts
553 553 # TODO: johbo: consider to move this into a mixin
554 554 #
555 555
556 556 @property
557 557 def EMPTY_CHANGESET(self):
558 558 warnings.warn(
559 559 "Use EMPTY_COMMIT or EMPTY_COMMIT_ID instead", DeprecationWarning)
560 560 return self.EMPTY_COMMIT_ID
561 561
562 562 @property
563 563 def revisions(self):
564 564 warnings.warn("Use commits attribute instead", DeprecationWarning)
565 565 return self.commit_ids
566 566
567 567 @revisions.setter
568 568 def revisions(self, value):
569 569 warnings.warn("Use commits attribute instead", DeprecationWarning)
570 570 self.commit_ids = value
571 571
572 572 def get_changeset(self, revision=None, pre_load=None):
573 573 warnings.warn("Use get_commit instead", DeprecationWarning)
574 574 commit_id = None
575 575 commit_idx = None
576 576 if isinstance(revision, basestring):
577 577 commit_id = revision
578 578 else:
579 579 commit_idx = revision
580 580 return self.get_commit(
581 581 commit_id=commit_id, commit_idx=commit_idx, pre_load=pre_load)
582 582
583 583 def get_changesets(
584 584 self, start=None, end=None, start_date=None, end_date=None,
585 585 branch_name=None, pre_load=None):
586 586 warnings.warn("Use get_commits instead", DeprecationWarning)
587 587 start_id = self._revision_to_commit(start)
588 588 end_id = self._revision_to_commit(end)
589 589 return self.get_commits(
590 590 start_id=start_id, end_id=end_id, start_date=start_date,
591 591 end_date=end_date, branch_name=branch_name, pre_load=pre_load)
592 592
593 593 def _revision_to_commit(self, revision):
594 594 """
595 595 Translates a revision to a commit_id
596 596
597 597 Helps to support the old changeset based API which allows to use
598 598 commit ids and commit indices interchangeable.
599 599 """
600 600 if revision is None:
601 601 return revision
602 602
603 603 if isinstance(revision, basestring):
604 604 commit_id = revision
605 605 else:
606 606 commit_id = self.commit_ids[revision]
607 607 return commit_id
608 608
609 609 @property
610 610 def in_memory_changeset(self):
611 611 warnings.warn("Use in_memory_commit instead", DeprecationWarning)
612 612 return self.in_memory_commit
613 613
614 614
615 615 class BaseCommit(object):
616 616 """
617 617 Each backend should implement it's commit representation.
618 618
619 619 **Attributes**
620 620
621 621 ``repository``
622 622 repository object within which commit exists
623 623
624 624 ``id``
625 625 The commit id, may be ``raw_id`` or i.e. for mercurial's tip
626 626 just ``tip``.
627 627
628 628 ``raw_id``
629 629 raw commit representation (i.e. full 40 length sha for git
630 630 backend)
631 631
632 632 ``short_id``
633 633 shortened (if apply) version of ``raw_id``; it would be simple
634 634 shortcut for ``raw_id[:12]`` for git/mercurial backends or same
635 635 as ``raw_id`` for subversion
636 636
637 637 ``idx``
638 638 commit index
639 639
640 640 ``files``
641 641 list of ``FileNode`` (``Node`` with NodeKind.FILE) objects
642 642
643 643 ``dirs``
644 644 list of ``DirNode`` (``Node`` with NodeKind.DIR) objects
645 645
646 646 ``nodes``
647 647 combined list of ``Node`` objects
648 648
649 649 ``author``
650 650 author of the commit, as unicode
651 651
652 652 ``message``
653 653 message of the commit, as unicode
654 654
655 655 ``parents``
656 656 list of parent commits
657 657
658 658 """
659 659
660 660 branch = None
661 661 """
662 662 Depending on the backend this should be set to the branch name of the
663 663 commit. Backends not supporting branches on commits should leave this
664 664 value as ``None``.
665 665 """
666 666
667 667 _ARCHIVE_PREFIX_TEMPLATE = b'{repo_name}-{short_id}'
668 668 """
669 669 This template is used to generate a default prefix for repository archives
670 670 if no prefix has been specified.
671 671 """
672 672
673 673 def __str__(self):
674 674 return '<%s at %s:%s>' % (
675 675 self.__class__.__name__, self.idx, self.short_id)
676 676
677 677 def __repr__(self):
678 678 return self.__str__()
679 679
680 680 def __unicode__(self):
681 681 return u'%s:%s' % (self.idx, self.short_id)
682 682
683 683 def __eq__(self, other):
684 684 same_instance = isinstance(other, self.__class__)
685 685 return same_instance and self.raw_id == other.raw_id
686 686
687 687 def __json__(self):
688 688 parents = []
689 689 try:
690 690 for parent in self.parents:
691 691 parents.append({'raw_id': parent.raw_id})
692 692 except NotImplementedError:
693 693 # empty commit doesn't have parents implemented
694 694 pass
695 695
696 696 return {
697 697 'short_id': self.short_id,
698 698 'raw_id': self.raw_id,
699 699 'revision': self.idx,
700 700 'message': self.message,
701 701 'date': self.date,
702 702 'author': self.author,
703 703 'parents': parents,
704 704 'branch': self.branch
705 705 }
706 706
707 707 @LazyProperty
708 708 def last(self):
709 709 """
710 710 ``True`` if this is last commit in repository, ``False``
711 711 otherwise; trying to access this attribute while there is no
712 712 commits would raise `EmptyRepositoryError`
713 713 """
714 714 if self.repository is None:
715 715 raise CommitError("Cannot check if it's most recent commit")
716 716 return self.raw_id == self.repository.commit_ids[-1]
717 717
718 718 @LazyProperty
719 719 def parents(self):
720 720 """
721 721 Returns list of parent commits.
722 722 """
723 723 raise NotImplementedError
724 724
725 725 @property
726 726 def merge(self):
727 727 """
728 728 Returns boolean if commit is a merge.
729 729 """
730 730 return len(self.parents) > 1
731 731
732 732 @LazyProperty
733 733 def children(self):
734 734 """
735 735 Returns list of child commits.
736 736 """
737 737 raise NotImplementedError
738 738
739 739 @LazyProperty
740 740 def id(self):
741 741 """
742 742 Returns string identifying this commit.
743 743 """
744 744 raise NotImplementedError
745 745
746 746 @LazyProperty
747 747 def raw_id(self):
748 748 """
749 749 Returns raw string identifying this commit.
750 750 """
751 751 raise NotImplementedError
752 752
753 753 @LazyProperty
754 754 def short_id(self):
755 755 """
756 756 Returns shortened version of ``raw_id`` attribute, as string,
757 757 identifying this commit, useful for presentation to users.
758 758 """
759 759 raise NotImplementedError
760 760
761 761 @LazyProperty
762 762 def idx(self):
763 763 """
764 764 Returns integer identifying this commit.
765 765 """
766 766 raise NotImplementedError
767 767
768 768 @LazyProperty
769 769 def committer(self):
770 770 """
771 771 Returns committer for this commit
772 772 """
773 773 raise NotImplementedError
774 774
775 775 @LazyProperty
776 776 def committer_name(self):
777 777 """
778 778 Returns committer name for this commit
779 779 """
780 780
781 781 return author_name(self.committer)
782 782
783 783 @LazyProperty
784 784 def committer_email(self):
785 785 """
786 786 Returns committer email address for this commit
787 787 """
788 788
789 789 return author_email(self.committer)
790 790
791 791 @LazyProperty
792 792 def author(self):
793 793 """
794 794 Returns author for this commit
795 795 """
796 796
797 797 raise NotImplementedError
798 798
799 799 @LazyProperty
800 800 def author_name(self):
801 801 """
802 802 Returns author name for this commit
803 803 """
804 804
805 805 return author_name(self.author)
806 806
807 807 @LazyProperty
808 808 def author_email(self):
809 809 """
810 810 Returns author email address for this commit
811 811 """
812 812
813 813 return author_email(self.author)
814 814
815 815 def get_file_mode(self, path):
816 816 """
817 817 Returns stat mode of the file at `path`.
818 818 """
819 819 raise NotImplementedError
820 820
821 821 def is_link(self, path):
822 822 """
823 823 Returns ``True`` if given `path` is a symlink
824 824 """
825 825 raise NotImplementedError
826 826
827 827 def get_file_content(self, path):
828 828 """
829 829 Returns content of the file at the given `path`.
830 830 """
831 831 raise NotImplementedError
832 832
833 833 def get_file_size(self, path):
834 834 """
835 835 Returns size of the file at the given `path`.
836 836 """
837 837 raise NotImplementedError
838 838
839 839 def get_file_commit(self, path, pre_load=None):
840 840 """
841 841 Returns last commit of the file at the given `path`.
842 842
843 843 :param pre_load: Optional. List of commit attributes to load.
844 844 """
845 845 commits = self.get_file_history(path, limit=1, pre_load=pre_load)
846 846 if not commits:
847 847 raise RepositoryError(
848 848 'Failed to fetch history for path {}. '
849 849 'Please check if such path exists in your repository'.format(
850 850 path))
851 851 return commits[0]
852 852
853 853 def get_file_history(self, path, limit=None, pre_load=None):
854 854 """
855 855 Returns history of file as reversed list of :class:`BaseCommit`
856 856 objects for which file at given `path` has been modified.
857 857
858 858 :param limit: Optional. Allows to limit the size of the returned
859 859 history. This is intended as a hint to the underlying backend, so
860 860 that it can apply optimizations depending on the limit.
861 861 :param pre_load: Optional. List of commit attributes to load.
862 862 """
863 863 raise NotImplementedError
864 864
865 865 def get_file_annotate(self, path, pre_load=None):
866 866 """
867 867 Returns a generator of four element tuples with
868 868 lineno, sha, commit lazy loader and line
869 869
870 870 :param pre_load: Optional. List of commit attributes to load.
871 871 """
872 872 raise NotImplementedError
873 873
874 874 def get_nodes(self, path):
875 875 """
876 876 Returns combined ``DirNode`` and ``FileNode`` objects list representing
877 877 state of commit at the given ``path``.
878 878
879 879 :raises ``CommitError``: if node at the given ``path`` is not
880 880 instance of ``DirNode``
881 881 """
882 882 raise NotImplementedError
883 883
884 884 def get_node(self, path):
885 885 """
886 886 Returns ``Node`` object from the given ``path``.
887 887
888 888 :raises ``NodeDoesNotExistError``: if there is no node at the given
889 889 ``path``
890 890 """
891 891 raise NotImplementedError
892 892
893 893 def get_largefile_node(self, path):
894 894 """
895 895 Returns the path to largefile from Mercurial storage.
896 896 """
897 897 raise NotImplementedError
898 898
899 899 def archive_repo(self, file_path, kind='tgz', subrepos=None,
900 900 prefix=None, write_metadata=False, mtime=None):
901 901 """
902 902 Creates an archive containing the contents of the repository.
903 903
904 904 :param file_path: path to the file which to create the archive.
905 905 :param kind: one of following: ``"tbz2"``, ``"tgz"``, ``"zip"``.
906 906 :param prefix: name of root directory in archive.
907 907 Default is repository name and commit's short_id joined with dash:
908 908 ``"{repo_name}-{short_id}"``.
909 909 :param write_metadata: write a metadata file into archive.
910 910 :param mtime: custom modification time for archive creation, defaults
911 911 to time.time() if not given.
912 912
913 913 :raise VCSError: If prefix has a problem.
914 914 """
915 915 allowed_kinds = settings.ARCHIVE_SPECS.keys()
916 916 if kind not in allowed_kinds:
917 917 raise ImproperArchiveTypeError(
918 918 'Archive kind (%s) not supported use one of %s' %
919 919 (kind, allowed_kinds))
920 920
921 921 prefix = self._validate_archive_prefix(prefix)
922 922
923 923 mtime = mtime or time.mktime(self.date.timetuple())
924 924
925 925 file_info = []
926 926 cur_rev = self.repository.get_commit(commit_id=self.raw_id)
927 927 for _r, _d, files in cur_rev.walk('/'):
928 928 for f in files:
929 929 f_path = os.path.join(prefix, f.path)
930 930 file_info.append(
931 931 (f_path, f.mode, f.is_link(), f.raw_bytes))
932 932
933 933 if write_metadata:
934 934 metadata = [
935 935 ('repo_name', self.repository.name),
936 936 ('rev', self.raw_id),
937 937 ('create_time', mtime),
938 938 ('branch', self.branch),
939 939 ('tags', ','.join(self.tags)),
940 940 ]
941 941 meta = ["%s:%s" % (f_name, value) for f_name, value in metadata]
942 942 file_info.append(('.archival.txt', 0644, False, '\n'.join(meta)))
943 943
944 944 connection.Hg.archive_repo(file_path, mtime, file_info, kind)
945 945
946 946 def _validate_archive_prefix(self, prefix):
947 947 if prefix is None:
948 948 prefix = self._ARCHIVE_PREFIX_TEMPLATE.format(
949 949 repo_name=safe_str(self.repository.name),
950 950 short_id=self.short_id)
951 951 elif not isinstance(prefix, str):
952 952 raise ValueError("prefix not a bytes object: %s" % repr(prefix))
953 953 elif prefix.startswith('/'):
954 954 raise VCSError("Prefix cannot start with leading slash")
955 955 elif prefix.strip() == '':
956 956 raise VCSError("Prefix cannot be empty")
957 957 return prefix
958 958
959 959 @LazyProperty
960 960 def root(self):
961 961 """
962 962 Returns ``RootNode`` object for this commit.
963 963 """
964 964 return self.get_node('')
965 965
966 966 def next(self, branch=None):
967 967 """
968 968 Returns next commit from current, if branch is gives it will return
969 969 next commit belonging to this branch
970 970
971 971 :param branch: show commits within the given named branch
972 972 """
973 973 indexes = xrange(self.idx + 1, self.repository.count())
974 974 return self._find_next(indexes, branch)
975 975
976 976 def prev(self, branch=None):
977 977 """
978 978 Returns previous commit from current, if branch is gives it will
979 979 return previous commit belonging to this branch
980 980
981 981 :param branch: show commit within the given named branch
982 982 """
983 983 indexes = xrange(self.idx - 1, -1, -1)
984 984 return self._find_next(indexes, branch)
985 985
986 986 def _find_next(self, indexes, branch=None):
987 987 if branch and self.branch != branch:
988 988 raise VCSError('Branch option used on commit not belonging '
989 989 'to that branch')
990 990
991 991 for next_idx in indexes:
992 992 commit = self.repository.get_commit(commit_idx=next_idx)
993 993 if branch and branch != commit.branch:
994 994 continue
995 995 return commit
996 996 raise CommitDoesNotExistError
997 997
998 998 def diff(self, ignore_whitespace=True, context=3):
999 999 """
1000 1000 Returns a `Diff` object representing the change made by this commit.
1001 1001 """
1002 1002 parent = (
1003 1003 self.parents[0] if self.parents else self.repository.EMPTY_COMMIT)
1004 1004 diff = self.repository.get_diff(
1005 1005 parent, self,
1006 1006 ignore_whitespace=ignore_whitespace,
1007 1007 context=context)
1008 1008 return diff
1009 1009
1010 1010 @LazyProperty
1011 1011 def added(self):
1012 1012 """
1013 1013 Returns list of added ``FileNode`` objects.
1014 1014 """
1015 1015 raise NotImplementedError
1016 1016
1017 1017 @LazyProperty
1018 1018 def changed(self):
1019 1019 """
1020 1020 Returns list of modified ``FileNode`` objects.
1021 1021 """
1022 1022 raise NotImplementedError
1023 1023
1024 1024 @LazyProperty
1025 1025 def removed(self):
1026 1026 """
1027 1027 Returns list of removed ``FileNode`` objects.
1028 1028 """
1029 1029 raise NotImplementedError
1030 1030
1031 1031 @LazyProperty
1032 1032 def size(self):
1033 1033 """
1034 1034 Returns total number of bytes from contents of all filenodes.
1035 1035 """
1036 1036 return sum((node.size for node in self.get_filenodes_generator()))
1037 1037
1038 1038 def walk(self, topurl=''):
1039 1039 """
1040 1040 Similar to os.walk method. Insted of filesystem it walks through
1041 1041 commit starting at given ``topurl``. Returns generator of tuples
1042 1042 (topnode, dirnodes, filenodes).
1043 1043 """
1044 1044 topnode = self.get_node(topurl)
1045 1045 if not topnode.is_dir():
1046 1046 return
1047 1047 yield (topnode, topnode.dirs, topnode.files)
1048 1048 for dirnode in topnode.dirs:
1049 1049 for tup in self.walk(dirnode.path):
1050 1050 yield tup
1051 1051
1052 1052 def get_filenodes_generator(self):
1053 1053 """
1054 1054 Returns generator that yields *all* file nodes.
1055 1055 """
1056 1056 for topnode, dirs, files in self.walk():
1057 1057 for node in files:
1058 1058 yield node
1059 1059
1060 1060 #
1061 1061 # Utilities for sub classes to support consistent behavior
1062 1062 #
1063 1063
1064 1064 def no_node_at_path(self, path):
1065 1065 return NodeDoesNotExistError(
1066 1066 "There is no file nor directory at the given path: "
1067 1067 "'%s' at commit %s" % (path, self.short_id))
1068 1068
1069 1069 def _fix_path(self, path):
1070 1070 """
1071 1071 Paths are stored without trailing slash so we need to get rid off it if
1072 1072 needed.
1073 1073 """
1074 1074 return path.rstrip('/')
1075 1075
1076 1076 #
1077 1077 # Deprecated API based on changesets
1078 1078 #
1079 1079
1080 1080 @property
1081 1081 def revision(self):
1082 1082 warnings.warn("Use idx instead", DeprecationWarning)
1083 1083 return self.idx
1084 1084
1085 1085 @revision.setter
1086 1086 def revision(self, value):
1087 1087 warnings.warn("Use idx instead", DeprecationWarning)
1088 1088 self.idx = value
1089 1089
1090 1090 def get_file_changeset(self, path):
1091 1091 warnings.warn("Use get_file_commit instead", DeprecationWarning)
1092 1092 return self.get_file_commit(path)
1093 1093
1094 1094
1095 1095 class BaseChangesetClass(type):
1096 1096
1097 1097 def __instancecheck__(self, instance):
1098 1098 return isinstance(instance, BaseCommit)
1099 1099
1100 1100
1101 1101 class BaseChangeset(BaseCommit):
1102 1102
1103 1103 __metaclass__ = BaseChangesetClass
1104 1104
1105 1105 def __new__(cls, *args, **kwargs):
1106 1106 warnings.warn(
1107 1107 "Use BaseCommit instead of BaseChangeset", DeprecationWarning)
1108 1108 return super(BaseChangeset, cls).__new__(cls, *args, **kwargs)
1109 1109
1110 1110
1111 1111 class BaseInMemoryCommit(object):
1112 1112 """
1113 1113 Represents differences between repository's state (most recent head) and
1114 1114 changes made *in place*.
1115 1115
1116 1116 **Attributes**
1117 1117
1118 1118 ``repository``
1119 1119 repository object for this in-memory-commit
1120 1120
1121 1121 ``added``
1122 1122 list of ``FileNode`` objects marked as *added*
1123 1123
1124 1124 ``changed``
1125 1125 list of ``FileNode`` objects marked as *changed*
1126 1126
1127 1127 ``removed``
1128 1128 list of ``FileNode`` or ``RemovedFileNode`` objects marked to be
1129 1129 *removed*
1130 1130
1131 1131 ``parents``
1132 1132 list of :class:`BaseCommit` instances representing parents of
1133 1133 in-memory commit. Should always be 2-element sequence.
1134 1134
1135 1135 """
1136 1136
1137 1137 def __init__(self, repository):
1138 1138 self.repository = repository
1139 1139 self.added = []
1140 1140 self.changed = []
1141 1141 self.removed = []
1142 1142 self.parents = []
1143 1143
1144 1144 def add(self, *filenodes):
1145 1145 """
1146 1146 Marks given ``FileNode`` objects as *to be committed*.
1147 1147
1148 1148 :raises ``NodeAlreadyExistsError``: if node with same path exists at
1149 1149 latest commit
1150 1150 :raises ``NodeAlreadyAddedError``: if node with same path is already
1151 1151 marked as *added*
1152 1152 """
1153 1153 # Check if not already marked as *added* first
1154 1154 for node in filenodes:
1155 1155 if node.path in (n.path for n in self.added):
1156 1156 raise NodeAlreadyAddedError(
1157 1157 "Such FileNode %s is already marked for addition"
1158 1158 % node.path)
1159 1159 for node in filenodes:
1160 1160 self.added.append(node)
1161 1161
1162 1162 def change(self, *filenodes):
1163 1163 """
1164 1164 Marks given ``FileNode`` objects to be *changed* in next commit.
1165 1165
1166 1166 :raises ``EmptyRepositoryError``: if there are no commits yet
1167 1167 :raises ``NodeAlreadyExistsError``: if node with same path is already
1168 1168 marked to be *changed*
1169 1169 :raises ``NodeAlreadyRemovedError``: if node with same path is already
1170 1170 marked to be *removed*
1171 1171 :raises ``NodeDoesNotExistError``: if node doesn't exist in latest
1172 1172 commit
1173 1173 :raises ``NodeNotChangedError``: if node hasn't really be changed
1174 1174 """
1175 1175 for node in filenodes:
1176 1176 if node.path in (n.path for n in self.removed):
1177 1177 raise NodeAlreadyRemovedError(
1178 1178 "Node at %s is already marked as removed" % node.path)
1179 1179 try:
1180 1180 self.repository.get_commit()
1181 1181 except EmptyRepositoryError:
1182 1182 raise EmptyRepositoryError(
1183 1183 "Nothing to change - try to *add* new nodes rather than "
1184 1184 "changing them")
1185 1185 for node in filenodes:
1186 1186 if node.path in (n.path for n in self.changed):
1187 1187 raise NodeAlreadyChangedError(
1188 1188 "Node at '%s' is already marked as changed" % node.path)
1189 1189 self.changed.append(node)
1190 1190
1191 1191 def remove(self, *filenodes):
1192 1192 """
1193 1193 Marks given ``FileNode`` (or ``RemovedFileNode``) objects to be
1194 1194 *removed* in next commit.
1195 1195
1196 1196 :raises ``NodeAlreadyRemovedError``: if node has been already marked to
1197 1197 be *removed*
1198 1198 :raises ``NodeAlreadyChangedError``: if node has been already marked to
1199 1199 be *changed*
1200 1200 """
1201 1201 for node in filenodes:
1202 1202 if node.path in (n.path for n in self.removed):
1203 1203 raise NodeAlreadyRemovedError(
1204 1204 "Node is already marked to for removal at %s" % node.path)
1205 1205 if node.path in (n.path for n in self.changed):
1206 1206 raise NodeAlreadyChangedError(
1207 1207 "Node is already marked to be changed at %s" % node.path)
1208 1208 # We only mark node as *removed* - real removal is done by
1209 1209 # commit method
1210 1210 self.removed.append(node)
1211 1211
1212 1212 def reset(self):
1213 1213 """
1214 1214 Resets this instance to initial state (cleans ``added``, ``changed``
1215 1215 and ``removed`` lists).
1216 1216 """
1217 1217 self.added = []
1218 1218 self.changed = []
1219 1219 self.removed = []
1220 1220 self.parents = []
1221 1221
1222 1222 def get_ipaths(self):
1223 1223 """
1224 1224 Returns generator of paths from nodes marked as added, changed or
1225 1225 removed.
1226 1226 """
1227 1227 for node in itertools.chain(self.added, self.changed, self.removed):
1228 1228 yield node.path
1229 1229
1230 1230 def get_paths(self):
1231 1231 """
1232 1232 Returns list of paths from nodes marked as added, changed or removed.
1233 1233 """
1234 1234 return list(self.get_ipaths())
1235 1235
1236 1236 def check_integrity(self, parents=None):
1237 1237 """
1238 1238 Checks in-memory commit's integrity. Also, sets parents if not
1239 1239 already set.
1240 1240
1241 1241 :raises CommitError: if any error occurs (i.e.
1242 1242 ``NodeDoesNotExistError``).
1243 1243 """
1244 1244 if not self.parents:
1245 1245 parents = parents or []
1246 1246 if len(parents) == 0:
1247 1247 try:
1248 1248 parents = [self.repository.get_commit(), None]
1249 1249 except EmptyRepositoryError:
1250 1250 parents = [None, None]
1251 1251 elif len(parents) == 1:
1252 1252 parents += [None]
1253 1253 self.parents = parents
1254 1254
1255 1255 # Local parents, only if not None
1256 1256 parents = [p for p in self.parents if p]
1257 1257
1258 1258 # Check nodes marked as added
1259 1259 for p in parents:
1260 1260 for node in self.added:
1261 1261 try:
1262 1262 p.get_node(node.path)
1263 1263 except NodeDoesNotExistError:
1264 1264 pass
1265 1265 else:
1266 1266 raise NodeAlreadyExistsError(
1267 1267 "Node `%s` already exists at %s" % (node.path, p))
1268 1268
1269 1269 # Check nodes marked as changed
1270 1270 missing = set(self.changed)
1271 1271 not_changed = set(self.changed)
1272 1272 if self.changed and not parents:
1273 1273 raise NodeDoesNotExistError(str(self.changed[0].path))
1274 1274 for p in parents:
1275 1275 for node in self.changed:
1276 1276 try:
1277 1277 old = p.get_node(node.path)
1278 1278 missing.remove(node)
1279 1279 # if content actually changed, remove node from not_changed
1280 1280 if old.content != node.content:
1281 1281 not_changed.remove(node)
1282 1282 except NodeDoesNotExistError:
1283 1283 pass
1284 1284 if self.changed and missing:
1285 1285 raise NodeDoesNotExistError(
1286 1286 "Node `%s` marked as modified but missing in parents: %s"
1287 1287 % (node.path, parents))
1288 1288
1289 1289 if self.changed and not_changed:
1290 1290 raise NodeNotChangedError(
1291 1291 "Node `%s` wasn't actually changed (parents: %s)"
1292 1292 % (not_changed.pop().path, parents))
1293 1293
1294 1294 # Check nodes marked as removed
1295 1295 if self.removed and not parents:
1296 1296 raise NodeDoesNotExistError(
1297 1297 "Cannot remove node at %s as there "
1298 1298 "were no parents specified" % self.removed[0].path)
1299 1299 really_removed = set()
1300 1300 for p in parents:
1301 1301 for node in self.removed:
1302 1302 try:
1303 1303 p.get_node(node.path)
1304 1304 really_removed.add(node)
1305 1305 except CommitError:
1306 1306 pass
1307 1307 not_removed = set(self.removed) - really_removed
1308 1308 if not_removed:
1309 1309 # TODO: johbo: This code branch does not seem to be covered
1310 1310 raise NodeDoesNotExistError(
1311 1311 "Cannot remove node at %s from "
1312 1312 "following parents: %s" % (not_removed, parents))
1313 1313
1314 1314 def commit(
1315 1315 self, message, author, parents=None, branch=None, date=None,
1316 1316 **kwargs):
1317 1317 """
1318 1318 Performs in-memory commit (doesn't check workdir in any way) and
1319 1319 returns newly created :class:`BaseCommit`. Updates repository's
1320 1320 attribute `commits`.
1321 1321
1322 1322 .. note::
1323 1323
1324 1324 While overriding this method each backend's should call
1325 1325 ``self.check_integrity(parents)`` in the first place.
1326 1326
1327 1327 :param message: message of the commit
1328 1328 :param author: full username, i.e. "Joe Doe <joe.doe@example.com>"
1329 1329 :param parents: single parent or sequence of parents from which commit
1330 1330 would be derived
1331 1331 :param date: ``datetime.datetime`` instance. Defaults to
1332 1332 ``datetime.datetime.now()``.
1333 1333 :param branch: branch name, as string. If none given, default backend's
1334 1334 branch would be used.
1335 1335
1336 1336 :raises ``CommitError``: if any error occurs while committing
1337 1337 """
1338 1338 raise NotImplementedError
1339 1339
1340 1340
1341 1341 class BaseInMemoryChangesetClass(type):
1342 1342
1343 1343 def __instancecheck__(self, instance):
1344 1344 return isinstance(instance, BaseInMemoryCommit)
1345 1345
1346 1346
1347 1347 class BaseInMemoryChangeset(BaseInMemoryCommit):
1348 1348
1349 1349 __metaclass__ = BaseInMemoryChangesetClass
1350 1350
1351 1351 def __new__(cls, *args, **kwargs):
1352 1352 warnings.warn(
1353 1353 "Use BaseCommit instead of BaseInMemoryCommit", DeprecationWarning)
1354 1354 return super(BaseInMemoryChangeset, cls).__new__(cls, *args, **kwargs)
1355 1355
1356 1356
1357 1357 class EmptyCommit(BaseCommit):
1358 1358 """
1359 1359 An dummy empty commit. It's possible to pass hash when creating
1360 1360 an EmptyCommit
1361 1361 """
1362 1362
1363 1363 def __init__(
1364 1364 self, commit_id='0' * 40, repo=None, alias=None, idx=-1,
1365 1365 message='', author='', date=None):
1366 1366 self._empty_commit_id = commit_id
1367 1367 # TODO: johbo: Solve idx parameter, default value does not make
1368 1368 # too much sense
1369 1369 self.idx = idx
1370 1370 self.message = message
1371 1371 self.author = author
1372 1372 self.date = date or datetime.datetime.fromtimestamp(0)
1373 1373 self.repository = repo
1374 1374 self.alias = alias
1375 1375
1376 1376 @LazyProperty
1377 1377 def raw_id(self):
1378 1378 """
1379 1379 Returns raw string identifying this commit, useful for web
1380 1380 representation.
1381 1381 """
1382 1382
1383 1383 return self._empty_commit_id
1384 1384
1385 1385 @LazyProperty
1386 1386 def branch(self):
1387 1387 if self.alias:
1388 1388 from rhodecode.lib.vcs.backends import get_backend
1389 1389 return get_backend(self.alias).DEFAULT_BRANCH_NAME
1390 1390
1391 1391 @LazyProperty
1392 1392 def short_id(self):
1393 1393 return self.raw_id[:12]
1394 1394
1395 1395 @LazyProperty
1396 1396 def id(self):
1397 1397 return self.raw_id
1398 1398
1399 1399 def get_file_commit(self, path):
1400 1400 return self
1401 1401
1402 1402 def get_file_content(self, path):
1403 1403 return u''
1404 1404
1405 1405 def get_file_size(self, path):
1406 1406 return 0
1407 1407
1408 1408
1409 1409 class EmptyChangesetClass(type):
1410 1410
1411 1411 def __instancecheck__(self, instance):
1412 1412 return isinstance(instance, EmptyCommit)
1413 1413
1414 1414
1415 1415 class EmptyChangeset(EmptyCommit):
1416 1416
1417 1417 __metaclass__ = EmptyChangesetClass
1418 1418
1419 1419 def __new__(cls, *args, **kwargs):
1420 1420 warnings.warn(
1421 1421 "Use EmptyCommit instead of EmptyChangeset", DeprecationWarning)
1422 1422 return super(EmptyCommit, cls).__new__(cls, *args, **kwargs)
1423 1423
1424 1424 def __init__(self, cs='0' * 40, repo=None, requested_revision=None,
1425 1425 alias=None, revision=-1, message='', author='', date=None):
1426 1426 if requested_revision is not None:
1427 1427 warnings.warn(
1428 1428 "Parameter requested_revision not supported anymore",
1429 1429 DeprecationWarning)
1430 1430 super(EmptyChangeset, self).__init__(
1431 1431 commit_id=cs, repo=repo, alias=alias, idx=revision,
1432 1432 message=message, author=author, date=date)
1433 1433
1434 1434 @property
1435 1435 def revision(self):
1436 1436 warnings.warn("Use idx instead", DeprecationWarning)
1437 1437 return self.idx
1438 1438
1439 1439 @revision.setter
1440 1440 def revision(self, value):
1441 1441 warnings.warn("Use idx instead", DeprecationWarning)
1442 1442 self.idx = value
1443 1443
1444 1444
1445 class EmptyRepository(BaseRepository):
1446 def __init__(self, repo_path=None, config=None, create=False, **kwargs):
1447 pass
1448
1449 def get_diff(self, *args, **kwargs):
1450 from rhodecode.lib.vcs.backends.git.diff import GitDiff
1451 return GitDiff('')
1452
1453
1445 1454 class CollectionGenerator(object):
1446 1455
1447 1456 def __init__(self, repo, commit_ids, collection_size=None, pre_load=None):
1448 1457 self.repo = repo
1449 1458 self.commit_ids = commit_ids
1450 1459 # TODO: (oliver) this isn't currently hooked up
1451 1460 self.collection_size = None
1452 1461 self.pre_load = pre_load
1453 1462
1454 1463 def __len__(self):
1455 1464 if self.collection_size is not None:
1456 1465 return self.collection_size
1457 1466 return self.commit_ids.__len__()
1458 1467
1459 1468 def __iter__(self):
1460 1469 for commit_id in self.commit_ids:
1461 1470 # TODO: johbo: Mercurial passes in commit indices or commit ids
1462 1471 yield self._commit_factory(commit_id)
1463 1472
1464 1473 def _commit_factory(self, commit_id):
1465 1474 """
1466 1475 Allows backends to override the way commits are generated.
1467 1476 """
1468 1477 return self.repo.get_commit(commit_id=commit_id,
1469 1478 pre_load=self.pre_load)
1470 1479
1471 1480 def __getslice__(self, i, j):
1472 1481 """
1473 1482 Returns an iterator of sliced repository
1474 1483 """
1475 1484 commit_ids = self.commit_ids[i:j]
1476 1485 return self.__class__(
1477 1486 self.repo, commit_ids, pre_load=self.pre_load)
1478 1487
1479 1488 def __repr__(self):
1480 1489 return '<CollectionGenerator[len:%s]>' % (self.__len__())
1481 1490
1482 1491
1483 1492 class Config(object):
1484 1493 """
1485 1494 Represents the configuration for a repository.
1486 1495
1487 1496 The API is inspired by :class:`ConfigParser.ConfigParser` from the
1488 1497 standard library. It implements only the needed subset.
1489 1498 """
1490 1499
1491 1500 def __init__(self):
1492 1501 self._values = {}
1493 1502
1494 1503 def copy(self):
1495 1504 clone = Config()
1496 1505 for section, values in self._values.items():
1497 1506 clone._values[section] = values.copy()
1498 1507 return clone
1499 1508
1500 1509 def __repr__(self):
1501 1510 return '<Config(%s sections) at %s>' % (
1502 1511 len(self._values), hex(id(self)))
1503 1512
1504 1513 def items(self, section):
1505 1514 return self._values.get(section, {}).iteritems()
1506 1515
1507 1516 def get(self, section, option):
1508 1517 return self._values.get(section, {}).get(option)
1509 1518
1510 1519 def set(self, section, option, value):
1511 1520 section_values = self._values.setdefault(section, {})
1512 1521 section_values[option] = value
1513 1522
1514 1523 def clear_section(self, section):
1515 1524 self._values[section] = {}
1516 1525
1517 1526 def serialize(self):
1518 1527 """
1519 1528 Creates a list of three tuples (section, key, value) representing
1520 1529 this config object.
1521 1530 """
1522 1531 items = []
1523 1532 for section in self._values:
1524 1533 for option, value in self._values[section].items():
1525 1534 items.append(
1526 1535 (safe_str(section), safe_str(option), safe_str(value)))
1527 1536 return items
1528 1537
1529 1538
1530 1539 class Diff(object):
1531 1540 """
1532 1541 Represents a diff result from a repository backend.
1533 1542
1534 1543 Subclasses have to provide a backend specific value for :attr:`_header_re`.
1535 1544 """
1536 1545
1537 1546 _header_re = None
1538 1547
1539 1548 def __init__(self, raw_diff):
1540 1549 self.raw = raw_diff
1541 1550
1542 1551 def chunks(self):
1543 1552 """
1544 1553 split the diff in chunks of separate --git a/file b/file chunks
1545 1554 to make diffs consistent we must prepend with \n, and make sure
1546 1555 we can detect last chunk as this was also has special rule
1547 1556 """
1548 1557 chunks = ('\n' + self.raw).split('\ndiff --git')[1:]
1549 1558 total_chunks = len(chunks)
1550 1559 return (DiffChunk(chunk, self, cur_chunk == total_chunks)
1551 1560 for cur_chunk, chunk in enumerate(chunks, start=1))
1552 1561
1553 1562
1554 1563 class DiffChunk(object):
1555 1564
1556 1565 def __init__(self, chunk, diff, last_chunk):
1557 1566 self._diff = diff
1558 1567
1559 1568 # since we split by \ndiff --git that part is lost from original diff
1560 1569 # we need to re-apply it at the end, EXCEPT ! if it's last chunk
1561 1570 if not last_chunk:
1562 1571 chunk += '\n'
1563 1572
1564 1573 match = self._diff._header_re.match(chunk)
1565 1574 self.header = match.groupdict()
1566 1575 self.diff = chunk[match.end():]
1567 1576 self.raw = chunk
@@ -1,3730 +1,3788 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2016 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 glob2re)
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 ip_addresses(self):
606 606 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
607 607 return [x.ip_addr for x in ret]
608 608
609 609 @property
610 610 def username_and_name(self):
611 611 return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
612 612
613 613 @property
614 614 def username_or_name_or_email(self):
615 615 full_name = self.full_name if self.full_name is not ' ' else None
616 616 return self.username or full_name or self.email
617 617
618 618 @property
619 619 def full_name(self):
620 620 return '%s %s' % (self.firstname, self.lastname)
621 621
622 622 @property
623 623 def full_name_or_username(self):
624 624 return ('%s %s' % (self.firstname, self.lastname)
625 625 if (self.firstname and self.lastname) else self.username)
626 626
627 627 @property
628 628 def full_contact(self):
629 629 return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
630 630
631 631 @property
632 632 def short_contact(self):
633 633 return '%s %s' % (self.firstname, self.lastname)
634 634
635 635 @property
636 636 def is_admin(self):
637 637 return self.admin
638 638
639 639 @property
640 640 def AuthUser(self):
641 641 """
642 642 Returns instance of AuthUser for this user
643 643 """
644 644 from rhodecode.lib.auth import AuthUser
645 645 return AuthUser(user_id=self.user_id, api_key=self.api_key,
646 646 username=self.username)
647 647
648 648 @hybrid_property
649 649 def user_data(self):
650 650 if not self._user_data:
651 651 return {}
652 652
653 653 try:
654 654 return json.loads(self._user_data)
655 655 except TypeError:
656 656 return {}
657 657
658 658 @user_data.setter
659 659 def user_data(self, val):
660 660 if not isinstance(val, dict):
661 661 raise Exception('user_data must be dict, got %s' % type(val))
662 662 try:
663 663 self._user_data = json.dumps(val)
664 664 except Exception:
665 665 log.error(traceback.format_exc())
666 666
667 667 @classmethod
668 668 def get_by_username(cls, username, case_insensitive=False,
669 669 cache=False, identity_cache=False):
670 670 session = Session()
671 671
672 672 if case_insensitive:
673 673 q = cls.query().filter(
674 674 func.lower(cls.username) == func.lower(username))
675 675 else:
676 676 q = cls.query().filter(cls.username == username)
677 677
678 678 if cache:
679 679 if identity_cache:
680 680 val = cls.identity_cache(session, 'username', username)
681 681 if val:
682 682 return val
683 683 else:
684 684 q = q.options(
685 685 FromCache("sql_cache_short",
686 686 "get_user_by_name_%s" % _hash_key(username)))
687 687
688 688 return q.scalar()
689 689
690 690 @classmethod
691 691 def get_by_auth_token(cls, auth_token, cache=False, fallback=True):
692 692 q = cls.query().filter(cls.api_key == auth_token)
693 693
694 694 if cache:
695 695 q = q.options(FromCache("sql_cache_short",
696 696 "get_auth_token_%s" % auth_token))
697 697 res = q.scalar()
698 698
699 699 if fallback and not res:
700 700 #fallback to additional keys
701 701 _res = UserApiKeys.query()\
702 702 .filter(UserApiKeys.api_key == auth_token)\
703 703 .filter(or_(UserApiKeys.expires == -1,
704 704 UserApiKeys.expires >= time.time()))\
705 705 .first()
706 706 if _res:
707 707 res = _res.user
708 708 return res
709 709
710 710 @classmethod
711 711 def get_by_email(cls, email, case_insensitive=False, cache=False):
712 712
713 713 if case_insensitive:
714 714 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
715 715
716 716 else:
717 717 q = cls.query().filter(cls.email == email)
718 718
719 719 if cache:
720 720 q = q.options(FromCache("sql_cache_short",
721 721 "get_email_key_%s" % _hash_key(email)))
722 722
723 723 ret = q.scalar()
724 724 if ret is None:
725 725 q = UserEmailMap.query()
726 726 # try fetching in alternate email map
727 727 if case_insensitive:
728 728 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
729 729 else:
730 730 q = q.filter(UserEmailMap.email == email)
731 731 q = q.options(joinedload(UserEmailMap.user))
732 732 if cache:
733 733 q = q.options(FromCache("sql_cache_short",
734 734 "get_email_map_key_%s" % email))
735 735 ret = getattr(q.scalar(), 'user', None)
736 736
737 737 return ret
738 738
739 739 @classmethod
740 740 def get_from_cs_author(cls, author):
741 741 """
742 742 Tries to get User objects out of commit author string
743 743
744 744 :param author:
745 745 """
746 746 from rhodecode.lib.helpers import email, author_name
747 747 # Valid email in the attribute passed, see if they're in the system
748 748 _email = email(author)
749 749 if _email:
750 750 user = cls.get_by_email(_email, case_insensitive=True)
751 751 if user:
752 752 return user
753 753 # Maybe we can match by username?
754 754 _author = author_name(author)
755 755 user = cls.get_by_username(_author, case_insensitive=True)
756 756 if user:
757 757 return user
758 758
759 759 def update_userdata(self, **kwargs):
760 760 usr = self
761 761 old = usr.user_data
762 762 old.update(**kwargs)
763 763 usr.user_data = old
764 764 Session().add(usr)
765 765 log.debug('updated userdata with ', kwargs)
766 766
767 767 def update_lastlogin(self):
768 768 """Update user lastlogin"""
769 769 self.last_login = datetime.datetime.now()
770 770 Session().add(self)
771 771 log.debug('updated user %s lastlogin', self.username)
772 772
773 773 def update_lastactivity(self):
774 774 """Update user lastactivity"""
775 775 usr = self
776 776 old = usr.user_data
777 777 old.update({'last_activity': time.time()})
778 778 usr.user_data = old
779 779 Session().add(usr)
780 780 log.debug('updated user %s lastactivity', usr.username)
781 781
782 782 def update_password(self, new_password, change_api_key=False):
783 783 from rhodecode.lib.auth import get_crypt_password,generate_auth_token
784 784
785 785 self.password = get_crypt_password(new_password)
786 786 if change_api_key:
787 787 self.api_key = generate_auth_token(self.username)
788 788 Session().add(self)
789 789
790 790 @classmethod
791 791 def get_first_super_admin(cls):
792 792 user = User.query().filter(User.admin == true()).first()
793 793 if user is None:
794 794 raise Exception('FATAL: Missing administrative account!')
795 795 return user
796 796
797 797 @classmethod
798 798 def get_all_super_admins(cls):
799 799 """
800 800 Returns all admin accounts sorted by username
801 801 """
802 802 return User.query().filter(User.admin == true())\
803 803 .order_by(User.username.asc()).all()
804 804
805 805 @classmethod
806 806 def get_default_user(cls, cache=False):
807 807 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
808 808 if user is None:
809 809 raise Exception('FATAL: Missing default account!')
810 810 return user
811 811
812 812 def _get_default_perms(self, user, suffix=''):
813 813 from rhodecode.model.permission import PermissionModel
814 814 return PermissionModel().get_default_perms(user.user_perms, suffix)
815 815
816 816 def get_default_perms(self, suffix=''):
817 817 return self._get_default_perms(self, suffix)
818 818
819 819 def get_api_data(self, include_secrets=False, details='full'):
820 820 """
821 821 Common function for generating user related data for API
822 822
823 823 :param include_secrets: By default secrets in the API data will be replaced
824 824 by a placeholder value to prevent exposing this data by accident. In case
825 825 this data shall be exposed, set this flag to ``True``.
826 826
827 827 :param details: details can be 'basic|full' basic gives only a subset of
828 828 the available user information that includes user_id, name and emails.
829 829 """
830 830 user = self
831 831 user_data = self.user_data
832 832 data = {
833 833 'user_id': user.user_id,
834 834 'username': user.username,
835 835 'firstname': user.name,
836 836 'lastname': user.lastname,
837 837 'email': user.email,
838 838 'emails': user.emails,
839 839 }
840 840 if details == 'basic':
841 841 return data
842 842
843 843 api_key_length = 40
844 844 api_key_replacement = '*' * api_key_length
845 845
846 846 extras = {
847 847 'api_key': api_key_replacement,
848 848 'api_keys': [api_key_replacement],
849 849 'active': user.active,
850 850 'admin': user.admin,
851 851 'extern_type': user.extern_type,
852 852 'extern_name': user.extern_name,
853 853 'last_login': user.last_login,
854 854 'ip_addresses': user.ip_addresses,
855 855 'language': user_data.get('language')
856 856 }
857 857 data.update(extras)
858 858
859 859 if include_secrets:
860 860 data['api_key'] = user.api_key
861 861 data['api_keys'] = user.auth_tokens
862 862 return data
863 863
864 864 def __json__(self):
865 865 data = {
866 866 'full_name': self.full_name,
867 867 'full_name_or_username': self.full_name_or_username,
868 868 'short_contact': self.short_contact,
869 869 'full_contact': self.full_contact,
870 870 }
871 871 data.update(self.get_api_data())
872 872 return data
873 873
874 874
875 875 class UserApiKeys(Base, BaseModel):
876 876 __tablename__ = 'user_api_keys'
877 877 __table_args__ = (
878 878 Index('uak_api_key_idx', 'api_key'),
879 879 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
880 880 UniqueConstraint('api_key'),
881 881 {'extend_existing': True, 'mysql_engine': 'InnoDB',
882 882 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
883 883 )
884 884 __mapper_args__ = {}
885 885
886 886 # ApiKey role
887 887 ROLE_ALL = 'token_role_all'
888 888 ROLE_HTTP = 'token_role_http'
889 889 ROLE_VCS = 'token_role_vcs'
890 890 ROLE_API = 'token_role_api'
891 891 ROLE_FEED = 'token_role_feed'
892 892 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
893 893
894 894 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
895 895 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
896 896 api_key = Column("api_key", String(255), nullable=False, unique=True)
897 897 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
898 898 expires = Column('expires', Float(53), nullable=False)
899 899 role = Column('role', String(255), nullable=True)
900 900 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
901 901
902 902 user = relationship('User', lazy='joined')
903 903
904 904 @classmethod
905 905 def _get_role_name(cls, role):
906 906 return {
907 907 cls.ROLE_ALL: _('all'),
908 908 cls.ROLE_HTTP: _('http/web interface'),
909 909 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
910 910 cls.ROLE_API: _('api calls'),
911 911 cls.ROLE_FEED: _('feed access'),
912 912 }.get(role, role)
913 913
914 914 @property
915 915 def expired(self):
916 916 if self.expires == -1:
917 917 return False
918 918 return time.time() > self.expires
919 919
920 920 @property
921 921 def role_humanized(self):
922 922 return self._get_role_name(self.role)
923 923
924 924
925 925 class UserEmailMap(Base, BaseModel):
926 926 __tablename__ = 'user_email_map'
927 927 __table_args__ = (
928 928 Index('uem_email_idx', 'email'),
929 929 UniqueConstraint('email'),
930 930 {'extend_existing': True, 'mysql_engine': 'InnoDB',
931 931 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
932 932 )
933 933 __mapper_args__ = {}
934 934
935 935 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
936 936 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
937 937 _email = Column("email", String(255), nullable=True, unique=False, default=None)
938 938 user = relationship('User', lazy='joined')
939 939
940 940 @validates('_email')
941 941 def validate_email(self, key, email):
942 942 # check if this email is not main one
943 943 main_email = Session().query(User).filter(User.email == email).scalar()
944 944 if main_email is not None:
945 945 raise AttributeError('email %s is present is user table' % email)
946 946 return email
947 947
948 948 @hybrid_property
949 949 def email(self):
950 950 return self._email
951 951
952 952 @email.setter
953 953 def email(self, val):
954 954 self._email = val.lower() if val else None
955 955
956 956
957 957 class UserIpMap(Base, BaseModel):
958 958 __tablename__ = 'user_ip_map'
959 959 __table_args__ = (
960 960 UniqueConstraint('user_id', 'ip_addr'),
961 961 {'extend_existing': True, 'mysql_engine': 'InnoDB',
962 962 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
963 963 )
964 964 __mapper_args__ = {}
965 965
966 966 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
967 967 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
968 968 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
969 969 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
970 970 description = Column("description", String(10000), nullable=True, unique=None, default=None)
971 971 user = relationship('User', lazy='joined')
972 972
973 973 @classmethod
974 974 def _get_ip_range(cls, ip_addr):
975 975 net = ipaddress.ip_network(ip_addr, strict=False)
976 976 return [str(net.network_address), str(net.broadcast_address)]
977 977
978 978 def __json__(self):
979 979 return {
980 980 'ip_addr': self.ip_addr,
981 981 'ip_range': self._get_ip_range(self.ip_addr),
982 982 }
983 983
984 984 def __unicode__(self):
985 985 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
986 986 self.user_id, self.ip_addr)
987 987
988 988 class UserLog(Base, BaseModel):
989 989 __tablename__ = 'user_logs'
990 990 __table_args__ = (
991 991 {'extend_existing': True, 'mysql_engine': 'InnoDB',
992 992 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
993 993 )
994 994 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
995 995 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
996 996 username = Column("username", String(255), nullable=True, unique=None, default=None)
997 997 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
998 998 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
999 999 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1000 1000 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1001 1001 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1002 1002
1003 1003 def __unicode__(self):
1004 1004 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1005 1005 self.repository_name,
1006 1006 self.action)
1007 1007
1008 1008 @property
1009 1009 def action_as_day(self):
1010 1010 return datetime.date(*self.action_date.timetuple()[:3])
1011 1011
1012 1012 user = relationship('User')
1013 1013 repository = relationship('Repository', cascade='')
1014 1014
1015 1015
1016 1016 class UserGroup(Base, BaseModel):
1017 1017 __tablename__ = 'users_groups'
1018 1018 __table_args__ = (
1019 1019 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1020 1020 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1021 1021 )
1022 1022
1023 1023 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1024 1024 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1025 1025 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1026 1026 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1027 1027 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1028 1028 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1029 1029 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1030 1030 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1031 1031
1032 1032 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1033 1033 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1034 1034 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1035 1035 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1036 1036 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1037 1037 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1038 1038
1039 1039 user = relationship('User')
1040 1040
1041 1041 @hybrid_property
1042 1042 def group_data(self):
1043 1043 if not self._group_data:
1044 1044 return {}
1045 1045
1046 1046 try:
1047 1047 return json.loads(self._group_data)
1048 1048 except TypeError:
1049 1049 return {}
1050 1050
1051 1051 @group_data.setter
1052 1052 def group_data(self, val):
1053 1053 try:
1054 1054 self._group_data = json.dumps(val)
1055 1055 except Exception:
1056 1056 log.error(traceback.format_exc())
1057 1057
1058 1058 def __unicode__(self):
1059 1059 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1060 1060 self.users_group_id,
1061 1061 self.users_group_name)
1062 1062
1063 1063 @classmethod
1064 1064 def get_by_group_name(cls, group_name, cache=False,
1065 1065 case_insensitive=False):
1066 1066 if case_insensitive:
1067 1067 q = cls.query().filter(func.lower(cls.users_group_name) ==
1068 1068 func.lower(group_name))
1069 1069
1070 1070 else:
1071 1071 q = cls.query().filter(cls.users_group_name == group_name)
1072 1072 if cache:
1073 1073 q = q.options(FromCache(
1074 1074 "sql_cache_short",
1075 1075 "get_group_%s" % _hash_key(group_name)))
1076 1076 return q.scalar()
1077 1077
1078 1078 @classmethod
1079 1079 def get(cls, user_group_id, cache=False):
1080 1080 user_group = cls.query()
1081 1081 if cache:
1082 1082 user_group = user_group.options(FromCache("sql_cache_short",
1083 1083 "get_users_group_%s" % user_group_id))
1084 1084 return user_group.get(user_group_id)
1085 1085
1086 1086 def permissions(self, with_admins=True, with_owner=True):
1087 1087 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1088 1088 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1089 1089 joinedload(UserUserGroupToPerm.user),
1090 1090 joinedload(UserUserGroupToPerm.permission),)
1091 1091
1092 1092 # get owners and admins and permissions. We do a trick of re-writing
1093 1093 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1094 1094 # has a global reference and changing one object propagates to all
1095 1095 # others. This means if admin is also an owner admin_row that change
1096 1096 # would propagate to both objects
1097 1097 perm_rows = []
1098 1098 for _usr in q.all():
1099 1099 usr = AttributeDict(_usr.user.get_dict())
1100 1100 usr.permission = _usr.permission.permission_name
1101 1101 perm_rows.append(usr)
1102 1102
1103 1103 # filter the perm rows by 'default' first and then sort them by
1104 1104 # admin,write,read,none permissions sorted again alphabetically in
1105 1105 # each group
1106 1106 perm_rows = sorted(perm_rows, key=display_sort)
1107 1107
1108 1108 _admin_perm = 'usergroup.admin'
1109 1109 owner_row = []
1110 1110 if with_owner:
1111 1111 usr = AttributeDict(self.user.get_dict())
1112 1112 usr.owner_row = True
1113 1113 usr.permission = _admin_perm
1114 1114 owner_row.append(usr)
1115 1115
1116 1116 super_admin_rows = []
1117 1117 if with_admins:
1118 1118 for usr in User.get_all_super_admins():
1119 1119 # if this admin is also owner, don't double the record
1120 1120 if usr.user_id == owner_row[0].user_id:
1121 1121 owner_row[0].admin_row = True
1122 1122 else:
1123 1123 usr = AttributeDict(usr.get_dict())
1124 1124 usr.admin_row = True
1125 1125 usr.permission = _admin_perm
1126 1126 super_admin_rows.append(usr)
1127 1127
1128 1128 return super_admin_rows + owner_row + perm_rows
1129 1129
1130 1130 def permission_user_groups(self):
1131 1131 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1132 1132 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1133 1133 joinedload(UserGroupUserGroupToPerm.target_user_group),
1134 1134 joinedload(UserGroupUserGroupToPerm.permission),)
1135 1135
1136 1136 perm_rows = []
1137 1137 for _user_group in q.all():
1138 1138 usr = AttributeDict(_user_group.user_group.get_dict())
1139 1139 usr.permission = _user_group.permission.permission_name
1140 1140 perm_rows.append(usr)
1141 1141
1142 1142 return perm_rows
1143 1143
1144 1144 def _get_default_perms(self, user_group, suffix=''):
1145 1145 from rhodecode.model.permission import PermissionModel
1146 1146 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1147 1147
1148 1148 def get_default_perms(self, suffix=''):
1149 1149 return self._get_default_perms(self, suffix)
1150 1150
1151 1151 def get_api_data(self, with_group_members=True, include_secrets=False):
1152 1152 """
1153 1153 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1154 1154 basically forwarded.
1155 1155
1156 1156 """
1157 1157 user_group = self
1158 1158
1159 1159 data = {
1160 1160 'users_group_id': user_group.users_group_id,
1161 1161 'group_name': user_group.users_group_name,
1162 1162 'group_description': user_group.user_group_description,
1163 1163 'active': user_group.users_group_active,
1164 1164 'owner': user_group.user.username,
1165 1165 }
1166 1166 if with_group_members:
1167 1167 users = []
1168 1168 for user in user_group.members:
1169 1169 user = user.user
1170 1170 users.append(user.get_api_data(include_secrets=include_secrets))
1171 1171 data['users'] = users
1172 1172
1173 1173 return data
1174 1174
1175 1175
1176 1176 class UserGroupMember(Base, BaseModel):
1177 1177 __tablename__ = 'users_groups_members'
1178 1178 __table_args__ = (
1179 1179 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1180 1180 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1181 1181 )
1182 1182
1183 1183 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1184 1184 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1185 1185 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1186 1186
1187 1187 user = relationship('User', lazy='joined')
1188 1188 users_group = relationship('UserGroup')
1189 1189
1190 1190 def __init__(self, gr_id='', u_id=''):
1191 1191 self.users_group_id = gr_id
1192 1192 self.user_id = u_id
1193 1193
1194 1194
1195 1195 class RepositoryField(Base, BaseModel):
1196 1196 __tablename__ = 'repositories_fields'
1197 1197 __table_args__ = (
1198 1198 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1199 1199 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1200 1200 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1201 1201 )
1202 1202 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1203 1203
1204 1204 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1205 1205 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1206 1206 field_key = Column("field_key", String(250))
1207 1207 field_label = Column("field_label", String(1024), nullable=False)
1208 1208 field_value = Column("field_value", String(10000), nullable=False)
1209 1209 field_desc = Column("field_desc", String(1024), nullable=False)
1210 1210 field_type = Column("field_type", String(255), nullable=False, unique=None)
1211 1211 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1212 1212
1213 1213 repository = relationship('Repository')
1214 1214
1215 1215 @property
1216 1216 def field_key_prefixed(self):
1217 1217 return 'ex_%s' % self.field_key
1218 1218
1219 1219 @classmethod
1220 1220 def un_prefix_key(cls, key):
1221 1221 if key.startswith(cls.PREFIX):
1222 1222 return key[len(cls.PREFIX):]
1223 1223 return key
1224 1224
1225 1225 @classmethod
1226 1226 def get_by_key_name(cls, key, repo):
1227 1227 row = cls.query()\
1228 1228 .filter(cls.repository == repo)\
1229 1229 .filter(cls.field_key == key).scalar()
1230 1230 return row
1231 1231
1232 1232
1233 1233 class Repository(Base, BaseModel):
1234 1234 __tablename__ = 'repositories'
1235 1235 __table_args__ = (
1236 1236 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1237 1237 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1238 1238 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1239 1239 )
1240 1240 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1241 1241 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1242 1242
1243 1243 STATE_CREATED = 'repo_state_created'
1244 1244 STATE_PENDING = 'repo_state_pending'
1245 1245 STATE_ERROR = 'repo_state_error'
1246 1246
1247 1247 LOCK_AUTOMATIC = 'lock_auto'
1248 1248 LOCK_API = 'lock_api'
1249 1249 LOCK_WEB = 'lock_web'
1250 1250 LOCK_PULL = 'lock_pull'
1251 1251
1252 1252 NAME_SEP = URL_SEP
1253 1253
1254 1254 repo_id = Column(
1255 1255 "repo_id", Integer(), nullable=False, unique=True, default=None,
1256 1256 primary_key=True)
1257 1257 _repo_name = Column(
1258 1258 "repo_name", Text(), nullable=False, default=None)
1259 1259 _repo_name_hash = Column(
1260 1260 "repo_name_hash", String(255), nullable=False, unique=True)
1261 1261 repo_state = Column("repo_state", String(255), nullable=True)
1262 1262
1263 1263 clone_uri = Column(
1264 1264 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1265 1265 default=None)
1266 1266 repo_type = Column(
1267 1267 "repo_type", String(255), nullable=False, unique=False, default=None)
1268 1268 user_id = Column(
1269 1269 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1270 1270 unique=False, default=None)
1271 1271 private = Column(
1272 1272 "private", Boolean(), nullable=True, unique=None, default=None)
1273 1273 enable_statistics = Column(
1274 1274 "statistics", Boolean(), nullable=True, unique=None, default=True)
1275 1275 enable_downloads = Column(
1276 1276 "downloads", Boolean(), nullable=True, unique=None, default=True)
1277 1277 description = Column(
1278 1278 "description", String(10000), nullable=True, unique=None, default=None)
1279 1279 created_on = Column(
1280 1280 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1281 1281 default=datetime.datetime.now)
1282 1282 updated_on = Column(
1283 1283 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1284 1284 default=datetime.datetime.now)
1285 1285 _landing_revision = Column(
1286 1286 "landing_revision", String(255), nullable=False, unique=False,
1287 1287 default=None)
1288 1288 enable_locking = Column(
1289 1289 "enable_locking", Boolean(), nullable=False, unique=None,
1290 1290 default=False)
1291 1291 _locked = Column(
1292 1292 "locked", String(255), nullable=True, unique=False, default=None)
1293 1293 _changeset_cache = Column(
1294 1294 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1295 1295
1296 1296 fork_id = Column(
1297 1297 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1298 1298 nullable=True, unique=False, default=None)
1299 1299 group_id = Column(
1300 1300 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1301 1301 unique=False, default=None)
1302 1302
1303 1303 user = relationship('User', lazy='joined')
1304 1304 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1305 1305 group = relationship('RepoGroup', lazy='joined')
1306 1306 repo_to_perm = relationship(
1307 1307 'UserRepoToPerm', cascade='all',
1308 1308 order_by='UserRepoToPerm.repo_to_perm_id')
1309 1309 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1310 1310 stats = relationship('Statistics', cascade='all', uselist=False)
1311 1311
1312 1312 followers = relationship(
1313 1313 'UserFollowing',
1314 1314 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1315 1315 cascade='all')
1316 1316 extra_fields = relationship(
1317 1317 'RepositoryField', cascade="all, delete, delete-orphan")
1318 1318 logs = relationship('UserLog')
1319 1319 comments = relationship(
1320 1320 'ChangesetComment', cascade="all, delete, delete-orphan")
1321 1321 pull_requests_source = relationship(
1322 1322 'PullRequest',
1323 1323 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1324 1324 cascade="all, delete, delete-orphan")
1325 1325 pull_requests_target = relationship(
1326 1326 'PullRequest',
1327 1327 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1328 1328 cascade="all, delete, delete-orphan")
1329 1329 ui = relationship('RepoRhodeCodeUi', cascade="all")
1330 1330 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1331 1331 integrations = relationship('Integration',
1332 1332 cascade="all, delete, delete-orphan")
1333 1333
1334 1334 def __unicode__(self):
1335 1335 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1336 1336 safe_unicode(self.repo_name))
1337 1337
1338 1338 @hybrid_property
1339 1339 def landing_rev(self):
1340 1340 # always should return [rev_type, rev]
1341 1341 if self._landing_revision:
1342 1342 _rev_info = self._landing_revision.split(':')
1343 1343 if len(_rev_info) < 2:
1344 1344 _rev_info.insert(0, 'rev')
1345 1345 return [_rev_info[0], _rev_info[1]]
1346 1346 return [None, None]
1347 1347
1348 1348 @landing_rev.setter
1349 1349 def landing_rev(self, val):
1350 1350 if ':' not in val:
1351 1351 raise ValueError('value must be delimited with `:` and consist '
1352 1352 'of <rev_type>:<rev>, got %s instead' % val)
1353 1353 self._landing_revision = val
1354 1354
1355 1355 @hybrid_property
1356 1356 def locked(self):
1357 1357 if self._locked:
1358 1358 user_id, timelocked, reason = self._locked.split(':')
1359 1359 lock_values = int(user_id), timelocked, reason
1360 1360 else:
1361 1361 lock_values = [None, None, None]
1362 1362 return lock_values
1363 1363
1364 1364 @locked.setter
1365 1365 def locked(self, val):
1366 1366 if val and isinstance(val, (list, tuple)):
1367 1367 self._locked = ':'.join(map(str, val))
1368 1368 else:
1369 1369 self._locked = None
1370 1370
1371 1371 @hybrid_property
1372 1372 def changeset_cache(self):
1373 1373 from rhodecode.lib.vcs.backends.base import EmptyCommit
1374 1374 dummy = EmptyCommit().__json__()
1375 1375 if not self._changeset_cache:
1376 1376 return dummy
1377 1377 try:
1378 1378 return json.loads(self._changeset_cache)
1379 1379 except TypeError:
1380 1380 return dummy
1381 1381 except Exception:
1382 1382 log.error(traceback.format_exc())
1383 1383 return dummy
1384 1384
1385 1385 @changeset_cache.setter
1386 1386 def changeset_cache(self, val):
1387 1387 try:
1388 1388 self._changeset_cache = json.dumps(val)
1389 1389 except Exception:
1390 1390 log.error(traceback.format_exc())
1391 1391
1392 1392 @hybrid_property
1393 1393 def repo_name(self):
1394 1394 return self._repo_name
1395 1395
1396 1396 @repo_name.setter
1397 1397 def repo_name(self, value):
1398 1398 self._repo_name = value
1399 1399 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1400 1400
1401 1401 @classmethod
1402 1402 def normalize_repo_name(cls, repo_name):
1403 1403 """
1404 1404 Normalizes os specific repo_name to the format internally stored inside
1405 1405 database using URL_SEP
1406 1406
1407 1407 :param cls:
1408 1408 :param repo_name:
1409 1409 """
1410 1410 return cls.NAME_SEP.join(repo_name.split(os.sep))
1411 1411
1412 1412 @classmethod
1413 1413 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1414 1414 session = Session()
1415 1415 q = session.query(cls).filter(cls.repo_name == repo_name)
1416 1416
1417 1417 if cache:
1418 1418 if identity_cache:
1419 1419 val = cls.identity_cache(session, 'repo_name', repo_name)
1420 1420 if val:
1421 1421 return val
1422 1422 else:
1423 1423 q = q.options(
1424 1424 FromCache("sql_cache_short",
1425 1425 "get_repo_by_name_%s" % _hash_key(repo_name)))
1426 1426
1427 1427 return q.scalar()
1428 1428
1429 1429 @classmethod
1430 1430 def get_by_full_path(cls, repo_full_path):
1431 1431 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1432 1432 repo_name = cls.normalize_repo_name(repo_name)
1433 1433 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1434 1434
1435 1435 @classmethod
1436 1436 def get_repo_forks(cls, repo_id):
1437 1437 return cls.query().filter(Repository.fork_id == repo_id)
1438 1438
1439 1439 @classmethod
1440 1440 def base_path(cls):
1441 1441 """
1442 1442 Returns base path when all repos are stored
1443 1443
1444 1444 :param cls:
1445 1445 """
1446 1446 q = Session().query(RhodeCodeUi)\
1447 1447 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1448 1448 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1449 1449 return q.one().ui_value
1450 1450
1451 1451 @classmethod
1452 1452 def is_valid(cls, repo_name):
1453 1453 """
1454 1454 returns True if given repo name is a valid filesystem repository
1455 1455
1456 1456 :param cls:
1457 1457 :param repo_name:
1458 1458 """
1459 1459 from rhodecode.lib.utils import is_valid_repo
1460 1460
1461 1461 return is_valid_repo(repo_name, cls.base_path())
1462 1462
1463 1463 @classmethod
1464 1464 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1465 1465 case_insensitive=True):
1466 1466 q = Repository.query()
1467 1467
1468 1468 if not isinstance(user_id, Optional):
1469 1469 q = q.filter(Repository.user_id == user_id)
1470 1470
1471 1471 if not isinstance(group_id, Optional):
1472 1472 q = q.filter(Repository.group_id == group_id)
1473 1473
1474 1474 if case_insensitive:
1475 1475 q = q.order_by(func.lower(Repository.repo_name))
1476 1476 else:
1477 1477 q = q.order_by(Repository.repo_name)
1478 1478 return q.all()
1479 1479
1480 1480 @property
1481 1481 def forks(self):
1482 1482 """
1483 1483 Return forks of this repo
1484 1484 """
1485 1485 return Repository.get_repo_forks(self.repo_id)
1486 1486
1487 1487 @property
1488 1488 def parent(self):
1489 1489 """
1490 1490 Returns fork parent
1491 1491 """
1492 1492 return self.fork
1493 1493
1494 1494 @property
1495 1495 def just_name(self):
1496 1496 return self.repo_name.split(self.NAME_SEP)[-1]
1497 1497
1498 1498 @property
1499 1499 def groups_with_parents(self):
1500 1500 groups = []
1501 1501 if self.group is None:
1502 1502 return groups
1503 1503
1504 1504 cur_gr = self.group
1505 1505 groups.insert(0, cur_gr)
1506 1506 while 1:
1507 1507 gr = getattr(cur_gr, 'parent_group', None)
1508 1508 cur_gr = cur_gr.parent_group
1509 1509 if gr is None:
1510 1510 break
1511 1511 groups.insert(0, gr)
1512 1512
1513 1513 return groups
1514 1514
1515 1515 @property
1516 1516 def groups_and_repo(self):
1517 1517 return self.groups_with_parents, self
1518 1518
1519 1519 @LazyProperty
1520 1520 def repo_path(self):
1521 1521 """
1522 1522 Returns base full path for that repository means where it actually
1523 1523 exists on a filesystem
1524 1524 """
1525 1525 q = Session().query(RhodeCodeUi).filter(
1526 1526 RhodeCodeUi.ui_key == self.NAME_SEP)
1527 1527 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1528 1528 return q.one().ui_value
1529 1529
1530 1530 @property
1531 1531 def repo_full_path(self):
1532 1532 p = [self.repo_path]
1533 1533 # we need to split the name by / since this is how we store the
1534 1534 # names in the database, but that eventually needs to be converted
1535 1535 # into a valid system path
1536 1536 p += self.repo_name.split(self.NAME_SEP)
1537 1537 return os.path.join(*map(safe_unicode, p))
1538 1538
1539 1539 @property
1540 1540 def cache_keys(self):
1541 1541 """
1542 1542 Returns associated cache keys for that repo
1543 1543 """
1544 1544 return CacheKey.query()\
1545 1545 .filter(CacheKey.cache_args == self.repo_name)\
1546 1546 .order_by(CacheKey.cache_key)\
1547 1547 .all()
1548 1548
1549 1549 def get_new_name(self, repo_name):
1550 1550 """
1551 1551 returns new full repository name based on assigned group and new new
1552 1552
1553 1553 :param group_name:
1554 1554 """
1555 1555 path_prefix = self.group.full_path_splitted if self.group else []
1556 1556 return self.NAME_SEP.join(path_prefix + [repo_name])
1557 1557
1558 1558 @property
1559 1559 def _config(self):
1560 1560 """
1561 1561 Returns db based config object.
1562 1562 """
1563 1563 from rhodecode.lib.utils import make_db_config
1564 1564 return make_db_config(clear_session=False, repo=self)
1565 1565
1566 1566 def permissions(self, with_admins=True, with_owner=True):
1567 1567 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1568 1568 q = q.options(joinedload(UserRepoToPerm.repository),
1569 1569 joinedload(UserRepoToPerm.user),
1570 1570 joinedload(UserRepoToPerm.permission),)
1571 1571
1572 1572 # get owners and admins and permissions. We do a trick of re-writing
1573 1573 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1574 1574 # has a global reference and changing one object propagates to all
1575 1575 # others. This means if admin is also an owner admin_row that change
1576 1576 # would propagate to both objects
1577 1577 perm_rows = []
1578 1578 for _usr in q.all():
1579 1579 usr = AttributeDict(_usr.user.get_dict())
1580 1580 usr.permission = _usr.permission.permission_name
1581 1581 perm_rows.append(usr)
1582 1582
1583 1583 # filter the perm rows by 'default' first and then sort them by
1584 1584 # admin,write,read,none permissions sorted again alphabetically in
1585 1585 # each group
1586 1586 perm_rows = sorted(perm_rows, key=display_sort)
1587 1587
1588 1588 _admin_perm = 'repository.admin'
1589 1589 owner_row = []
1590 1590 if with_owner:
1591 1591 usr = AttributeDict(self.user.get_dict())
1592 1592 usr.owner_row = True
1593 1593 usr.permission = _admin_perm
1594 1594 owner_row.append(usr)
1595 1595
1596 1596 super_admin_rows = []
1597 1597 if with_admins:
1598 1598 for usr in User.get_all_super_admins():
1599 1599 # if this admin is also owner, don't double the record
1600 1600 if usr.user_id == owner_row[0].user_id:
1601 1601 owner_row[0].admin_row = True
1602 1602 else:
1603 1603 usr = AttributeDict(usr.get_dict())
1604 1604 usr.admin_row = True
1605 1605 usr.permission = _admin_perm
1606 1606 super_admin_rows.append(usr)
1607 1607
1608 1608 return super_admin_rows + owner_row + perm_rows
1609 1609
1610 1610 def permission_user_groups(self):
1611 1611 q = UserGroupRepoToPerm.query().filter(
1612 1612 UserGroupRepoToPerm.repository == self)
1613 1613 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1614 1614 joinedload(UserGroupRepoToPerm.users_group),
1615 1615 joinedload(UserGroupRepoToPerm.permission),)
1616 1616
1617 1617 perm_rows = []
1618 1618 for _user_group in q.all():
1619 1619 usr = AttributeDict(_user_group.users_group.get_dict())
1620 1620 usr.permission = _user_group.permission.permission_name
1621 1621 perm_rows.append(usr)
1622 1622
1623 1623 return perm_rows
1624 1624
1625 1625 def get_api_data(self, include_secrets=False):
1626 1626 """
1627 1627 Common function for generating repo api data
1628 1628
1629 1629 :param include_secrets: See :meth:`User.get_api_data`.
1630 1630
1631 1631 """
1632 1632 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1633 1633 # move this methods on models level.
1634 1634 from rhodecode.model.settings import SettingsModel
1635 1635
1636 1636 repo = self
1637 1637 _user_id, _time, _reason = self.locked
1638 1638
1639 1639 data = {
1640 1640 'repo_id': repo.repo_id,
1641 1641 'repo_name': repo.repo_name,
1642 1642 'repo_type': repo.repo_type,
1643 1643 'clone_uri': repo.clone_uri or '',
1644 1644 'url': url('summary_home', repo_name=self.repo_name, qualified=True),
1645 1645 'private': repo.private,
1646 1646 'created_on': repo.created_on,
1647 1647 'description': repo.description,
1648 1648 'landing_rev': repo.landing_rev,
1649 1649 'owner': repo.user.username,
1650 1650 'fork_of': repo.fork.repo_name if repo.fork else None,
1651 1651 'enable_statistics': repo.enable_statistics,
1652 1652 'enable_locking': repo.enable_locking,
1653 1653 'enable_downloads': repo.enable_downloads,
1654 1654 'last_changeset': repo.changeset_cache,
1655 1655 'locked_by': User.get(_user_id).get_api_data(
1656 1656 include_secrets=include_secrets) if _user_id else None,
1657 1657 'locked_date': time_to_datetime(_time) if _time else None,
1658 1658 'lock_reason': _reason if _reason else None,
1659 1659 }
1660 1660
1661 1661 # TODO: mikhail: should be per-repo settings here
1662 1662 rc_config = SettingsModel().get_all_settings()
1663 1663 repository_fields = str2bool(
1664 1664 rc_config.get('rhodecode_repository_fields'))
1665 1665 if repository_fields:
1666 1666 for f in self.extra_fields:
1667 1667 data[f.field_key_prefixed] = f.field_value
1668 1668
1669 1669 return data
1670 1670
1671 1671 @classmethod
1672 1672 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1673 1673 if not lock_time:
1674 1674 lock_time = time.time()
1675 1675 if not lock_reason:
1676 1676 lock_reason = cls.LOCK_AUTOMATIC
1677 1677 repo.locked = [user_id, lock_time, lock_reason]
1678 1678 Session().add(repo)
1679 1679 Session().commit()
1680 1680
1681 1681 @classmethod
1682 1682 def unlock(cls, repo):
1683 1683 repo.locked = None
1684 1684 Session().add(repo)
1685 1685 Session().commit()
1686 1686
1687 1687 @classmethod
1688 1688 def getlock(cls, repo):
1689 1689 return repo.locked
1690 1690
1691 1691 def is_user_lock(self, user_id):
1692 1692 if self.lock[0]:
1693 1693 lock_user_id = safe_int(self.lock[0])
1694 1694 user_id = safe_int(user_id)
1695 1695 # both are ints, and they are equal
1696 1696 return all([lock_user_id, user_id]) and lock_user_id == user_id
1697 1697
1698 1698 return False
1699 1699
1700 1700 def get_locking_state(self, action, user_id, only_when_enabled=True):
1701 1701 """
1702 1702 Checks locking on this repository, if locking is enabled and lock is
1703 1703 present returns a tuple of make_lock, locked, locked_by.
1704 1704 make_lock can have 3 states None (do nothing) True, make lock
1705 1705 False release lock, This value is later propagated to hooks, which
1706 1706 do the locking. Think about this as signals passed to hooks what to do.
1707 1707
1708 1708 """
1709 1709 # TODO: johbo: This is part of the business logic and should be moved
1710 1710 # into the RepositoryModel.
1711 1711
1712 1712 if action not in ('push', 'pull'):
1713 1713 raise ValueError("Invalid action value: %s" % repr(action))
1714 1714
1715 1715 # defines if locked error should be thrown to user
1716 1716 currently_locked = False
1717 1717 # defines if new lock should be made, tri-state
1718 1718 make_lock = None
1719 1719 repo = self
1720 1720 user = User.get(user_id)
1721 1721
1722 1722 lock_info = repo.locked
1723 1723
1724 1724 if repo and (repo.enable_locking or not only_when_enabled):
1725 1725 if action == 'push':
1726 1726 # check if it's already locked !, if it is compare users
1727 1727 locked_by_user_id = lock_info[0]
1728 1728 if user.user_id == locked_by_user_id:
1729 1729 log.debug(
1730 1730 'Got `push` action from user %s, now unlocking', user)
1731 1731 # unlock if we have push from user who locked
1732 1732 make_lock = False
1733 1733 else:
1734 1734 # we're not the same user who locked, ban with
1735 1735 # code defined in settings (default is 423 HTTP Locked) !
1736 1736 log.debug('Repo %s is currently locked by %s', repo, user)
1737 1737 currently_locked = True
1738 1738 elif action == 'pull':
1739 1739 # [0] user [1] date
1740 1740 if lock_info[0] and lock_info[1]:
1741 1741 log.debug('Repo %s is currently locked by %s', repo, user)
1742 1742 currently_locked = True
1743 1743 else:
1744 1744 log.debug('Setting lock on repo %s by %s', repo, user)
1745 1745 make_lock = True
1746 1746
1747 1747 else:
1748 1748 log.debug('Repository %s do not have locking enabled', repo)
1749 1749
1750 1750 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
1751 1751 make_lock, currently_locked, lock_info)
1752 1752
1753 1753 from rhodecode.lib.auth import HasRepoPermissionAny
1754 1754 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
1755 1755 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
1756 1756 # if we don't have at least write permission we cannot make a lock
1757 1757 log.debug('lock state reset back to FALSE due to lack '
1758 1758 'of at least read permission')
1759 1759 make_lock = False
1760 1760
1761 1761 return make_lock, currently_locked, lock_info
1762 1762
1763 1763 @property
1764 1764 def last_db_change(self):
1765 1765 return self.updated_on
1766 1766
1767 1767 @property
1768 1768 def clone_uri_hidden(self):
1769 1769 clone_uri = self.clone_uri
1770 1770 if clone_uri:
1771 1771 import urlobject
1772 1772 url_obj = urlobject.URLObject(clone_uri)
1773 1773 if url_obj.password:
1774 1774 clone_uri = url_obj.with_password('*****')
1775 1775 return clone_uri
1776 1776
1777 1777 def clone_url(self, **override):
1778 1778 qualified_home_url = url('home', qualified=True)
1779 1779
1780 1780 uri_tmpl = None
1781 1781 if 'with_id' in override:
1782 1782 uri_tmpl = self.DEFAULT_CLONE_URI_ID
1783 1783 del override['with_id']
1784 1784
1785 1785 if 'uri_tmpl' in override:
1786 1786 uri_tmpl = override['uri_tmpl']
1787 1787 del override['uri_tmpl']
1788 1788
1789 1789 # we didn't override our tmpl from **overrides
1790 1790 if not uri_tmpl:
1791 1791 uri_tmpl = self.DEFAULT_CLONE_URI
1792 1792 try:
1793 1793 from pylons import tmpl_context as c
1794 1794 uri_tmpl = c.clone_uri_tmpl
1795 1795 except Exception:
1796 1796 # in any case if we call this outside of request context,
1797 1797 # ie, not having tmpl_context set up
1798 1798 pass
1799 1799
1800 1800 return get_clone_url(uri_tmpl=uri_tmpl,
1801 1801 qualifed_home_url=qualified_home_url,
1802 1802 repo_name=self.repo_name,
1803 1803 repo_id=self.repo_id, **override)
1804 1804
1805 1805 def set_state(self, state):
1806 1806 self.repo_state = state
1807 1807 Session().add(self)
1808 1808 #==========================================================================
1809 1809 # SCM PROPERTIES
1810 1810 #==========================================================================
1811 1811
1812 1812 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
1813 1813 return get_commit_safe(
1814 1814 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
1815 1815
1816 1816 def get_changeset(self, rev=None, pre_load=None):
1817 1817 warnings.warn("Use get_commit", DeprecationWarning)
1818 1818 commit_id = None
1819 1819 commit_idx = None
1820 1820 if isinstance(rev, basestring):
1821 1821 commit_id = rev
1822 1822 else:
1823 1823 commit_idx = rev
1824 1824 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
1825 1825 pre_load=pre_load)
1826 1826
1827 1827 def get_landing_commit(self):
1828 1828 """
1829 1829 Returns landing commit, or if that doesn't exist returns the tip
1830 1830 """
1831 1831 _rev_type, _rev = self.landing_rev
1832 1832 commit = self.get_commit(_rev)
1833 1833 if isinstance(commit, EmptyCommit):
1834 1834 return self.get_commit()
1835 1835 return commit
1836 1836
1837 1837 def update_commit_cache(self, cs_cache=None, config=None):
1838 1838 """
1839 1839 Update cache of last changeset for repository, keys should be::
1840 1840
1841 1841 short_id
1842 1842 raw_id
1843 1843 revision
1844 1844 parents
1845 1845 message
1846 1846 date
1847 1847 author
1848 1848
1849 1849 :param cs_cache:
1850 1850 """
1851 1851 from rhodecode.lib.vcs.backends.base import BaseChangeset
1852 1852 if cs_cache is None:
1853 1853 # use no-cache version here
1854 1854 scm_repo = self.scm_instance(cache=False, config=config)
1855 1855 if scm_repo:
1856 1856 cs_cache = scm_repo.get_commit(
1857 1857 pre_load=["author", "date", "message", "parents"])
1858 1858 else:
1859 1859 cs_cache = EmptyCommit()
1860 1860
1861 1861 if isinstance(cs_cache, BaseChangeset):
1862 1862 cs_cache = cs_cache.__json__()
1863 1863
1864 1864 def is_outdated(new_cs_cache):
1865 1865 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
1866 1866 new_cs_cache['revision'] != self.changeset_cache['revision']):
1867 1867 return True
1868 1868 return False
1869 1869
1870 1870 # check if we have maybe already latest cached revision
1871 1871 if is_outdated(cs_cache) or not self.changeset_cache:
1872 1872 _default = datetime.datetime.fromtimestamp(0)
1873 1873 last_change = cs_cache.get('date') or _default
1874 1874 log.debug('updated repo %s with new cs cache %s',
1875 1875 self.repo_name, cs_cache)
1876 1876 self.updated_on = last_change
1877 1877 self.changeset_cache = cs_cache
1878 1878 Session().add(self)
1879 1879 Session().commit()
1880 1880 else:
1881 1881 log.debug('Skipping update_commit_cache for repo:`%s` '
1882 1882 'commit already with latest changes', self.repo_name)
1883 1883
1884 1884 @property
1885 1885 def tip(self):
1886 1886 return self.get_commit('tip')
1887 1887
1888 1888 @property
1889 1889 def author(self):
1890 1890 return self.tip.author
1891 1891
1892 1892 @property
1893 1893 def last_change(self):
1894 1894 return self.scm_instance().last_change
1895 1895
1896 1896 def get_comments(self, revisions=None):
1897 1897 """
1898 1898 Returns comments for this repository grouped by revisions
1899 1899
1900 1900 :param revisions: filter query by revisions only
1901 1901 """
1902 1902 cmts = ChangesetComment.query()\
1903 1903 .filter(ChangesetComment.repo == self)
1904 1904 if revisions:
1905 1905 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
1906 1906 grouped = collections.defaultdict(list)
1907 1907 for cmt in cmts.all():
1908 1908 grouped[cmt.revision].append(cmt)
1909 1909 return grouped
1910 1910
1911 1911 def statuses(self, revisions=None):
1912 1912 """
1913 1913 Returns statuses for this repository
1914 1914
1915 1915 :param revisions: list of revisions to get statuses for
1916 1916 """
1917 1917 statuses = ChangesetStatus.query()\
1918 1918 .filter(ChangesetStatus.repo == self)\
1919 1919 .filter(ChangesetStatus.version == 0)
1920 1920
1921 1921 if revisions:
1922 1922 # Try doing the filtering in chunks to avoid hitting limits
1923 1923 size = 500
1924 1924 status_results = []
1925 1925 for chunk in xrange(0, len(revisions), size):
1926 1926 status_results += statuses.filter(
1927 1927 ChangesetStatus.revision.in_(
1928 1928 revisions[chunk: chunk+size])
1929 1929 ).all()
1930 1930 else:
1931 1931 status_results = statuses.all()
1932 1932
1933 1933 grouped = {}
1934 1934
1935 1935 # maybe we have open new pullrequest without a status?
1936 1936 stat = ChangesetStatus.STATUS_UNDER_REVIEW
1937 1937 status_lbl = ChangesetStatus.get_status_lbl(stat)
1938 1938 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
1939 1939 for rev in pr.revisions:
1940 1940 pr_id = pr.pull_request_id
1941 1941 pr_repo = pr.target_repo.repo_name
1942 1942 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
1943 1943
1944 1944 for stat in status_results:
1945 1945 pr_id = pr_repo = None
1946 1946 if stat.pull_request:
1947 1947 pr_id = stat.pull_request.pull_request_id
1948 1948 pr_repo = stat.pull_request.target_repo.repo_name
1949 1949 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
1950 1950 pr_id, pr_repo]
1951 1951 return grouped
1952 1952
1953 1953 # ==========================================================================
1954 1954 # SCM CACHE INSTANCE
1955 1955 # ==========================================================================
1956 1956
1957 1957 def scm_instance(self, **kwargs):
1958 1958 import rhodecode
1959 1959
1960 1960 # Passing a config will not hit the cache currently only used
1961 1961 # for repo2dbmapper
1962 1962 config = kwargs.pop('config', None)
1963 1963 cache = kwargs.pop('cache', None)
1964 1964 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
1965 1965 # if cache is NOT defined use default global, else we have a full
1966 1966 # control over cache behaviour
1967 1967 if cache is None and full_cache and not config:
1968 1968 return self._get_instance_cached()
1969 1969 return self._get_instance(cache=bool(cache), config=config)
1970 1970
1971 1971 def _get_instance_cached(self):
1972 1972 @cache_region('long_term')
1973 1973 def _get_repo(cache_key):
1974 1974 return self._get_instance()
1975 1975
1976 1976 invalidator_context = CacheKey.repo_context_cache(
1977 1977 _get_repo, self.repo_name, None, thread_scoped=True)
1978 1978
1979 1979 with invalidator_context as context:
1980 1980 context.invalidate()
1981 1981 repo = context.compute()
1982 1982
1983 1983 return repo
1984 1984
1985 1985 def _get_instance(self, cache=True, config=None):
1986 1986 config = config or self._config
1987 1987 custom_wire = {
1988 1988 'cache': cache # controls the vcs.remote cache
1989 1989 }
1990 1990 repo = get_vcs_instance(
1991 1991 repo_path=safe_str(self.repo_full_path),
1992 1992 config=config,
1993 1993 with_wire=custom_wire,
1994 1994 create=False,
1995 1995 _vcs_alias=self.repo_type)
1996 1996
1997 1997 return repo
1998 1998
1999 1999 def __json__(self):
2000 2000 return {'landing_rev': self.landing_rev}
2001 2001
2002 2002 def get_dict(self):
2003 2003
2004 2004 # Since we transformed `repo_name` to a hybrid property, we need to
2005 2005 # keep compatibility with the code which uses `repo_name` field.
2006 2006
2007 2007 result = super(Repository, self).get_dict()
2008 2008 result['repo_name'] = result.pop('_repo_name', None)
2009 2009 return result
2010 2010
2011 2011
2012 2012 class RepoGroup(Base, BaseModel):
2013 2013 __tablename__ = 'groups'
2014 2014 __table_args__ = (
2015 2015 UniqueConstraint('group_name', 'group_parent_id'),
2016 2016 CheckConstraint('group_id != group_parent_id'),
2017 2017 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2018 2018 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2019 2019 )
2020 2020 __mapper_args__ = {'order_by': 'group_name'}
2021 2021
2022 2022 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2023 2023
2024 2024 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2025 2025 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2026 2026 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2027 2027 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2028 2028 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2029 2029 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2030 2030 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2031 2031 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2032 2032
2033 2033 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2034 2034 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2035 2035 parent_group = relationship('RepoGroup', remote_side=group_id)
2036 2036 user = relationship('User')
2037 2037 integrations = relationship('Integration',
2038 2038 cascade="all, delete, delete-orphan")
2039 2039
2040 2040 def __init__(self, group_name='', parent_group=None):
2041 2041 self.group_name = group_name
2042 2042 self.parent_group = parent_group
2043 2043
2044 2044 def __unicode__(self):
2045 2045 return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
2046 2046 self.group_name)
2047 2047
2048 2048 @classmethod
2049 2049 def _generate_choice(cls, repo_group):
2050 2050 from webhelpers.html import literal as _literal
2051 2051 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2052 2052 return repo_group.group_id, _name(repo_group.full_path_splitted)
2053 2053
2054 2054 @classmethod
2055 2055 def groups_choices(cls, groups=None, show_empty_group=True):
2056 2056 if not groups:
2057 2057 groups = cls.query().all()
2058 2058
2059 2059 repo_groups = []
2060 2060 if show_empty_group:
2061 2061 repo_groups = [('-1', u'-- %s --' % _('No parent'))]
2062 2062
2063 2063 repo_groups.extend([cls._generate_choice(x) for x in groups])
2064 2064
2065 2065 repo_groups = sorted(
2066 2066 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2067 2067 return repo_groups
2068 2068
2069 2069 @classmethod
2070 2070 def url_sep(cls):
2071 2071 return URL_SEP
2072 2072
2073 2073 @classmethod
2074 2074 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2075 2075 if case_insensitive:
2076 2076 gr = cls.query().filter(func.lower(cls.group_name)
2077 2077 == func.lower(group_name))
2078 2078 else:
2079 2079 gr = cls.query().filter(cls.group_name == group_name)
2080 2080 if cache:
2081 2081 gr = gr.options(FromCache(
2082 2082 "sql_cache_short",
2083 2083 "get_group_%s" % _hash_key(group_name)))
2084 2084 return gr.scalar()
2085 2085
2086 2086 @classmethod
2087 2087 def get_user_personal_repo_group(cls, user_id):
2088 2088 user = User.get(user_id)
2089 2089 return cls.query()\
2090 2090 .filter(cls.personal == true())\
2091 2091 .filter(cls.user == user).scalar()
2092 2092
2093 2093 @classmethod
2094 2094 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2095 2095 case_insensitive=True):
2096 2096 q = RepoGroup.query()
2097 2097
2098 2098 if not isinstance(user_id, Optional):
2099 2099 q = q.filter(RepoGroup.user_id == user_id)
2100 2100
2101 2101 if not isinstance(group_id, Optional):
2102 2102 q = q.filter(RepoGroup.group_parent_id == group_id)
2103 2103
2104 2104 if case_insensitive:
2105 2105 q = q.order_by(func.lower(RepoGroup.group_name))
2106 2106 else:
2107 2107 q = q.order_by(RepoGroup.group_name)
2108 2108 return q.all()
2109 2109
2110 2110 @property
2111 2111 def parents(self):
2112 2112 parents_recursion_limit = 10
2113 2113 groups = []
2114 2114 if self.parent_group is None:
2115 2115 return groups
2116 2116 cur_gr = self.parent_group
2117 2117 groups.insert(0, cur_gr)
2118 2118 cnt = 0
2119 2119 while 1:
2120 2120 cnt += 1
2121 2121 gr = getattr(cur_gr, 'parent_group', None)
2122 2122 cur_gr = cur_gr.parent_group
2123 2123 if gr is None:
2124 2124 break
2125 2125 if cnt == parents_recursion_limit:
2126 2126 # this will prevent accidental infinit loops
2127 2127 log.error(('more than %s parents found for group %s, stopping '
2128 2128 'recursive parent fetching' % (parents_recursion_limit, self)))
2129 2129 break
2130 2130
2131 2131 groups.insert(0, gr)
2132 2132 return groups
2133 2133
2134 2134 @property
2135 2135 def children(self):
2136 2136 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2137 2137
2138 2138 @property
2139 2139 def name(self):
2140 2140 return self.group_name.split(RepoGroup.url_sep())[-1]
2141 2141
2142 2142 @property
2143 2143 def full_path(self):
2144 2144 return self.group_name
2145 2145
2146 2146 @property
2147 2147 def full_path_splitted(self):
2148 2148 return self.group_name.split(RepoGroup.url_sep())
2149 2149
2150 2150 @property
2151 2151 def repositories(self):
2152 2152 return Repository.query()\
2153 2153 .filter(Repository.group == self)\
2154 2154 .order_by(Repository.repo_name)
2155 2155
2156 2156 @property
2157 2157 def repositories_recursive_count(self):
2158 2158 cnt = self.repositories.count()
2159 2159
2160 2160 def children_count(group):
2161 2161 cnt = 0
2162 2162 for child in group.children:
2163 2163 cnt += child.repositories.count()
2164 2164 cnt += children_count(child)
2165 2165 return cnt
2166 2166
2167 2167 return cnt + children_count(self)
2168 2168
2169 2169 def _recursive_objects(self, include_repos=True):
2170 2170 all_ = []
2171 2171
2172 2172 def _get_members(root_gr):
2173 2173 if include_repos:
2174 2174 for r in root_gr.repositories:
2175 2175 all_.append(r)
2176 2176 childs = root_gr.children.all()
2177 2177 if childs:
2178 2178 for gr in childs:
2179 2179 all_.append(gr)
2180 2180 _get_members(gr)
2181 2181
2182 2182 _get_members(self)
2183 2183 return [self] + all_
2184 2184
2185 2185 def recursive_groups_and_repos(self):
2186 2186 """
2187 2187 Recursive return all groups, with repositories in those groups
2188 2188 """
2189 2189 return self._recursive_objects()
2190 2190
2191 2191 def recursive_groups(self):
2192 2192 """
2193 2193 Returns all children groups for this group including children of children
2194 2194 """
2195 2195 return self._recursive_objects(include_repos=False)
2196 2196
2197 2197 def get_new_name(self, group_name):
2198 2198 """
2199 2199 returns new full group name based on parent and new name
2200 2200
2201 2201 :param group_name:
2202 2202 """
2203 2203 path_prefix = (self.parent_group.full_path_splitted if
2204 2204 self.parent_group else [])
2205 2205 return RepoGroup.url_sep().join(path_prefix + [group_name])
2206 2206
2207 2207 def permissions(self, with_admins=True, with_owner=True):
2208 2208 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2209 2209 q = q.options(joinedload(UserRepoGroupToPerm.group),
2210 2210 joinedload(UserRepoGroupToPerm.user),
2211 2211 joinedload(UserRepoGroupToPerm.permission),)
2212 2212
2213 2213 # get owners and admins and permissions. We do a trick of re-writing
2214 2214 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2215 2215 # has a global reference and changing one object propagates to all
2216 2216 # others. This means if admin is also an owner admin_row that change
2217 2217 # would propagate to both objects
2218 2218 perm_rows = []
2219 2219 for _usr in q.all():
2220 2220 usr = AttributeDict(_usr.user.get_dict())
2221 2221 usr.permission = _usr.permission.permission_name
2222 2222 perm_rows.append(usr)
2223 2223
2224 2224 # filter the perm rows by 'default' first and then sort them by
2225 2225 # admin,write,read,none permissions sorted again alphabetically in
2226 2226 # each group
2227 2227 perm_rows = sorted(perm_rows, key=display_sort)
2228 2228
2229 2229 _admin_perm = 'group.admin'
2230 2230 owner_row = []
2231 2231 if with_owner:
2232 2232 usr = AttributeDict(self.user.get_dict())
2233 2233 usr.owner_row = True
2234 2234 usr.permission = _admin_perm
2235 2235 owner_row.append(usr)
2236 2236
2237 2237 super_admin_rows = []
2238 2238 if with_admins:
2239 2239 for usr in User.get_all_super_admins():
2240 2240 # if this admin is also owner, don't double the record
2241 2241 if usr.user_id == owner_row[0].user_id:
2242 2242 owner_row[0].admin_row = True
2243 2243 else:
2244 2244 usr = AttributeDict(usr.get_dict())
2245 2245 usr.admin_row = True
2246 2246 usr.permission = _admin_perm
2247 2247 super_admin_rows.append(usr)
2248 2248
2249 2249 return super_admin_rows + owner_row + perm_rows
2250 2250
2251 2251 def permission_user_groups(self):
2252 2252 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2253 2253 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2254 2254 joinedload(UserGroupRepoGroupToPerm.users_group),
2255 2255 joinedload(UserGroupRepoGroupToPerm.permission),)
2256 2256
2257 2257 perm_rows = []
2258 2258 for _user_group in q.all():
2259 2259 usr = AttributeDict(_user_group.users_group.get_dict())
2260 2260 usr.permission = _user_group.permission.permission_name
2261 2261 perm_rows.append(usr)
2262 2262
2263 2263 return perm_rows
2264 2264
2265 2265 def get_api_data(self):
2266 2266 """
2267 2267 Common function for generating api data
2268 2268
2269 2269 """
2270 2270 group = self
2271 2271 data = {
2272 2272 'group_id': group.group_id,
2273 2273 'group_name': group.group_name,
2274 2274 'group_description': group.group_description,
2275 2275 'parent_group': group.parent_group.group_name if group.parent_group else None,
2276 2276 'repositories': [x.repo_name for x in group.repositories],
2277 2277 'owner': group.user.username,
2278 2278 }
2279 2279 return data
2280 2280
2281 2281
2282 2282 class Permission(Base, BaseModel):
2283 2283 __tablename__ = 'permissions'
2284 2284 __table_args__ = (
2285 2285 Index('p_perm_name_idx', 'permission_name'),
2286 2286 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2287 2287 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2288 2288 )
2289 2289 PERMS = [
2290 2290 ('hg.admin', _('RhodeCode Super Administrator')),
2291 2291
2292 2292 ('repository.none', _('Repository no access')),
2293 2293 ('repository.read', _('Repository read access')),
2294 2294 ('repository.write', _('Repository write access')),
2295 2295 ('repository.admin', _('Repository admin access')),
2296 2296
2297 2297 ('group.none', _('Repository group no access')),
2298 2298 ('group.read', _('Repository group read access')),
2299 2299 ('group.write', _('Repository group write access')),
2300 2300 ('group.admin', _('Repository group admin access')),
2301 2301
2302 2302 ('usergroup.none', _('User group no access')),
2303 2303 ('usergroup.read', _('User group read access')),
2304 2304 ('usergroup.write', _('User group write access')),
2305 2305 ('usergroup.admin', _('User group admin access')),
2306 2306
2307 2307 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2308 2308 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2309 2309
2310 2310 ('hg.usergroup.create.false', _('User Group creation disabled')),
2311 2311 ('hg.usergroup.create.true', _('User Group creation enabled')),
2312 2312
2313 2313 ('hg.create.none', _('Repository creation disabled')),
2314 2314 ('hg.create.repository', _('Repository creation enabled')),
2315 2315 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2316 2316 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2317 2317
2318 2318 ('hg.fork.none', _('Repository forking disabled')),
2319 2319 ('hg.fork.repository', _('Repository forking enabled')),
2320 2320
2321 2321 ('hg.register.none', _('Registration disabled')),
2322 2322 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2323 2323 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2324 2324
2325 2325 ('hg.password_reset.enabled', _('Password reset enabled')),
2326 2326 ('hg.password_reset.hidden', _('Password reset hidden')),
2327 2327 ('hg.password_reset.disabled', _('Password reset disabled')),
2328 2328
2329 2329 ('hg.extern_activate.manual', _('Manual activation of external account')),
2330 2330 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2331 2331
2332 2332 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2333 2333 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2334 2334 ]
2335 2335
2336 2336 # definition of system default permissions for DEFAULT user
2337 2337 DEFAULT_USER_PERMISSIONS = [
2338 2338 'repository.read',
2339 2339 'group.read',
2340 2340 'usergroup.read',
2341 2341 'hg.create.repository',
2342 2342 'hg.repogroup.create.false',
2343 2343 'hg.usergroup.create.false',
2344 2344 'hg.create.write_on_repogroup.true',
2345 2345 'hg.fork.repository',
2346 2346 'hg.register.manual_activate',
2347 2347 'hg.password_reset.enabled',
2348 2348 'hg.extern_activate.auto',
2349 2349 'hg.inherit_default_perms.true',
2350 2350 ]
2351 2351
2352 2352 # defines which permissions are more important higher the more important
2353 2353 # Weight defines which permissions are more important.
2354 2354 # The higher number the more important.
2355 2355 PERM_WEIGHTS = {
2356 2356 'repository.none': 0,
2357 2357 'repository.read': 1,
2358 2358 'repository.write': 3,
2359 2359 'repository.admin': 4,
2360 2360
2361 2361 'group.none': 0,
2362 2362 'group.read': 1,
2363 2363 'group.write': 3,
2364 2364 'group.admin': 4,
2365 2365
2366 2366 'usergroup.none': 0,
2367 2367 'usergroup.read': 1,
2368 2368 'usergroup.write': 3,
2369 2369 'usergroup.admin': 4,
2370 2370
2371 2371 'hg.repogroup.create.false': 0,
2372 2372 'hg.repogroup.create.true': 1,
2373 2373
2374 2374 'hg.usergroup.create.false': 0,
2375 2375 'hg.usergroup.create.true': 1,
2376 2376
2377 2377 'hg.fork.none': 0,
2378 2378 'hg.fork.repository': 1,
2379 2379 'hg.create.none': 0,
2380 2380 'hg.create.repository': 1
2381 2381 }
2382 2382
2383 2383 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2384 2384 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2385 2385 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2386 2386
2387 2387 def __unicode__(self):
2388 2388 return u"<%s('%s:%s')>" % (
2389 2389 self.__class__.__name__, self.permission_id, self.permission_name
2390 2390 )
2391 2391
2392 2392 @classmethod
2393 2393 def get_by_key(cls, key):
2394 2394 return cls.query().filter(cls.permission_name == key).scalar()
2395 2395
2396 2396 @classmethod
2397 2397 def get_default_repo_perms(cls, user_id, repo_id=None):
2398 2398 q = Session().query(UserRepoToPerm, Repository, Permission)\
2399 2399 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2400 2400 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2401 2401 .filter(UserRepoToPerm.user_id == user_id)
2402 2402 if repo_id:
2403 2403 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2404 2404 return q.all()
2405 2405
2406 2406 @classmethod
2407 2407 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2408 2408 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2409 2409 .join(
2410 2410 Permission,
2411 2411 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2412 2412 .join(
2413 2413 Repository,
2414 2414 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2415 2415 .join(
2416 2416 UserGroup,
2417 2417 UserGroupRepoToPerm.users_group_id ==
2418 2418 UserGroup.users_group_id)\
2419 2419 .join(
2420 2420 UserGroupMember,
2421 2421 UserGroupRepoToPerm.users_group_id ==
2422 2422 UserGroupMember.users_group_id)\
2423 2423 .filter(
2424 2424 UserGroupMember.user_id == user_id,
2425 2425 UserGroup.users_group_active == true())
2426 2426 if repo_id:
2427 2427 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2428 2428 return q.all()
2429 2429
2430 2430 @classmethod
2431 2431 def get_default_group_perms(cls, user_id, repo_group_id=None):
2432 2432 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2433 2433 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2434 2434 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2435 2435 .filter(UserRepoGroupToPerm.user_id == user_id)
2436 2436 if repo_group_id:
2437 2437 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2438 2438 return q.all()
2439 2439
2440 2440 @classmethod
2441 2441 def get_default_group_perms_from_user_group(
2442 2442 cls, user_id, repo_group_id=None):
2443 2443 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2444 2444 .join(
2445 2445 Permission,
2446 2446 UserGroupRepoGroupToPerm.permission_id ==
2447 2447 Permission.permission_id)\
2448 2448 .join(
2449 2449 RepoGroup,
2450 2450 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2451 2451 .join(
2452 2452 UserGroup,
2453 2453 UserGroupRepoGroupToPerm.users_group_id ==
2454 2454 UserGroup.users_group_id)\
2455 2455 .join(
2456 2456 UserGroupMember,
2457 2457 UserGroupRepoGroupToPerm.users_group_id ==
2458 2458 UserGroupMember.users_group_id)\
2459 2459 .filter(
2460 2460 UserGroupMember.user_id == user_id,
2461 2461 UserGroup.users_group_active == true())
2462 2462 if repo_group_id:
2463 2463 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2464 2464 return q.all()
2465 2465
2466 2466 @classmethod
2467 2467 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2468 2468 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2469 2469 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2470 2470 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2471 2471 .filter(UserUserGroupToPerm.user_id == user_id)
2472 2472 if user_group_id:
2473 2473 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2474 2474 return q.all()
2475 2475
2476 2476 @classmethod
2477 2477 def get_default_user_group_perms_from_user_group(
2478 2478 cls, user_id, user_group_id=None):
2479 2479 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2480 2480 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2481 2481 .join(
2482 2482 Permission,
2483 2483 UserGroupUserGroupToPerm.permission_id ==
2484 2484 Permission.permission_id)\
2485 2485 .join(
2486 2486 TargetUserGroup,
2487 2487 UserGroupUserGroupToPerm.target_user_group_id ==
2488 2488 TargetUserGroup.users_group_id)\
2489 2489 .join(
2490 2490 UserGroup,
2491 2491 UserGroupUserGroupToPerm.user_group_id ==
2492 2492 UserGroup.users_group_id)\
2493 2493 .join(
2494 2494 UserGroupMember,
2495 2495 UserGroupUserGroupToPerm.user_group_id ==
2496 2496 UserGroupMember.users_group_id)\
2497 2497 .filter(
2498 2498 UserGroupMember.user_id == user_id,
2499 2499 UserGroup.users_group_active == true())
2500 2500 if user_group_id:
2501 2501 q = q.filter(
2502 2502 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2503 2503
2504 2504 return q.all()
2505 2505
2506 2506
2507 2507 class UserRepoToPerm(Base, BaseModel):
2508 2508 __tablename__ = 'repo_to_perm'
2509 2509 __table_args__ = (
2510 2510 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2511 2511 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2512 2512 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2513 2513 )
2514 2514 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2515 2515 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2516 2516 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2517 2517 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2518 2518
2519 2519 user = relationship('User')
2520 2520 repository = relationship('Repository')
2521 2521 permission = relationship('Permission')
2522 2522
2523 2523 @classmethod
2524 2524 def create(cls, user, repository, permission):
2525 2525 n = cls()
2526 2526 n.user = user
2527 2527 n.repository = repository
2528 2528 n.permission = permission
2529 2529 Session().add(n)
2530 2530 return n
2531 2531
2532 2532 def __unicode__(self):
2533 2533 return u'<%s => %s >' % (self.user, self.repository)
2534 2534
2535 2535
2536 2536 class UserUserGroupToPerm(Base, BaseModel):
2537 2537 __tablename__ = 'user_user_group_to_perm'
2538 2538 __table_args__ = (
2539 2539 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2540 2540 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2541 2541 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2542 2542 )
2543 2543 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2544 2544 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2545 2545 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2546 2546 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2547 2547
2548 2548 user = relationship('User')
2549 2549 user_group = relationship('UserGroup')
2550 2550 permission = relationship('Permission')
2551 2551
2552 2552 @classmethod
2553 2553 def create(cls, user, user_group, permission):
2554 2554 n = cls()
2555 2555 n.user = user
2556 2556 n.user_group = user_group
2557 2557 n.permission = permission
2558 2558 Session().add(n)
2559 2559 return n
2560 2560
2561 2561 def __unicode__(self):
2562 2562 return u'<%s => %s >' % (self.user, self.user_group)
2563 2563
2564 2564
2565 2565 class UserToPerm(Base, BaseModel):
2566 2566 __tablename__ = 'user_to_perm'
2567 2567 __table_args__ = (
2568 2568 UniqueConstraint('user_id', 'permission_id'),
2569 2569 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2570 2570 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2571 2571 )
2572 2572 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2573 2573 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2574 2574 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2575 2575
2576 2576 user = relationship('User')
2577 2577 permission = relationship('Permission', lazy='joined')
2578 2578
2579 2579 def __unicode__(self):
2580 2580 return u'<%s => %s >' % (self.user, self.permission)
2581 2581
2582 2582
2583 2583 class UserGroupRepoToPerm(Base, BaseModel):
2584 2584 __tablename__ = 'users_group_repo_to_perm'
2585 2585 __table_args__ = (
2586 2586 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2587 2587 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2588 2588 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2589 2589 )
2590 2590 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2591 2591 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2592 2592 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2593 2593 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2594 2594
2595 2595 users_group = relationship('UserGroup')
2596 2596 permission = relationship('Permission')
2597 2597 repository = relationship('Repository')
2598 2598
2599 2599 @classmethod
2600 2600 def create(cls, users_group, repository, permission):
2601 2601 n = cls()
2602 2602 n.users_group = users_group
2603 2603 n.repository = repository
2604 2604 n.permission = permission
2605 2605 Session().add(n)
2606 2606 return n
2607 2607
2608 2608 def __unicode__(self):
2609 2609 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2610 2610
2611 2611
2612 2612 class UserGroupUserGroupToPerm(Base, BaseModel):
2613 2613 __tablename__ = 'user_group_user_group_to_perm'
2614 2614 __table_args__ = (
2615 2615 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2616 2616 CheckConstraint('target_user_group_id != user_group_id'),
2617 2617 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2618 2618 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2619 2619 )
2620 2620 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)
2621 2621 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2622 2622 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2623 2623 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2624 2624
2625 2625 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2626 2626 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2627 2627 permission = relationship('Permission')
2628 2628
2629 2629 @classmethod
2630 2630 def create(cls, target_user_group, user_group, permission):
2631 2631 n = cls()
2632 2632 n.target_user_group = target_user_group
2633 2633 n.user_group = user_group
2634 2634 n.permission = permission
2635 2635 Session().add(n)
2636 2636 return n
2637 2637
2638 2638 def __unicode__(self):
2639 2639 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2640 2640
2641 2641
2642 2642 class UserGroupToPerm(Base, BaseModel):
2643 2643 __tablename__ = 'users_group_to_perm'
2644 2644 __table_args__ = (
2645 2645 UniqueConstraint('users_group_id', 'permission_id',),
2646 2646 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2647 2647 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2648 2648 )
2649 2649 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2650 2650 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2651 2651 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2652 2652
2653 2653 users_group = relationship('UserGroup')
2654 2654 permission = relationship('Permission')
2655 2655
2656 2656
2657 2657 class UserRepoGroupToPerm(Base, BaseModel):
2658 2658 __tablename__ = 'user_repo_group_to_perm'
2659 2659 __table_args__ = (
2660 2660 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2661 2661 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2662 2662 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2663 2663 )
2664 2664
2665 2665 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2666 2666 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2667 2667 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2668 2668 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2669 2669
2670 2670 user = relationship('User')
2671 2671 group = relationship('RepoGroup')
2672 2672 permission = relationship('Permission')
2673 2673
2674 2674 @classmethod
2675 2675 def create(cls, user, repository_group, permission):
2676 2676 n = cls()
2677 2677 n.user = user
2678 2678 n.group = repository_group
2679 2679 n.permission = permission
2680 2680 Session().add(n)
2681 2681 return n
2682 2682
2683 2683
2684 2684 class UserGroupRepoGroupToPerm(Base, BaseModel):
2685 2685 __tablename__ = 'users_group_repo_group_to_perm'
2686 2686 __table_args__ = (
2687 2687 UniqueConstraint('users_group_id', 'group_id'),
2688 2688 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2689 2689 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2690 2690 )
2691 2691
2692 2692 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)
2693 2693 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2694 2694 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2695 2695 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2696 2696
2697 2697 users_group = relationship('UserGroup')
2698 2698 permission = relationship('Permission')
2699 2699 group = relationship('RepoGroup')
2700 2700
2701 2701 @classmethod
2702 2702 def create(cls, user_group, repository_group, permission):
2703 2703 n = cls()
2704 2704 n.users_group = user_group
2705 2705 n.group = repository_group
2706 2706 n.permission = permission
2707 2707 Session().add(n)
2708 2708 return n
2709 2709
2710 2710 def __unicode__(self):
2711 2711 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
2712 2712
2713 2713
2714 2714 class Statistics(Base, BaseModel):
2715 2715 __tablename__ = 'statistics'
2716 2716 __table_args__ = (
2717 2717 UniqueConstraint('repository_id'),
2718 2718 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2719 2719 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2720 2720 )
2721 2721 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2722 2722 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
2723 2723 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
2724 2724 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
2725 2725 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
2726 2726 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
2727 2727
2728 2728 repository = relationship('Repository', single_parent=True)
2729 2729
2730 2730
2731 2731 class UserFollowing(Base, BaseModel):
2732 2732 __tablename__ = 'user_followings'
2733 2733 __table_args__ = (
2734 2734 UniqueConstraint('user_id', 'follows_repository_id'),
2735 2735 UniqueConstraint('user_id', 'follows_user_id'),
2736 2736 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2737 2737 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2738 2738 )
2739 2739
2740 2740 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2741 2741 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2742 2742 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
2743 2743 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
2744 2744 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2745 2745
2746 2746 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
2747 2747
2748 2748 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
2749 2749 follows_repository = relationship('Repository', order_by='Repository.repo_name')
2750 2750
2751 2751 @classmethod
2752 2752 def get_repo_followers(cls, repo_id):
2753 2753 return cls.query().filter(cls.follows_repo_id == repo_id)
2754 2754
2755 2755
2756 2756 class CacheKey(Base, BaseModel):
2757 2757 __tablename__ = 'cache_invalidation'
2758 2758 __table_args__ = (
2759 2759 UniqueConstraint('cache_key'),
2760 2760 Index('key_idx', 'cache_key'),
2761 2761 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2762 2762 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2763 2763 )
2764 2764 CACHE_TYPE_ATOM = 'ATOM'
2765 2765 CACHE_TYPE_RSS = 'RSS'
2766 2766 CACHE_TYPE_README = 'README'
2767 2767
2768 2768 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2769 2769 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
2770 2770 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
2771 2771 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
2772 2772
2773 2773 def __init__(self, cache_key, cache_args=''):
2774 2774 self.cache_key = cache_key
2775 2775 self.cache_args = cache_args
2776 2776 self.cache_active = False
2777 2777
2778 2778 def __unicode__(self):
2779 2779 return u"<%s('%s:%s[%s]')>" % (
2780 2780 self.__class__.__name__,
2781 2781 self.cache_id, self.cache_key, self.cache_active)
2782 2782
2783 2783 def _cache_key_partition(self):
2784 2784 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
2785 2785 return prefix, repo_name, suffix
2786 2786
2787 2787 def get_prefix(self):
2788 2788 """
2789 2789 Try to extract prefix from existing cache key. The key could consist
2790 2790 of prefix, repo_name, suffix
2791 2791 """
2792 2792 # this returns prefix, repo_name, suffix
2793 2793 return self._cache_key_partition()[0]
2794 2794
2795 2795 def get_suffix(self):
2796 2796 """
2797 2797 get suffix that might have been used in _get_cache_key to
2798 2798 generate self.cache_key. Only used for informational purposes
2799 2799 in repo_edit.html.
2800 2800 """
2801 2801 # prefix, repo_name, suffix
2802 2802 return self._cache_key_partition()[2]
2803 2803
2804 2804 @classmethod
2805 2805 def delete_all_cache(cls):
2806 2806 """
2807 2807 Delete all cache keys from database.
2808 2808 Should only be run when all instances are down and all entries
2809 2809 thus stale.
2810 2810 """
2811 2811 cls.query().delete()
2812 2812 Session().commit()
2813 2813
2814 2814 @classmethod
2815 2815 def get_cache_key(cls, repo_name, cache_type):
2816 2816 """
2817 2817
2818 2818 Generate a cache key for this process of RhodeCode instance.
2819 2819 Prefix most likely will be process id or maybe explicitly set
2820 2820 instance_id from .ini file.
2821 2821 """
2822 2822 import rhodecode
2823 2823 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
2824 2824
2825 2825 repo_as_unicode = safe_unicode(repo_name)
2826 2826 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
2827 2827 if cache_type else repo_as_unicode
2828 2828
2829 2829 return u'{}{}'.format(prefix, key)
2830 2830
2831 2831 @classmethod
2832 2832 def set_invalidate(cls, repo_name, delete=False):
2833 2833 """
2834 2834 Mark all caches of a repo as invalid in the database.
2835 2835 """
2836 2836
2837 2837 try:
2838 2838 qry = Session().query(cls).filter(cls.cache_args == repo_name)
2839 2839 if delete:
2840 2840 log.debug('cache objects deleted for repo %s',
2841 2841 safe_str(repo_name))
2842 2842 qry.delete()
2843 2843 else:
2844 2844 log.debug('cache objects marked as invalid for repo %s',
2845 2845 safe_str(repo_name))
2846 2846 qry.update({"cache_active": False})
2847 2847
2848 2848 Session().commit()
2849 2849 except Exception:
2850 2850 log.exception(
2851 2851 'Cache key invalidation failed for repository %s',
2852 2852 safe_str(repo_name))
2853 2853 Session().rollback()
2854 2854
2855 2855 @classmethod
2856 2856 def get_active_cache(cls, cache_key):
2857 2857 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
2858 2858 if inv_obj:
2859 2859 return inv_obj
2860 2860 return None
2861 2861
2862 2862 @classmethod
2863 2863 def repo_context_cache(cls, compute_func, repo_name, cache_type,
2864 2864 thread_scoped=False):
2865 2865 """
2866 2866 @cache_region('long_term')
2867 2867 def _heavy_calculation(cache_key):
2868 2868 return 'result'
2869 2869
2870 2870 cache_context = CacheKey.repo_context_cache(
2871 2871 _heavy_calculation, repo_name, cache_type)
2872 2872
2873 2873 with cache_context as context:
2874 2874 context.invalidate()
2875 2875 computed = context.compute()
2876 2876
2877 2877 assert computed == 'result'
2878 2878 """
2879 2879 from rhodecode.lib import caches
2880 2880 return caches.InvalidationContext(
2881 2881 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
2882 2882
2883 2883
2884 2884 class ChangesetComment(Base, BaseModel):
2885 2885 __tablename__ = 'changeset_comments'
2886 2886 __table_args__ = (
2887 2887 Index('cc_revision_idx', 'revision'),
2888 2888 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2889 2889 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2890 2890 )
2891 2891
2892 2892 COMMENT_OUTDATED = u'comment_outdated'
2893 2893
2894 2894 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
2895 2895 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
2896 2896 revision = Column('revision', String(40), nullable=True)
2897 2897 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
2898 2898 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
2899 2899 line_no = Column('line_no', Unicode(10), nullable=True)
2900 2900 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
2901 2901 f_path = Column('f_path', Unicode(1000), nullable=True)
2902 2902 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
2903 2903 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
2904 2904 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2905 2905 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2906 2906 renderer = Column('renderer', Unicode(64), nullable=True)
2907 2907 display_state = Column('display_state', Unicode(128), nullable=True)
2908 2908
2909 2909 author = relationship('User', lazy='joined')
2910 2910 repo = relationship('Repository')
2911 2911 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
2912 2912 pull_request = relationship('PullRequest', lazy='joined')
2913 2913 pull_request_version = relationship('PullRequestVersion')
2914 2914
2915 2915 @classmethod
2916 2916 def get_users(cls, revision=None, pull_request_id=None):
2917 2917 """
2918 2918 Returns user associated with this ChangesetComment. ie those
2919 2919 who actually commented
2920 2920
2921 2921 :param cls:
2922 2922 :param revision:
2923 2923 """
2924 2924 q = Session().query(User)\
2925 2925 .join(ChangesetComment.author)
2926 2926 if revision:
2927 2927 q = q.filter(cls.revision == revision)
2928 2928 elif pull_request_id:
2929 2929 q = q.filter(cls.pull_request_id == pull_request_id)
2930 2930 return q.all()
2931 2931
2932 2932 @property
2933 2933 def outdated(self):
2934 2934 return self.display_state == self.COMMENT_OUTDATED
2935 2935
2936 2936 def outdated_at_version(self, version):
2937 2937 """
2938 2938 Checks if comment is outdated for given pull request version
2939 2939 """
2940 2940 return self.outdated and self.pull_request_version_id != version
2941 2941
2942 2942 def render(self, mentions=False):
2943 2943 from rhodecode.lib import helpers as h
2944 2944 return h.render(self.text, renderer=self.renderer, mentions=mentions)
2945 2945
2946 2946 def __repr__(self):
2947 2947 if self.comment_id:
2948 2948 return '<DB:ChangesetComment #%s>' % self.comment_id
2949 2949 else:
2950 2950 return '<DB:ChangesetComment at %#x>' % id(self)
2951 2951
2952 2952
2953 2953 class ChangesetStatus(Base, BaseModel):
2954 2954 __tablename__ = 'changeset_statuses'
2955 2955 __table_args__ = (
2956 2956 Index('cs_revision_idx', 'revision'),
2957 2957 Index('cs_version_idx', 'version'),
2958 2958 UniqueConstraint('repo_id', 'revision', 'version'),
2959 2959 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2960 2960 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2961 2961 )
2962 2962 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
2963 2963 STATUS_APPROVED = 'approved'
2964 2964 STATUS_REJECTED = 'rejected'
2965 2965 STATUS_UNDER_REVIEW = 'under_review'
2966 2966
2967 2967 STATUSES = [
2968 2968 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
2969 2969 (STATUS_APPROVED, _("Approved")),
2970 2970 (STATUS_REJECTED, _("Rejected")),
2971 2971 (STATUS_UNDER_REVIEW, _("Under Review")),
2972 2972 ]
2973 2973
2974 2974 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
2975 2975 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
2976 2976 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
2977 2977 revision = Column('revision', String(40), nullable=False)
2978 2978 status = Column('status', String(128), nullable=False, default=DEFAULT)
2979 2979 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
2980 2980 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
2981 2981 version = Column('version', Integer(), nullable=False, default=0)
2982 2982 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
2983 2983
2984 2984 author = relationship('User', lazy='joined')
2985 2985 repo = relationship('Repository')
2986 2986 comment = relationship('ChangesetComment', lazy='joined')
2987 2987 pull_request = relationship('PullRequest', lazy='joined')
2988 2988
2989 2989 def __unicode__(self):
2990 2990 return u"<%s('%s[%s]:%s')>" % (
2991 2991 self.__class__.__name__,
2992 2992 self.status, self.version, self.author
2993 2993 )
2994 2994
2995 2995 @classmethod
2996 2996 def get_status_lbl(cls, value):
2997 2997 return dict(cls.STATUSES).get(value)
2998 2998
2999 2999 @property
3000 3000 def status_lbl(self):
3001 3001 return ChangesetStatus.get_status_lbl(self.status)
3002 3002
3003 3003
3004 3004 class _PullRequestBase(BaseModel):
3005 3005 """
3006 3006 Common attributes of pull request and version entries.
3007 3007 """
3008 3008
3009 3009 # .status values
3010 3010 STATUS_NEW = u'new'
3011 3011 STATUS_OPEN = u'open'
3012 3012 STATUS_CLOSED = u'closed'
3013 3013
3014 3014 title = Column('title', Unicode(255), nullable=True)
3015 3015 description = Column(
3016 3016 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3017 3017 nullable=True)
3018 3018 # new/open/closed status of pull request (not approve/reject/etc)
3019 3019 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3020 3020 created_on = Column(
3021 3021 'created_on', DateTime(timezone=False), nullable=False,
3022 3022 default=datetime.datetime.now)
3023 3023 updated_on = Column(
3024 3024 'updated_on', DateTime(timezone=False), nullable=False,
3025 3025 default=datetime.datetime.now)
3026 3026
3027 3027 @declared_attr
3028 3028 def user_id(cls):
3029 3029 return Column(
3030 3030 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3031 3031 unique=None)
3032 3032
3033 3033 # 500 revisions max
3034 3034 _revisions = Column(
3035 3035 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3036 3036
3037 3037 @declared_attr
3038 3038 def source_repo_id(cls):
3039 3039 # TODO: dan: rename column to source_repo_id
3040 3040 return Column(
3041 3041 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3042 3042 nullable=False)
3043 3043
3044 3044 source_ref = Column('org_ref', Unicode(255), nullable=False)
3045 3045
3046 3046 @declared_attr
3047 3047 def target_repo_id(cls):
3048 3048 # TODO: dan: rename column to target_repo_id
3049 3049 return Column(
3050 3050 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3051 3051 nullable=False)
3052 3052
3053 3053 target_ref = Column('other_ref', Unicode(255), nullable=False)
3054 3054 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3055 3055
3056 3056 # TODO: dan: rename column to last_merge_source_rev
3057 3057 _last_merge_source_rev = Column(
3058 3058 'last_merge_org_rev', String(40), nullable=True)
3059 3059 # TODO: dan: rename column to last_merge_target_rev
3060 3060 _last_merge_target_rev = Column(
3061 3061 'last_merge_other_rev', String(40), nullable=True)
3062 3062 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3063 3063 merge_rev = Column('merge_rev', String(40), nullable=True)
3064 3064
3065 3065 @hybrid_property
3066 3066 def revisions(self):
3067 3067 return self._revisions.split(':') if self._revisions else []
3068 3068
3069 3069 @revisions.setter
3070 3070 def revisions(self, val):
3071 3071 self._revisions = ':'.join(val)
3072 3072
3073 3073 @declared_attr
3074 3074 def author(cls):
3075 3075 return relationship('User', lazy='joined')
3076 3076
3077 3077 @declared_attr
3078 3078 def source_repo(cls):
3079 3079 return relationship(
3080 3080 'Repository',
3081 3081 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3082 3082
3083 3083 @property
3084 3084 def source_ref_parts(self):
3085 3085 return self.unicode_to_reference(self.source_ref)
3086 3086
3087 3087 @declared_attr
3088 3088 def target_repo(cls):
3089 3089 return relationship(
3090 3090 'Repository',
3091 3091 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3092 3092
3093 3093 @property
3094 3094 def target_ref_parts(self):
3095 3095 return self.unicode_to_reference(self.target_ref)
3096 3096
3097 3097 @property
3098 3098 def shadow_merge_ref(self):
3099 3099 return self.unicode_to_reference(self._shadow_merge_ref)
3100 3100
3101 3101 @shadow_merge_ref.setter
3102 3102 def shadow_merge_ref(self, ref):
3103 3103 self._shadow_merge_ref = self.reference_to_unicode(ref)
3104 3104
3105 3105 def unicode_to_reference(self, raw):
3106 3106 """
3107 3107 Convert a unicode (or string) to a reference object.
3108 3108 If unicode evaluates to False it returns None.
3109 3109 """
3110 3110 if raw:
3111 3111 refs = raw.split(':')
3112 3112 return Reference(*refs)
3113 3113 else:
3114 3114 return None
3115 3115
3116 3116 def reference_to_unicode(self, ref):
3117 3117 """
3118 3118 Convert a reference object to unicode.
3119 3119 If reference is None it returns None.
3120 3120 """
3121 3121 if ref:
3122 3122 return u':'.join(ref)
3123 3123 else:
3124 3124 return None
3125 3125
3126 3126 def get_api_data(self):
3127 3127 from rhodecode.model.pull_request import PullRequestModel
3128 3128 pull_request = self
3129 3129 merge_status = PullRequestModel().merge_status(pull_request)
3130 3130
3131 3131 pull_request_url = url(
3132 3132 'pullrequest_show', repo_name=self.target_repo.repo_name,
3133 3133 pull_request_id=self.pull_request_id, qualified=True)
3134 3134
3135 3135 merge_data = {
3136 3136 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3137 3137 'reference': (
3138 3138 pull_request.shadow_merge_ref._asdict()
3139 3139 if pull_request.shadow_merge_ref else None),
3140 3140 }
3141 3141
3142 3142 data = {
3143 3143 'pull_request_id': pull_request.pull_request_id,
3144 3144 'url': pull_request_url,
3145 3145 'title': pull_request.title,
3146 3146 'description': pull_request.description,
3147 3147 'status': pull_request.status,
3148 3148 'created_on': pull_request.created_on,
3149 3149 'updated_on': pull_request.updated_on,
3150 3150 'commit_ids': pull_request.revisions,
3151 3151 'review_status': pull_request.calculated_review_status(),
3152 3152 'mergeable': {
3153 3153 'status': merge_status[0],
3154 3154 'message': unicode(merge_status[1]),
3155 3155 },
3156 3156 'source': {
3157 3157 'clone_url': pull_request.source_repo.clone_url(),
3158 3158 'repository': pull_request.source_repo.repo_name,
3159 3159 'reference': {
3160 3160 'name': pull_request.source_ref_parts.name,
3161 3161 'type': pull_request.source_ref_parts.type,
3162 3162 'commit_id': pull_request.source_ref_parts.commit_id,
3163 3163 },
3164 3164 },
3165 3165 'target': {
3166 3166 'clone_url': pull_request.target_repo.clone_url(),
3167 3167 'repository': pull_request.target_repo.repo_name,
3168 3168 'reference': {
3169 3169 'name': pull_request.target_ref_parts.name,
3170 3170 'type': pull_request.target_ref_parts.type,
3171 3171 'commit_id': pull_request.target_ref_parts.commit_id,
3172 3172 },
3173 3173 },
3174 3174 'merge': merge_data,
3175 3175 'author': pull_request.author.get_api_data(include_secrets=False,
3176 3176 details='basic'),
3177 3177 'reviewers': [
3178 3178 {
3179 3179 'user': reviewer.get_api_data(include_secrets=False,
3180 3180 details='basic'),
3181 3181 'reasons': reasons,
3182 3182 'review_status': st[0][1].status if st else 'not_reviewed',
3183 3183 }
3184 3184 for reviewer, reasons, st in pull_request.reviewers_statuses()
3185 3185 ]
3186 3186 }
3187 3187
3188 3188 return data
3189 3189
3190 3190
3191 3191 class PullRequest(Base, _PullRequestBase):
3192 3192 __tablename__ = 'pull_requests'
3193 3193 __table_args__ = (
3194 3194 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3195 3195 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3196 3196 )
3197 3197
3198 3198 pull_request_id = Column(
3199 3199 'pull_request_id', Integer(), nullable=False, primary_key=True)
3200 3200
3201 3201 def __repr__(self):
3202 3202 if self.pull_request_id:
3203 3203 return '<DB:PullRequest #%s>' % self.pull_request_id
3204 3204 else:
3205 3205 return '<DB:PullRequest at %#x>' % id(self)
3206 3206
3207 3207 reviewers = relationship('PullRequestReviewers',
3208 3208 cascade="all, delete, delete-orphan")
3209 3209 statuses = relationship('ChangesetStatus')
3210 3210 comments = relationship('ChangesetComment',
3211 3211 cascade="all, delete, delete-orphan")
3212 3212 versions = relationship('PullRequestVersion',
3213 3213 cascade="all, delete, delete-orphan",
3214 3214 lazy='dynamic')
3215 3215
3216
3217 @classmethod
3218 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3219 internal_methods=None):
3220
3221 class PullRequestDisplay(object):
3222 """
3223 Special object wrapper for showing PullRequest data via Versions
3224 It mimics PR object as close as possible. This is read only object
3225 just for display
3226 """
3227
3228 def __init__(self, attrs, internal=None):
3229 self.attrs = attrs
3230 # internal have priority over the given ones via attrs
3231 self.internal = internal or ['versions']
3232
3233 def __getattr__(self, item):
3234 if item in self.internal:
3235 return getattr(self, item)
3236 try:
3237 return self.attrs[item]
3238 except KeyError:
3239 raise AttributeError(
3240 '%s object has no attribute %s' % (self, item))
3241
3242 def __repr__(self):
3243 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3244
3245 def versions(self):
3246 return pull_request_obj.versions.order_by(
3247 PullRequestVersion.pull_request_version_id).all()
3248
3249 def is_closed(self):
3250 return pull_request_obj.is_closed()
3251
3252 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3253
3254 attrs.author = StrictAttributeDict(
3255 pull_request_obj.author.get_api_data())
3256 if pull_request_obj.target_repo:
3257 attrs.target_repo = StrictAttributeDict(
3258 pull_request_obj.target_repo.get_api_data())
3259 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3260
3261 if pull_request_obj.source_repo:
3262 attrs.source_repo = StrictAttributeDict(
3263 pull_request_obj.source_repo.get_api_data())
3264 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3265
3266 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3267 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3268 attrs.revisions = pull_request_obj.revisions
3269
3270 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3271
3272 return PullRequestDisplay(attrs, internal=internal_methods)
3273
3216 3274 def is_closed(self):
3217 3275 return self.status == self.STATUS_CLOSED
3218 3276
3219 3277 def __json__(self):
3220 3278 return {
3221 3279 'revisions': self.revisions,
3222 3280 }
3223 3281
3224 3282 def calculated_review_status(self):
3225 3283 from rhodecode.model.changeset_status import ChangesetStatusModel
3226 3284 return ChangesetStatusModel().calculated_review_status(self)
3227 3285
3228 3286 def reviewers_statuses(self):
3229 3287 from rhodecode.model.changeset_status import ChangesetStatusModel
3230 3288 return ChangesetStatusModel().reviewers_statuses(self)
3231 3289
3232 3290
3233 3291 class PullRequestVersion(Base, _PullRequestBase):
3234 3292 __tablename__ = 'pull_request_versions'
3235 3293 __table_args__ = (
3236 3294 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3237 3295 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3238 3296 )
3239 3297
3240 3298 pull_request_version_id = Column(
3241 3299 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3242 3300 pull_request_id = Column(
3243 3301 'pull_request_id', Integer(),
3244 3302 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3245 3303 pull_request = relationship('PullRequest')
3246 3304
3247 3305 def __repr__(self):
3248 3306 if self.pull_request_version_id:
3249 3307 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3250 3308 else:
3251 3309 return '<DB:PullRequestVersion at %#x>' % id(self)
3252 3310
3253 3311 @property
3254 3312 def reviewers(self):
3255 3313 return self.pull_request.reviewers
3256 3314
3257 3315 @property
3258 3316 def versions(self):
3259 3317 return self.pull_request.versions
3260 3318
3261 3319 def is_closed(self):
3262 3320 # calculate from original
3263 3321 return self.pull_request.status == self.STATUS_CLOSED
3264 3322
3265 3323 def calculated_review_status(self):
3266 3324 return self.pull_request.calculated_review_status()
3267 3325
3268 3326 def reviewers_statuses(self):
3269 3327 return self.pull_request.reviewers_statuses()
3270 3328
3271 3329
3272 3330 class PullRequestReviewers(Base, BaseModel):
3273 3331 __tablename__ = 'pull_request_reviewers'
3274 3332 __table_args__ = (
3275 3333 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3276 3334 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3277 3335 )
3278 3336
3279 3337 def __init__(self, user=None, pull_request=None, reasons=None):
3280 3338 self.user = user
3281 3339 self.pull_request = pull_request
3282 3340 self.reasons = reasons or []
3283 3341
3284 3342 @hybrid_property
3285 3343 def reasons(self):
3286 3344 if not self._reasons:
3287 3345 return []
3288 3346 return self._reasons
3289 3347
3290 3348 @reasons.setter
3291 3349 def reasons(self, val):
3292 3350 val = val or []
3293 3351 if any(not isinstance(x, basestring) for x in val):
3294 3352 raise Exception('invalid reasons type, must be list of strings')
3295 3353 self._reasons = val
3296 3354
3297 3355 pull_requests_reviewers_id = Column(
3298 3356 'pull_requests_reviewers_id', Integer(), nullable=False,
3299 3357 primary_key=True)
3300 3358 pull_request_id = Column(
3301 3359 "pull_request_id", Integer(),
3302 3360 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3303 3361 user_id = Column(
3304 3362 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3305 3363 _reasons = Column(
3306 3364 'reason', MutationList.as_mutable(
3307 3365 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3308 3366
3309 3367 user = relationship('User')
3310 3368 pull_request = relationship('PullRequest')
3311 3369
3312 3370
3313 3371 class Notification(Base, BaseModel):
3314 3372 __tablename__ = 'notifications'
3315 3373 __table_args__ = (
3316 3374 Index('notification_type_idx', 'type'),
3317 3375 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3318 3376 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3319 3377 )
3320 3378
3321 3379 TYPE_CHANGESET_COMMENT = u'cs_comment'
3322 3380 TYPE_MESSAGE = u'message'
3323 3381 TYPE_MENTION = u'mention'
3324 3382 TYPE_REGISTRATION = u'registration'
3325 3383 TYPE_PULL_REQUEST = u'pull_request'
3326 3384 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3327 3385
3328 3386 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3329 3387 subject = Column('subject', Unicode(512), nullable=True)
3330 3388 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3331 3389 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3332 3390 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3333 3391 type_ = Column('type', Unicode(255))
3334 3392
3335 3393 created_by_user = relationship('User')
3336 3394 notifications_to_users = relationship('UserNotification', lazy='joined',
3337 3395 cascade="all, delete, delete-orphan")
3338 3396
3339 3397 @property
3340 3398 def recipients(self):
3341 3399 return [x.user for x in UserNotification.query()\
3342 3400 .filter(UserNotification.notification == self)\
3343 3401 .order_by(UserNotification.user_id.asc()).all()]
3344 3402
3345 3403 @classmethod
3346 3404 def create(cls, created_by, subject, body, recipients, type_=None):
3347 3405 if type_ is None:
3348 3406 type_ = Notification.TYPE_MESSAGE
3349 3407
3350 3408 notification = cls()
3351 3409 notification.created_by_user = created_by
3352 3410 notification.subject = subject
3353 3411 notification.body = body
3354 3412 notification.type_ = type_
3355 3413 notification.created_on = datetime.datetime.now()
3356 3414
3357 3415 for u in recipients:
3358 3416 assoc = UserNotification()
3359 3417 assoc.notification = notification
3360 3418
3361 3419 # if created_by is inside recipients mark his notification
3362 3420 # as read
3363 3421 if u.user_id == created_by.user_id:
3364 3422 assoc.read = True
3365 3423
3366 3424 u.notifications.append(assoc)
3367 3425 Session().add(notification)
3368 3426
3369 3427 return notification
3370 3428
3371 3429 @property
3372 3430 def description(self):
3373 3431 from rhodecode.model.notification import NotificationModel
3374 3432 return NotificationModel().make_description(self)
3375 3433
3376 3434
3377 3435 class UserNotification(Base, BaseModel):
3378 3436 __tablename__ = 'user_to_notification'
3379 3437 __table_args__ = (
3380 3438 UniqueConstraint('user_id', 'notification_id'),
3381 3439 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3382 3440 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3383 3441 )
3384 3442 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3385 3443 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3386 3444 read = Column('read', Boolean, default=False)
3387 3445 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3388 3446
3389 3447 user = relationship('User', lazy="joined")
3390 3448 notification = relationship('Notification', lazy="joined",
3391 3449 order_by=lambda: Notification.created_on.desc(),)
3392 3450
3393 3451 def mark_as_read(self):
3394 3452 self.read = True
3395 3453 Session().add(self)
3396 3454
3397 3455
3398 3456 class Gist(Base, BaseModel):
3399 3457 __tablename__ = 'gists'
3400 3458 __table_args__ = (
3401 3459 Index('g_gist_access_id_idx', 'gist_access_id'),
3402 3460 Index('g_created_on_idx', 'created_on'),
3403 3461 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3404 3462 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3405 3463 )
3406 3464 GIST_PUBLIC = u'public'
3407 3465 GIST_PRIVATE = u'private'
3408 3466 DEFAULT_FILENAME = u'gistfile1.txt'
3409 3467
3410 3468 ACL_LEVEL_PUBLIC = u'acl_public'
3411 3469 ACL_LEVEL_PRIVATE = u'acl_private'
3412 3470
3413 3471 gist_id = Column('gist_id', Integer(), primary_key=True)
3414 3472 gist_access_id = Column('gist_access_id', Unicode(250))
3415 3473 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3416 3474 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3417 3475 gist_expires = Column('gist_expires', Float(53), nullable=False)
3418 3476 gist_type = Column('gist_type', Unicode(128), nullable=False)
3419 3477 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3420 3478 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3421 3479 acl_level = Column('acl_level', Unicode(128), nullable=True)
3422 3480
3423 3481 owner = relationship('User')
3424 3482
3425 3483 def __repr__(self):
3426 3484 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3427 3485
3428 3486 @classmethod
3429 3487 def get_or_404(cls, id_):
3430 3488 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3431 3489 if not res:
3432 3490 raise HTTPNotFound
3433 3491 return res
3434 3492
3435 3493 @classmethod
3436 3494 def get_by_access_id(cls, gist_access_id):
3437 3495 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3438 3496
3439 3497 def gist_url(self):
3440 3498 import rhodecode
3441 3499 alias_url = rhodecode.CONFIG.get('gist_alias_url')
3442 3500 if alias_url:
3443 3501 return alias_url.replace('{gistid}', self.gist_access_id)
3444 3502
3445 3503 return url('gist', gist_id=self.gist_access_id, qualified=True)
3446 3504
3447 3505 @classmethod
3448 3506 def base_path(cls):
3449 3507 """
3450 3508 Returns base path when all gists are stored
3451 3509
3452 3510 :param cls:
3453 3511 """
3454 3512 from rhodecode.model.gist import GIST_STORE_LOC
3455 3513 q = Session().query(RhodeCodeUi)\
3456 3514 .filter(RhodeCodeUi.ui_key == URL_SEP)
3457 3515 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3458 3516 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3459 3517
3460 3518 def get_api_data(self):
3461 3519 """
3462 3520 Common function for generating gist related data for API
3463 3521 """
3464 3522 gist = self
3465 3523 data = {
3466 3524 'gist_id': gist.gist_id,
3467 3525 'type': gist.gist_type,
3468 3526 'access_id': gist.gist_access_id,
3469 3527 'description': gist.gist_description,
3470 3528 'url': gist.gist_url(),
3471 3529 'expires': gist.gist_expires,
3472 3530 'created_on': gist.created_on,
3473 3531 'modified_at': gist.modified_at,
3474 3532 'content': None,
3475 3533 'acl_level': gist.acl_level,
3476 3534 }
3477 3535 return data
3478 3536
3479 3537 def __json__(self):
3480 3538 data = dict(
3481 3539 )
3482 3540 data.update(self.get_api_data())
3483 3541 return data
3484 3542 # SCM functions
3485 3543
3486 3544 def scm_instance(self, **kwargs):
3487 3545 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3488 3546 return get_vcs_instance(
3489 3547 repo_path=safe_str(full_repo_path), create=False)
3490 3548
3491 3549
3492 3550 class DbMigrateVersion(Base, BaseModel):
3493 3551 __tablename__ = 'db_migrate_version'
3494 3552 __table_args__ = (
3495 3553 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3496 3554 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3497 3555 )
3498 3556 repository_id = Column('repository_id', String(250), primary_key=True)
3499 3557 repository_path = Column('repository_path', Text)
3500 3558 version = Column('version', Integer)
3501 3559
3502 3560
3503 3561 class ExternalIdentity(Base, BaseModel):
3504 3562 __tablename__ = 'external_identities'
3505 3563 __table_args__ = (
3506 3564 Index('local_user_id_idx', 'local_user_id'),
3507 3565 Index('external_id_idx', 'external_id'),
3508 3566 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3509 3567 'mysql_charset': 'utf8'})
3510 3568
3511 3569 external_id = Column('external_id', Unicode(255), default=u'',
3512 3570 primary_key=True)
3513 3571 external_username = Column('external_username', Unicode(1024), default=u'')
3514 3572 local_user_id = Column('local_user_id', Integer(),
3515 3573 ForeignKey('users.user_id'), primary_key=True)
3516 3574 provider_name = Column('provider_name', Unicode(255), default=u'',
3517 3575 primary_key=True)
3518 3576 access_token = Column('access_token', String(1024), default=u'')
3519 3577 alt_token = Column('alt_token', String(1024), default=u'')
3520 3578 token_secret = Column('token_secret', String(1024), default=u'')
3521 3579
3522 3580 @classmethod
3523 3581 def by_external_id_and_provider(cls, external_id, provider_name,
3524 3582 local_user_id=None):
3525 3583 """
3526 3584 Returns ExternalIdentity instance based on search params
3527 3585
3528 3586 :param external_id:
3529 3587 :param provider_name:
3530 3588 :return: ExternalIdentity
3531 3589 """
3532 3590 query = cls.query()
3533 3591 query = query.filter(cls.external_id == external_id)
3534 3592 query = query.filter(cls.provider_name == provider_name)
3535 3593 if local_user_id:
3536 3594 query = query.filter(cls.local_user_id == local_user_id)
3537 3595 return query.first()
3538 3596
3539 3597 @classmethod
3540 3598 def user_by_external_id_and_provider(cls, external_id, provider_name):
3541 3599 """
3542 3600 Returns User instance based on search params
3543 3601
3544 3602 :param external_id:
3545 3603 :param provider_name:
3546 3604 :return: User
3547 3605 """
3548 3606 query = User.query()
3549 3607 query = query.filter(cls.external_id == external_id)
3550 3608 query = query.filter(cls.provider_name == provider_name)
3551 3609 query = query.filter(User.user_id == cls.local_user_id)
3552 3610 return query.first()
3553 3611
3554 3612 @classmethod
3555 3613 def by_local_user_id(cls, local_user_id):
3556 3614 """
3557 3615 Returns all tokens for user
3558 3616
3559 3617 :param local_user_id:
3560 3618 :return: ExternalIdentity
3561 3619 """
3562 3620 query = cls.query()
3563 3621 query = query.filter(cls.local_user_id == local_user_id)
3564 3622 return query
3565 3623
3566 3624
3567 3625 class Integration(Base, BaseModel):
3568 3626 __tablename__ = 'integrations'
3569 3627 __table_args__ = (
3570 3628 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3571 3629 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3572 3630 )
3573 3631
3574 3632 integration_id = Column('integration_id', Integer(), primary_key=True)
3575 3633 integration_type = Column('integration_type', String(255))
3576 3634 enabled = Column('enabled', Boolean(), nullable=False)
3577 3635 name = Column('name', String(255), nullable=False)
3578 3636 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
3579 3637 default=False)
3580 3638
3581 3639 settings = Column(
3582 3640 'settings_json', MutationObj.as_mutable(
3583 3641 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3584 3642 repo_id = Column(
3585 3643 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
3586 3644 nullable=True, unique=None, default=None)
3587 3645 repo = relationship('Repository', lazy='joined')
3588 3646
3589 3647 repo_group_id = Column(
3590 3648 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
3591 3649 nullable=True, unique=None, default=None)
3592 3650 repo_group = relationship('RepoGroup', lazy='joined')
3593 3651
3594 3652 @property
3595 3653 def scope(self):
3596 3654 if self.repo:
3597 3655 return repr(self.repo)
3598 3656 if self.repo_group:
3599 3657 if self.child_repos_only:
3600 3658 return repr(self.repo_group) + ' (child repos only)'
3601 3659 else:
3602 3660 return repr(self.repo_group) + ' (recursive)'
3603 3661 if self.child_repos_only:
3604 3662 return 'root_repos'
3605 3663 return 'global'
3606 3664
3607 3665 def __repr__(self):
3608 3666 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
3609 3667
3610 3668
3611 3669 class RepoReviewRuleUser(Base, BaseModel):
3612 3670 __tablename__ = 'repo_review_rules_users'
3613 3671 __table_args__ = (
3614 3672 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3615 3673 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3616 3674 )
3617 3675 repo_review_rule_user_id = Column(
3618 3676 'repo_review_rule_user_id', Integer(), primary_key=True)
3619 3677 repo_review_rule_id = Column("repo_review_rule_id",
3620 3678 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3621 3679 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'),
3622 3680 nullable=False)
3623 3681 user = relationship('User')
3624 3682
3625 3683
3626 3684 class RepoReviewRuleUserGroup(Base, BaseModel):
3627 3685 __tablename__ = 'repo_review_rules_users_groups'
3628 3686 __table_args__ = (
3629 3687 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3630 3688 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3631 3689 )
3632 3690 repo_review_rule_users_group_id = Column(
3633 3691 'repo_review_rule_users_group_id', Integer(), primary_key=True)
3634 3692 repo_review_rule_id = Column("repo_review_rule_id",
3635 3693 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3636 3694 users_group_id = Column("users_group_id", Integer(),
3637 3695 ForeignKey('users_groups.users_group_id'), nullable=False)
3638 3696 users_group = relationship('UserGroup')
3639 3697
3640 3698
3641 3699 class RepoReviewRule(Base, BaseModel):
3642 3700 __tablename__ = 'repo_review_rules'
3643 3701 __table_args__ = (
3644 3702 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3645 3703 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3646 3704 )
3647 3705
3648 3706 repo_review_rule_id = Column(
3649 3707 'repo_review_rule_id', Integer(), primary_key=True)
3650 3708 repo_id = Column(
3651 3709 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
3652 3710 repo = relationship('Repository', backref='review_rules')
3653 3711
3654 3712 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3655 3713 default=u'*') # glob
3656 3714 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3657 3715 default=u'*') # glob
3658 3716
3659 3717 use_authors_for_review = Column("use_authors_for_review", Boolean(),
3660 3718 nullable=False, default=False)
3661 3719 rule_users = relationship('RepoReviewRuleUser')
3662 3720 rule_user_groups = relationship('RepoReviewRuleUserGroup')
3663 3721
3664 3722 @hybrid_property
3665 3723 def branch_pattern(self):
3666 3724 return self._branch_pattern or '*'
3667 3725
3668 3726 def _validate_glob(self, value):
3669 3727 re.compile('^' + glob2re(value) + '$')
3670 3728
3671 3729 @branch_pattern.setter
3672 3730 def branch_pattern(self, value):
3673 3731 self._validate_glob(value)
3674 3732 self._branch_pattern = value or '*'
3675 3733
3676 3734 @hybrid_property
3677 3735 def file_pattern(self):
3678 3736 return self._file_pattern or '*'
3679 3737
3680 3738 @file_pattern.setter
3681 3739 def file_pattern(self, value):
3682 3740 self._validate_glob(value)
3683 3741 self._file_pattern = value or '*'
3684 3742
3685 3743 def matches(self, branch, files_changed):
3686 3744 """
3687 3745 Check if this review rule matches a branch/files in a pull request
3688 3746
3689 3747 :param branch: branch name for the commit
3690 3748 :param files_changed: list of file paths changed in the pull request
3691 3749 """
3692 3750
3693 3751 branch = branch or ''
3694 3752 files_changed = files_changed or []
3695 3753
3696 3754 branch_matches = True
3697 3755 if branch:
3698 3756 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
3699 3757 branch_matches = bool(branch_regex.search(branch))
3700 3758
3701 3759 files_matches = True
3702 3760 if self.file_pattern != '*':
3703 3761 files_matches = False
3704 3762 file_regex = re.compile(glob2re(self.file_pattern))
3705 3763 for filename in files_changed:
3706 3764 if file_regex.search(filename):
3707 3765 files_matches = True
3708 3766 break
3709 3767
3710 3768 return branch_matches and files_matches
3711 3769
3712 3770 @property
3713 3771 def review_users(self):
3714 3772 """ Returns the users which this rule applies to """
3715 3773
3716 3774 users = set()
3717 3775 users |= set([
3718 3776 rule_user.user for rule_user in self.rule_users
3719 3777 if rule_user.user.active])
3720 3778 users |= set(
3721 3779 member.user
3722 3780 for rule_user_group in self.rule_user_groups
3723 3781 for member in rule_user_group.users_group.members
3724 3782 if member.user.active
3725 3783 )
3726 3784 return users
3727 3785
3728 3786 def __repr__(self):
3729 3787 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
3730 3788 self.repo_review_rule_id, self.repo)
@@ -1,2206 +1,2216 b''
1 1 //Primary CSS
2 2
3 3 //--- IMPORTS ------------------//
4 4
5 5 @import 'helpers';
6 6 @import 'mixins';
7 7 @import 'rcicons';
8 8 @import 'fonts';
9 9 @import 'variables';
10 10 @import 'bootstrap-variables';
11 11 @import 'form-bootstrap';
12 12 @import 'codemirror';
13 13 @import 'legacy_code_styles';
14 14 @import 'progress-bar';
15 15
16 16 @import 'type';
17 17 @import 'alerts';
18 18 @import 'buttons';
19 19 @import 'tags';
20 20 @import 'code-block';
21 21 @import 'examples';
22 22 @import 'login';
23 23 @import 'main-content';
24 24 @import 'select2';
25 25 @import 'comments';
26 26 @import 'panels-bootstrap';
27 27 @import 'panels';
28 28 @import 'deform';
29 29
30 30 //--- BASE ------------------//
31 31 .noscript-error {
32 32 top: 0;
33 33 left: 0;
34 34 width: 100%;
35 35 z-index: 101;
36 36 text-align: center;
37 37 font-family: @text-semibold;
38 38 font-size: 120%;
39 39 color: white;
40 40 background-color: @alert2;
41 41 padding: 5px 0 5px 0;
42 42 }
43 43
44 44 html {
45 45 display: table;
46 46 height: 100%;
47 47 width: 100%;
48 48 }
49 49
50 50 body {
51 51 display: table-cell;
52 52 width: 100%;
53 53 }
54 54
55 55 //--- LAYOUT ------------------//
56 56
57 57 .hidden{
58 58 display: none !important;
59 59 }
60 60
61 61 .box{
62 62 float: left;
63 63 width: 100%;
64 64 }
65 65
66 66 .browser-header {
67 67 clear: both;
68 68 }
69 69 .main {
70 70 clear: both;
71 71 padding:0 0 @pagepadding;
72 72 height: auto;
73 73
74 74 &:after { //clearfix
75 75 content:"";
76 76 clear:both;
77 77 width:100%;
78 78 display:block;
79 79 }
80 80 }
81 81
82 82 .action-link{
83 83 margin-left: @padding;
84 84 padding-left: @padding;
85 85 border-left: @border-thickness solid @border-default-color;
86 86 }
87 87
88 88 input + .action-link, .action-link.first{
89 89 border-left: none;
90 90 }
91 91
92 92 .action-link.last{
93 93 margin-right: @padding;
94 94 padding-right: @padding;
95 95 }
96 96
97 97 .action-link.active,
98 98 .action-link.active a{
99 99 color: @grey4;
100 100 }
101 101
102 102 ul.simple-list{
103 103 list-style: none;
104 104 margin: 0;
105 105 padding: 0;
106 106 }
107 107
108 108 .main-content {
109 109 padding-bottom: @pagepadding;
110 110 }
111 111
112 112 .wide-mode-wrapper {
113 113 max-width:2400px !important;
114 114 }
115 115
116 116 .wrapper {
117 117 position: relative;
118 118 max-width: @wrapper-maxwidth;
119 119 margin: 0 auto;
120 120 }
121 121
122 122 #content {
123 123 clear: both;
124 124 padding: 0 @contentpadding;
125 125 }
126 126
127 127 .advanced-settings-fields{
128 128 input{
129 129 margin-left: @textmargin;
130 130 margin-right: @padding/2;
131 131 }
132 132 }
133 133
134 134 .cs_files_title {
135 135 margin: @pagepadding 0 0;
136 136 }
137 137
138 138 input.inline[type="file"] {
139 139 display: inline;
140 140 }
141 141
142 142 .error_page {
143 143 margin: 10% auto;
144 144
145 145 h1 {
146 146 color: @grey2;
147 147 }
148 148
149 149 .alert {
150 150 margin: @padding 0;
151 151 }
152 152
153 153 .error-branding {
154 154 font-family: @text-semibold;
155 155 color: @grey4;
156 156 }
157 157
158 158 .error_message {
159 159 font-family: @text-regular;
160 160 }
161 161
162 162 .sidebar {
163 163 min-height: 275px;
164 164 margin: 0;
165 165 padding: 0 0 @sidebarpadding @sidebarpadding;
166 166 border: none;
167 167 }
168 168
169 169 .main-content {
170 170 position: relative;
171 171 margin: 0 @sidebarpadding @sidebarpadding;
172 172 padding: 0 0 0 @sidebarpadding;
173 173 border-left: @border-thickness solid @grey5;
174 174
175 175 @media (max-width:767px) {
176 176 clear: both;
177 177 width: 100%;
178 178 margin: 0;
179 179 border: none;
180 180 }
181 181 }
182 182
183 183 .inner-column {
184 184 float: left;
185 185 width: 29.75%;
186 186 min-height: 150px;
187 187 margin: @sidebarpadding 2% 0 0;
188 188 padding: 0 2% 0 0;
189 189 border-right: @border-thickness solid @grey5;
190 190
191 191 @media (max-width:767px) {
192 192 clear: both;
193 193 width: 100%;
194 194 border: none;
195 195 }
196 196
197 197 ul {
198 198 padding-left: 1.25em;
199 199 }
200 200
201 201 &:last-child {
202 202 margin: @sidebarpadding 0 0;
203 203 border: none;
204 204 }
205 205
206 206 h4 {
207 207 margin: 0 0 @padding;
208 208 font-family: @text-semibold;
209 209 }
210 210 }
211 211 }
212 212 .error-page-logo {
213 213 width: 130px;
214 214 height: 160px;
215 215 }
216 216
217 217 // HEADER
218 218 .header {
219 219
220 220 // TODO: johbo: Fix login pages, so that they work without a min-height
221 221 // for the header and then remove the min-height. I chose a smaller value
222 222 // intentionally here to avoid rendering issues in the main navigation.
223 223 min-height: 49px;
224 224
225 225 position: relative;
226 226 vertical-align: bottom;
227 227 padding: 0 @header-padding;
228 228 background-color: @grey2;
229 229 color: @grey5;
230 230
231 231 .title {
232 232 overflow: visible;
233 233 }
234 234
235 235 &:before,
236 236 &:after {
237 237 content: "";
238 238 clear: both;
239 239 width: 100%;
240 240 }
241 241
242 242 // TODO: johbo: Avoids breaking "Repositories" chooser
243 243 .select2-container .select2-choice .select2-arrow {
244 244 display: none;
245 245 }
246 246 }
247 247
248 248 #header-inner {
249 249 &.title {
250 250 margin: 0;
251 251 }
252 252 &:before,
253 253 &:after {
254 254 content: "";
255 255 clear: both;
256 256 }
257 257 }
258 258
259 259 // Gists
260 260 #files_data {
261 261 clear: both; //for firefox
262 262 }
263 263 #gistid {
264 264 margin-right: @padding;
265 265 }
266 266
267 267 // Global Settings Editor
268 268 .textarea.editor {
269 269 float: left;
270 270 position: relative;
271 271 max-width: @texteditor-width;
272 272
273 273 select {
274 274 position: absolute;
275 275 top:10px;
276 276 right:0;
277 277 }
278 278
279 279 .CodeMirror {
280 280 margin: 0;
281 281 }
282 282
283 283 .help-block {
284 284 margin: 0 0 @padding;
285 285 padding:.5em;
286 286 background-color: @grey6;
287 287 }
288 288 }
289 289
290 290 ul.auth_plugins {
291 291 margin: @padding 0 @padding @legend-width;
292 292 padding: 0;
293 293
294 294 li {
295 295 margin-bottom: @padding;
296 296 line-height: 1em;
297 297 list-style-type: none;
298 298
299 299 .auth_buttons .btn {
300 300 margin-right: @padding;
301 301 }
302 302
303 303 &:before { content: none; }
304 304 }
305 305 }
306 306
307 307
308 308 // My Account PR list
309 309
310 310 #show_closed {
311 311 margin: 0 1em 0 0;
312 312 }
313 313
314 314 .pullrequestlist {
315 315 .closed {
316 316 background-color: @grey6;
317 317 }
318 318 .td-status {
319 319 padding-left: .5em;
320 320 }
321 321 .log-container .truncate {
322 322 height: 2.75em;
323 323 white-space: pre-line;
324 324 }
325 325 table.rctable .user {
326 326 padding-left: 0;
327 327 }
328 328 table.rctable {
329 329 td.td-description,
330 330 .rc-user {
331 331 min-width: auto;
332 332 }
333 333 }
334 334 }
335 335
336 336 // Pull Requests
337 337
338 338 .pullrequests_section_head {
339 339 display: block;
340 340 clear: both;
341 341 margin: @padding 0;
342 342 font-family: @text-bold;
343 343 }
344 344
345 345 .pr-origininfo, .pr-targetinfo {
346 346 position: relative;
347 347
348 348 .tag {
349 349 display: inline-block;
350 350 margin: 0 1em .5em 0;
351 351 }
352 352
353 353 .clone-url {
354 354 display: inline-block;
355 355 margin: 0 0 .5em 0;
356 356 padding: 0;
357 357 line-height: 1.2em;
358 358 }
359 359 }
360 360
361 361 .pr-pullinfo {
362 362 clear: both;
363 363 margin: .5em 0;
364 364 }
365 365
366 366 #pr-title-input {
367 367 width: 72%;
368 368 font-size: 1em;
369 369 font-family: @text-bold;
370 370 margin: 0;
371 371 padding: 0 0 0 @padding/4;
372 372 line-height: 1.7em;
373 373 color: @text-color;
374 374 letter-spacing: .02em;
375 375 }
376 376
377 377 #pullrequest_title {
378 378 width: 100%;
379 379 box-sizing: border-box;
380 380 }
381 381
382 382 #pr_open_message {
383 383 border: @border-thickness solid #fff;
384 384 border-radius: @border-radius;
385 385 padding: @padding-large-vertical @padding-large-vertical @padding-large-vertical 0;
386 386 text-align: right;
387 387 overflow: hidden;
388 388 }
389 389
390 390 .pr-submit-button {
391 391 float: right;
392 392 margin: 0 0 0 5px;
393 393 }
394 394
395 395 .pr-spacing-container {
396 396 padding: 20px;
397 397 clear: both
398 398 }
399 399
400 400 #pr-description-input {
401 401 margin-bottom: 0;
402 402 }
403 403
404 404 .pr-description-label {
405 405 vertical-align: top;
406 406 }
407 407
408 408 .perms_section_head {
409 409 min-width: 625px;
410 410
411 411 h2 {
412 412 margin-bottom: 0;
413 413 }
414 414
415 415 .label-checkbox {
416 416 float: left;
417 417 }
418 418
419 419 &.field {
420 420 margin: @space 0 @padding;
421 421 }
422 422
423 423 &:first-child.field {
424 424 margin-top: 0;
425 425
426 426 .label {
427 427 margin-top: 0;
428 428 padding-top: 0;
429 429 }
430 430
431 431 .radios {
432 432 padding-top: 0;
433 433 }
434 434 }
435 435
436 436 .radios {
437 437 float: right;
438 438 position: relative;
439 439 width: 405px;
440 440 }
441 441 }
442 442
443 443 //--- MODULES ------------------//
444 444
445 445
446 446 // Server Announcement
447 447 #server-announcement {
448 448 width: 95%;
449 449 margin: @padding auto;
450 450 padding: @padding;
451 451 border-width: 2px;
452 452 border-style: solid;
453 453 .border-radius(2px);
454 454 font-family: @text-bold;
455 455
456 456 &.info { border-color: @alert4; background-color: @alert4-inner; }
457 457 &.warning { border-color: @alert3; background-color: @alert3-inner; }
458 458 &.error { border-color: @alert2; background-color: @alert2-inner; }
459 459 &.success { border-color: @alert1; background-color: @alert1-inner; }
460 460 &.neutral { border-color: @grey3; background-color: @grey6; }
461 461 }
462 462
463 463 // Fixed Sidebar Column
464 464 .sidebar-col-wrapper {
465 465 padding-left: @sidebar-all-width;
466 466
467 467 .sidebar {
468 468 width: @sidebar-width;
469 469 margin-left: -@sidebar-all-width;
470 470 }
471 471 }
472 472
473 473 .sidebar-col-wrapper.scw-small {
474 474 padding-left: @sidebar-small-all-width;
475 475
476 476 .sidebar {
477 477 width: @sidebar-small-width;
478 478 margin-left: -@sidebar-small-all-width;
479 479 }
480 480 }
481 481
482 482
483 483 // FOOTER
484 484 #footer {
485 485 padding: 0;
486 486 text-align: center;
487 487 vertical-align: middle;
488 488 color: @grey2;
489 489 background-color: @grey6;
490 490
491 491 p {
492 492 margin: 0;
493 493 padding: 1em;
494 494 line-height: 1em;
495 495 }
496 496
497 497 .server-instance { //server instance
498 498 display: none;
499 499 }
500 500
501 501 .title {
502 502 float: none;
503 503 margin: 0 auto;
504 504 }
505 505 }
506 506
507 507 button.close {
508 508 padding: 0;
509 509 cursor: pointer;
510 510 background: transparent;
511 511 border: 0;
512 512 .box-shadow(none);
513 513 -webkit-appearance: none;
514 514 }
515 515
516 516 .close {
517 517 float: right;
518 518 font-size: 21px;
519 519 font-family: @text-bootstrap;
520 520 line-height: 1em;
521 521 font-weight: bold;
522 522 color: @grey2;
523 523
524 524 &:hover,
525 525 &:focus {
526 526 color: @grey1;
527 527 text-decoration: none;
528 528 cursor: pointer;
529 529 }
530 530 }
531 531
532 532 // GRID
533 533 .sorting,
534 534 .sorting_desc,
535 535 .sorting_asc {
536 536 cursor: pointer;
537 537 }
538 538 .sorting_desc:after {
539 539 content: "\00A0\25B2";
540 540 font-size: .75em;
541 541 }
542 542 .sorting_asc:after {
543 543 content: "\00A0\25BC";
544 544 font-size: .68em;
545 545 }
546 546
547 547
548 548 .user_auth_tokens {
549 549
550 550 &.truncate {
551 551 white-space: nowrap;
552 552 overflow: hidden;
553 553 text-overflow: ellipsis;
554 554 }
555 555
556 556 .fields .field .input {
557 557 margin: 0;
558 558 }
559 559
560 560 input#description {
561 561 width: 100px;
562 562 margin: 0;
563 563 }
564 564
565 565 .drop-menu {
566 566 // TODO: johbo: Remove this, should work out of the box when
567 567 // having multiple inputs inline
568 568 margin: 0 0 0 5px;
569 569 }
570 570 }
571 571 #user_list_table {
572 572 .closed {
573 573 background-color: @grey6;
574 574 }
575 575 }
576 576
577 577
578 578 input {
579 579 &.disabled {
580 580 opacity: .5;
581 581 }
582 582 }
583 583
584 584 // remove extra padding in firefox
585 585 input::-moz-focus-inner { border:0; padding:0 }
586 586
587 587 .adjacent input {
588 588 margin-bottom: @padding;
589 589 }
590 590
591 591 .permissions_boxes {
592 592 display: block;
593 593 }
594 594
595 595 //TODO: lisa: this should be in tables
596 596 .show_more_col {
597 597 width: 20px;
598 598 }
599 599
600 600 //FORMS
601 601
602 602 .medium-inline,
603 603 input#description.medium-inline {
604 604 display: inline;
605 605 width: @medium-inline-input-width;
606 606 min-width: 100px;
607 607 }
608 608
609 609 select {
610 610 //reset
611 611 -webkit-appearance: none;
612 612 -moz-appearance: none;
613 613
614 614 display: inline-block;
615 615 height: 28px;
616 616 width: auto;
617 617 margin: 0 @padding @padding 0;
618 618 padding: 0 18px 0 8px;
619 619 line-height:1em;
620 620 font-size: @basefontsize;
621 621 border: @border-thickness solid @rcblue;
622 622 background:white url("../images/dt-arrow-dn.png") no-repeat 100% 50%;
623 623 color: @rcblue;
624 624
625 625 &:after {
626 626 content: "\00A0\25BE";
627 627 }
628 628
629 629 &:focus {
630 630 outline: none;
631 631 }
632 632 }
633 633
634 634 option {
635 635 &:focus {
636 636 outline: none;
637 637 }
638 638 }
639 639
640 640 input,
641 641 textarea {
642 642 padding: @input-padding;
643 643 border: @input-border-thickness solid @border-highlight-color;
644 644 .border-radius (@border-radius);
645 645 font-family: @text-light;
646 646 font-size: @basefontsize;
647 647
648 648 &.input-sm {
649 649 padding: 5px;
650 650 }
651 651
652 652 &#description {
653 653 min-width: @input-description-minwidth;
654 654 min-height: 1em;
655 655 padding: 10px;
656 656 }
657 657 }
658 658
659 659 .field-sm {
660 660 input,
661 661 textarea {
662 662 padding: 5px;
663 663 }
664 664 }
665 665
666 666 textarea {
667 667 display: block;
668 668 clear: both;
669 669 width: 100%;
670 670 min-height: 100px;
671 671 margin-bottom: @padding;
672 672 .box-sizing(border-box);
673 673 overflow: auto;
674 674 }
675 675
676 676 label {
677 677 font-family: @text-light;
678 678 }
679 679
680 680 // GRAVATARS
681 681 // centers gravatar on username to the right
682 682
683 683 .gravatar {
684 684 display: inline;
685 685 min-width: 16px;
686 686 min-height: 16px;
687 687 margin: -5px 0;
688 688 padding: 0;
689 689 line-height: 1em;
690 690 border: 1px solid @grey4;
691 691
692 692 &.gravatar-large {
693 693 margin: -0.5em .25em -0.5em 0;
694 694 }
695 695
696 696 & + .user {
697 697 display: inline;
698 698 margin: 0;
699 699 padding: 0 0 0 .17em;
700 700 line-height: 1em;
701 701 }
702 702 }
703 703
704 704 .user-inline-data {
705 705 display: inline-block;
706 706 float: left;
707 707 padding-left: .5em;
708 708 line-height: 1.3em;
709 709 }
710 710
711 711 .rc-user { // gravatar + user wrapper
712 712 float: left;
713 713 position: relative;
714 714 min-width: 100px;
715 715 max-width: 200px;
716 716 min-height: (@gravatar-size + @border-thickness * 2); // account for border
717 717 display: block;
718 718 padding: 0 0 0 (@gravatar-size + @basefontsize/2 + @border-thickness * 2);
719 719
720 720
721 721 .gravatar {
722 722 display: block;
723 723 position: absolute;
724 724 top: 0;
725 725 left: 0;
726 726 min-width: @gravatar-size;
727 727 min-height: @gravatar-size;
728 728 margin: 0;
729 729 }
730 730
731 731 .user {
732 732 display: block;
733 733 max-width: 175px;
734 734 padding-top: 2px;
735 735 overflow: hidden;
736 736 text-overflow: ellipsis;
737 737 }
738 738 }
739 739
740 740 .gist-gravatar,
741 741 .journal_container {
742 742 .gravatar-large {
743 743 margin: 0 .5em -10px 0;
744 744 }
745 745 }
746 746
747 747
748 748 // ADMIN SETTINGS
749 749
750 750 // Tag Patterns
751 751 .tag_patterns {
752 752 .tag_input {
753 753 margin-bottom: @padding;
754 754 }
755 755 }
756 756
757 757 .locked_input {
758 758 position: relative;
759 759
760 760 input {
761 761 display: inline;
762 762 margin-top: 3px;
763 763 }
764 764
765 765 br {
766 766 display: none;
767 767 }
768 768
769 769 .error-message {
770 770 float: left;
771 771 width: 100%;
772 772 }
773 773
774 774 .lock_input_button {
775 775 display: inline;
776 776 }
777 777
778 778 .help-block {
779 779 clear: both;
780 780 }
781 781 }
782 782
783 783 // Notifications
784 784
785 785 .notifications_buttons {
786 786 margin: 0 0 @space 0;
787 787 padding: 0;
788 788
789 789 .btn {
790 790 display: inline-block;
791 791 }
792 792 }
793 793
794 794 .notification-list {
795 795
796 796 div {
797 797 display: inline-block;
798 798 vertical-align: middle;
799 799 }
800 800
801 801 .container {
802 802 display: block;
803 803 margin: 0 0 @padding 0;
804 804 }
805 805
806 806 .delete-notifications {
807 807 margin-left: @padding;
808 808 text-align: right;
809 809 cursor: pointer;
810 810 }
811 811
812 812 .read-notifications {
813 813 margin-left: @padding/2;
814 814 text-align: right;
815 815 width: 35px;
816 816 cursor: pointer;
817 817 }
818 818
819 819 .icon-minus-sign {
820 820 color: @alert2;
821 821 }
822 822
823 823 .icon-ok-sign {
824 824 color: @alert1;
825 825 }
826 826 }
827 827
828 828 .user_settings {
829 829 float: left;
830 830 clear: both;
831 831 display: block;
832 832 width: 100%;
833 833
834 834 .gravatar_box {
835 835 margin-bottom: @padding;
836 836
837 837 &:after {
838 838 content: " ";
839 839 clear: both;
840 840 width: 100%;
841 841 }
842 842 }
843 843
844 844 .fields .field {
845 845 clear: both;
846 846 }
847 847 }
848 848
849 849 .advanced_settings {
850 850 margin-bottom: @space;
851 851
852 852 .help-block {
853 853 margin-left: 0;
854 854 }
855 855
856 856 button + .help-block {
857 857 margin-top: @padding;
858 858 }
859 859 }
860 860
861 861 // admin settings radio buttons and labels
862 862 .label-2 {
863 863 float: left;
864 864 width: @label2-width;
865 865
866 866 label {
867 867 color: @grey1;
868 868 }
869 869 }
870 870 .checkboxes {
871 871 float: left;
872 872 width: @checkboxes-width;
873 873 margin-bottom: @padding;
874 874
875 875 .checkbox {
876 876 width: 100%;
877 877
878 878 label {
879 879 margin: 0;
880 880 padding: 0;
881 881 }
882 882 }
883 883
884 884 .checkbox + .checkbox {
885 885 display: inline-block;
886 886 }
887 887
888 888 label {
889 889 margin-right: 1em;
890 890 }
891 891 }
892 892
893 893 // CHANGELOG
894 894 .container_header {
895 895 float: left;
896 896 display: block;
897 897 width: 100%;
898 898 margin: @padding 0 @padding;
899 899
900 900 #filter_changelog {
901 901 float: left;
902 902 margin-right: @padding;
903 903 }
904 904
905 905 .breadcrumbs_light {
906 906 display: inline-block;
907 907 }
908 908 }
909 909
910 910 .info_box {
911 911 float: right;
912 912 }
913 913
914 914
915 915 #graph_nodes {
916 916 padding-top: 43px;
917 917 }
918 918
919 919 #graph_content{
920 920
921 921 // adjust for table headers so that graph renders properly
922 922 // #graph_nodes padding - table cell padding
923 923 padding-top: (@space - (@basefontsize * 2.4));
924 924
925 925 &.graph_full_width {
926 926 width: 100%;
927 927 max-width: 100%;
928 928 }
929 929 }
930 930
931 931 #graph {
932 932 .flag_status {
933 933 margin: 0;
934 934 }
935 935
936 936 .pagination-left {
937 937 float: left;
938 938 clear: both;
939 939 }
940 940
941 941 .log-container {
942 942 max-width: 345px;
943 943
944 944 .message{
945 945 max-width: 340px;
946 946 }
947 947 }
948 948
949 949 .graph-col-wrapper {
950 950 padding-left: 110px;
951 951
952 952 #graph_nodes {
953 953 width: 100px;
954 954 margin-left: -110px;
955 955 float: left;
956 956 clear: left;
957 957 }
958 958 }
959 959 }
960 960
961 961 #filter_changelog {
962 962 float: left;
963 963 }
964 964
965 965
966 966 //--- THEME ------------------//
967 967
968 968 #logo {
969 969 float: left;
970 970 margin: 9px 0 0 0;
971 971
972 972 .header {
973 973 background-color: transparent;
974 974 }
975 975
976 976 a {
977 977 display: inline-block;
978 978 }
979 979
980 980 img {
981 981 height:30px;
982 982 }
983 983 }
984 984
985 985 .logo-wrapper {
986 986 float:left;
987 987 }
988 988
989 989 .branding{
990 990 float: left;
991 991 padding: 9px 2px;
992 992 line-height: 1em;
993 993 font-size: @navigation-fontsize;
994 994 }
995 995
996 996 img {
997 997 border: none;
998 998 outline: none;
999 999 }
1000 1000 user-profile-header
1001 1001 label {
1002 1002
1003 1003 input[type="checkbox"] {
1004 1004 margin-right: 1em;
1005 1005 }
1006 1006 input[type="radio"] {
1007 1007 margin-right: 1em;
1008 1008 }
1009 1009 }
1010 1010
1011 1011 .flag_status {
1012 1012 margin: 2px 8px 6px 2px;
1013 1013 &.under_review {
1014 1014 .circle(5px, @alert3);
1015 1015 }
1016 1016 &.approved {
1017 1017 .circle(5px, @alert1);
1018 1018 }
1019 1019 &.rejected,
1020 1020 &.forced_closed{
1021 1021 .circle(5px, @alert2);
1022 1022 }
1023 1023 &.not_reviewed {
1024 1024 .circle(5px, @grey5);
1025 1025 }
1026 1026 }
1027 1027
1028 1028 .flag_status_comment_box {
1029 1029 margin: 5px 6px 0px 2px;
1030 1030 }
1031 1031 .test_pattern_preview {
1032 1032 margin: @space 0;
1033 1033
1034 1034 p {
1035 1035 margin-bottom: 0;
1036 1036 border-bottom: @border-thickness solid @border-default-color;
1037 1037 color: @grey3;
1038 1038 }
1039 1039
1040 1040 .btn {
1041 1041 margin-bottom: @padding;
1042 1042 }
1043 1043 }
1044 1044 #test_pattern_result {
1045 1045 display: none;
1046 1046 &:extend(pre);
1047 1047 padding: .9em;
1048 1048 color: @grey3;
1049 1049 background-color: @grey7;
1050 1050 border-right: @border-thickness solid @border-default-color;
1051 1051 border-bottom: @border-thickness solid @border-default-color;
1052 1052 border-left: @border-thickness solid @border-default-color;
1053 1053 }
1054 1054
1055 1055 #repo_vcs_settings {
1056 1056 #inherit_overlay_vcs_default {
1057 1057 display: none;
1058 1058 }
1059 1059 #inherit_overlay_vcs_custom {
1060 1060 display: custom;
1061 1061 }
1062 1062 &.inherited {
1063 1063 #inherit_overlay_vcs_default {
1064 1064 display: block;
1065 1065 }
1066 1066 #inherit_overlay_vcs_custom {
1067 1067 display: none;
1068 1068 }
1069 1069 }
1070 1070 }
1071 1071
1072 1072 .issue-tracker-link {
1073 1073 color: @rcblue;
1074 1074 }
1075 1075
1076 1076 // Issue Tracker Table Show/Hide
1077 1077 #repo_issue_tracker {
1078 1078 #inherit_overlay {
1079 1079 display: none;
1080 1080 }
1081 1081 #custom_overlay {
1082 1082 display: custom;
1083 1083 }
1084 1084 &.inherited {
1085 1085 #inherit_overlay {
1086 1086 display: block;
1087 1087 }
1088 1088 #custom_overlay {
1089 1089 display: none;
1090 1090 }
1091 1091 }
1092 1092 }
1093 1093 table.issuetracker {
1094 1094 &.readonly {
1095 1095 tr, td {
1096 1096 color: @grey3;
1097 1097 }
1098 1098 }
1099 1099 .edit {
1100 1100 display: none;
1101 1101 }
1102 1102 .editopen {
1103 1103 .edit {
1104 1104 display: inline;
1105 1105 }
1106 1106 .entry {
1107 1107 display: none;
1108 1108 }
1109 1109 }
1110 1110 tr td.td-action {
1111 1111 min-width: 117px;
1112 1112 }
1113 1113 td input {
1114 1114 max-width: none;
1115 1115 min-width: 30px;
1116 1116 width: 80%;
1117 1117 }
1118 1118 .issuetracker_pref input {
1119 1119 width: 40%;
1120 1120 }
1121 1121 input.edit_issuetracker_update {
1122 1122 margin-right: 0;
1123 1123 width: auto;
1124 1124 }
1125 1125 }
1126 1126
1127 1127 table.integrations {
1128 1128 .td-icon {
1129 1129 width: 20px;
1130 1130 .integration-icon {
1131 1131 height: 20px;
1132 1132 width: 20px;
1133 1133 }
1134 1134 }
1135 1135 }
1136 1136
1137 1137 .integrations {
1138 1138 a.integration-box {
1139 1139 color: @text-color;
1140 1140 &:hover {
1141 1141 .panel {
1142 1142 background: #fbfbfb;
1143 1143 }
1144 1144 }
1145 1145 .integration-icon {
1146 1146 width: 30px;
1147 1147 height: 30px;
1148 1148 margin-right: 20px;
1149 1149 float: left;
1150 1150 }
1151 1151
1152 1152 .panel-body {
1153 1153 padding: 10px;
1154 1154 }
1155 1155 .panel {
1156 1156 margin-bottom: 10px;
1157 1157 }
1158 1158 h2 {
1159 1159 display: inline-block;
1160 1160 margin: 0;
1161 1161 min-width: 140px;
1162 1162 }
1163 1163 }
1164 1164 }
1165 1165
1166 1166 //Permissions Settings
1167 1167 #add_perm {
1168 1168 margin: 0 0 @padding;
1169 1169 cursor: pointer;
1170 1170 }
1171 1171
1172 1172 .perm_ac {
1173 1173 input {
1174 1174 width: 95%;
1175 1175 }
1176 1176 }
1177 1177
1178 1178 .autocomplete-suggestions {
1179 1179 width: auto !important; // overrides autocomplete.js
1180 1180 margin: 0;
1181 1181 border: @border-thickness solid @rcblue;
1182 1182 border-radius: @border-radius;
1183 1183 color: @rcblue;
1184 1184 background-color: white;
1185 1185 }
1186 1186 .autocomplete-selected {
1187 1187 background: #F0F0F0;
1188 1188 }
1189 1189 .ac-container-wrap {
1190 1190 margin: 0;
1191 1191 padding: 8px;
1192 1192 border-bottom: @border-thickness solid @rclightblue;
1193 1193 list-style-type: none;
1194 1194 cursor: pointer;
1195 1195
1196 1196 &:hover {
1197 1197 background-color: @rclightblue;
1198 1198 }
1199 1199
1200 1200 img {
1201 1201 height: @gravatar-size;
1202 1202 width: @gravatar-size;
1203 1203 margin-right: 1em;
1204 1204 }
1205 1205
1206 1206 strong {
1207 1207 font-weight: normal;
1208 1208 }
1209 1209 }
1210 1210
1211 1211 // Settings Dropdown
1212 1212 .user-menu .container {
1213 1213 padding: 0 4px;
1214 1214 margin: 0;
1215 1215 }
1216 1216
1217 1217 .user-menu .gravatar {
1218 1218 cursor: pointer;
1219 1219 }
1220 1220
1221 1221 .codeblock {
1222 1222 margin-bottom: @padding;
1223 1223 clear: both;
1224 1224
1225 1225 .stats{
1226 1226 overflow: hidden;
1227 1227 }
1228 1228
1229 1229 .message{
1230 1230 textarea{
1231 1231 margin: 0;
1232 1232 }
1233 1233 }
1234 1234
1235 1235 .code-header {
1236 1236 .stats {
1237 1237 line-height: 2em;
1238 1238
1239 1239 .revision_id {
1240 1240 margin-left: 0;
1241 1241 }
1242 1242 .buttons {
1243 1243 padding-right: 0;
1244 1244 }
1245 1245 }
1246 1246
1247 1247 .item{
1248 1248 margin-right: 0.5em;
1249 1249 }
1250 1250 }
1251 1251
1252 1252 #editor_container{
1253 1253 position: relative;
1254 1254 margin: @padding;
1255 1255 }
1256 1256 }
1257 1257
1258 1258 #file_history_container {
1259 1259 display: none;
1260 1260 }
1261 1261
1262 1262 .file-history-inner {
1263 1263 margin-bottom: 10px;
1264 1264 }
1265 1265
1266 1266 // Pull Requests
1267 1267 .summary-details {
1268 1268 width: 72%;
1269 1269 }
1270 1270 .pr-summary {
1271 1271 border-bottom: @border-thickness solid @grey5;
1272 1272 margin-bottom: @space;
1273 1273 }
1274 1274 .reviewers-title {
1275 1275 width: 25%;
1276 1276 min-width: 200px;
1277 1277 }
1278 1278 .reviewers {
1279 1279 width: 25%;
1280 1280 min-width: 200px;
1281 1281 }
1282 1282 .reviewers ul li {
1283 1283 position: relative;
1284 1284 width: 100%;
1285 1285 margin-bottom: 8px;
1286 1286 }
1287 1287 .reviewers_member {
1288 1288 width: 100%;
1289 1289 overflow: auto;
1290 1290 }
1291 1291 .reviewer_reason {
1292 1292 padding-left: 20px;
1293 1293 }
1294 1294 .reviewer_status {
1295 1295 display: inline-block;
1296 1296 vertical-align: top;
1297 1297 width: 7%;
1298 1298 min-width: 20px;
1299 1299 height: 1.2em;
1300 1300 margin-top: 3px;
1301 1301 line-height: 1em;
1302 1302 }
1303 1303
1304 1304 .reviewer_name {
1305 1305 display: inline-block;
1306 1306 max-width: 83%;
1307 1307 padding-right: 20px;
1308 1308 vertical-align: middle;
1309 1309 line-height: 1;
1310 1310
1311 1311 .rc-user {
1312 1312 min-width: 0;
1313 1313 margin: -2px 1em 0 0;
1314 1314 }
1315 1315
1316 1316 .reviewer {
1317 1317 float: left;
1318 1318 }
1319 1319
1320 1320 &.to-delete {
1321 1321 .user,
1322 1322 .reviewer {
1323 1323 text-decoration: line-through;
1324 1324 }
1325 1325 }
1326 1326 }
1327 1327
1328 1328 .reviewer_member_remove {
1329 1329 position: absolute;
1330 1330 right: 0;
1331 1331 top: 0;
1332 1332 width: 16px;
1333 1333 margin-bottom: 10px;
1334 1334 padding: 0;
1335 1335 color: black;
1336 1336 }
1337 1337 .reviewer_member_status {
1338 1338 margin-top: 5px;
1339 1339 }
1340 1340 .pr-summary #summary{
1341 1341 width: 100%;
1342 1342 }
1343 1343 .pr-summary .action_button:hover {
1344 1344 border: 0;
1345 1345 cursor: pointer;
1346 1346 }
1347 1347 .pr-details-title {
1348 1348 padding-bottom: 8px;
1349 1349 border-bottom: @border-thickness solid @grey5;
1350 1350
1351 1351 .action_button.disabled {
1352 1352 color: @grey4;
1353 1353 cursor: inherit;
1354 1354 }
1355 1355 .action_button {
1356 1356 color: @rcblue;
1357 1357 }
1358 1358 }
1359 1359 .pr-details-content {
1360 1360 margin-top: @textmargin;
1361 1361 margin-bottom: @textmargin;
1362 1362 }
1363 1363 .pr-description {
1364 1364 white-space:pre-wrap;
1365 1365 }
1366 1366 .group_members {
1367 1367 margin-top: 0;
1368 1368 padding: 0;
1369 1369 list-style: outside none none;
1370 1370
1371 1371 img {
1372 1372 height: @gravatar-size;
1373 1373 width: @gravatar-size;
1374 1374 margin-right: .5em;
1375 1375 margin-left: 3px;
1376 1376 }
1377 1377
1378 1378 .to-delete {
1379 1379 .user {
1380 1380 text-decoration: line-through;
1381 1381 }
1382 1382 }
1383 1383 }
1384 1384
1385 .compare_view_commits_title {
1386 .disabled {
1387 cursor: inherit;
1388 &:hover{
1389 background-color: inherit;
1390 color: inherit;
1391 }
1392 }
1393 }
1394
1385 1395 // new entry in group_members
1386 1396 .td-author-new-entry {
1387 1397 background-color: rgba(red(@alert1), green(@alert1), blue(@alert1), 0.3);
1388 1398 }
1389 1399
1390 1400 .usergroup_member_remove {
1391 1401 width: 16px;
1392 1402 margin-bottom: 10px;
1393 1403 padding: 0;
1394 1404 color: black !important;
1395 1405 cursor: pointer;
1396 1406 }
1397 1407
1398 1408 .reviewer_ac .ac-input {
1399 1409 width: 92%;
1400 1410 margin-bottom: 1em;
1401 1411 }
1402 1412
1403 1413 .compare_view_commits tr{
1404 1414 height: 20px;
1405 1415 }
1406 1416 .compare_view_commits td {
1407 1417 vertical-align: top;
1408 1418 padding-top: 10px;
1409 1419 }
1410 1420 .compare_view_commits .author {
1411 1421 margin-left: 5px;
1412 1422 }
1413 1423
1414 1424 .compare_view_files {
1415 1425 width: 100%;
1416 1426
1417 1427 td {
1418 1428 vertical-align: middle;
1419 1429 }
1420 1430 }
1421 1431
1422 1432 .compare_view_filepath {
1423 1433 color: @grey1;
1424 1434 }
1425 1435
1426 1436 .show_more {
1427 1437 display: inline-block;
1428 1438 position: relative;
1429 1439 vertical-align: middle;
1430 1440 width: 4px;
1431 1441 height: @basefontsize;
1432 1442
1433 1443 &:after {
1434 1444 content: "\00A0\25BE";
1435 1445 display: inline-block;
1436 1446 width:10px;
1437 1447 line-height: 5px;
1438 1448 font-size: 12px;
1439 1449 cursor: pointer;
1440 1450 }
1441 1451 }
1442 1452
1443 1453 .journal_more .show_more {
1444 1454 display: inline;
1445 1455
1446 1456 &:after {
1447 1457 content: none;
1448 1458 }
1449 1459 }
1450 1460
1451 1461 .open .show_more:after,
1452 1462 .select2-dropdown-open .show_more:after {
1453 1463 .rotate(180deg);
1454 1464 margin-left: 4px;
1455 1465 }
1456 1466
1457 1467
1458 1468 .compare_view_commits .collapse_commit:after {
1459 1469 cursor: pointer;
1460 1470 content: "\00A0\25B4";
1461 1471 margin-left: -3px;
1462 1472 font-size: 17px;
1463 1473 color: @grey4;
1464 1474 }
1465 1475
1466 1476 .diff_links {
1467 1477 margin-left: 8px;
1468 1478 }
1469 1479
1470 1480 p.ancestor {
1471 1481 margin: @padding 0;
1472 1482 }
1473 1483
1474 1484 .cs_icon_td input[type="checkbox"] {
1475 1485 display: none;
1476 1486 }
1477 1487
1478 1488 .cs_icon_td .expand_file_icon:after {
1479 1489 cursor: pointer;
1480 1490 content: "\00A0\25B6";
1481 1491 font-size: 12px;
1482 1492 color: @grey4;
1483 1493 }
1484 1494
1485 1495 .cs_icon_td .collapse_file_icon:after {
1486 1496 cursor: pointer;
1487 1497 content: "\00A0\25BC";
1488 1498 font-size: 12px;
1489 1499 color: @grey4;
1490 1500 }
1491 1501
1492 1502 /*new binary
1493 1503 NEW_FILENODE = 1
1494 1504 DEL_FILENODE = 2
1495 1505 MOD_FILENODE = 3
1496 1506 RENAMED_FILENODE = 4
1497 1507 COPIED_FILENODE = 5
1498 1508 CHMOD_FILENODE = 6
1499 1509 BIN_FILENODE = 7
1500 1510 */
1501 1511 .cs_files_expand {
1502 1512 font-size: @basefontsize + 5px;
1503 1513 line-height: 1.8em;
1504 1514 float: right;
1505 1515 }
1506 1516
1507 1517 .cs_files_expand span{
1508 1518 color: @rcblue;
1509 1519 cursor: pointer;
1510 1520 }
1511 1521 .cs_files {
1512 1522 clear: both;
1513 1523 padding-bottom: @padding;
1514 1524
1515 1525 .cur_cs {
1516 1526 margin: 10px 2px;
1517 1527 font-weight: bold;
1518 1528 }
1519 1529
1520 1530 .node {
1521 1531 float: left;
1522 1532 }
1523 1533
1524 1534 .changes {
1525 1535 float: right;
1526 1536 color: white;
1527 1537 font-size: @basefontsize - 4px;
1528 1538 margin-top: 4px;
1529 1539 opacity: 0.6;
1530 1540 filter: Alpha(opacity=60); /* IE8 and earlier */
1531 1541
1532 1542 .added {
1533 1543 background-color: @alert1;
1534 1544 float: left;
1535 1545 text-align: center;
1536 1546 }
1537 1547
1538 1548 .deleted {
1539 1549 background-color: @alert2;
1540 1550 float: left;
1541 1551 text-align: center;
1542 1552 }
1543 1553
1544 1554 .bin {
1545 1555 background-color: @alert1;
1546 1556 text-align: center;
1547 1557 }
1548 1558
1549 1559 /*new binary*/
1550 1560 .bin.bin1 {
1551 1561 background-color: @alert1;
1552 1562 text-align: center;
1553 1563 }
1554 1564
1555 1565 /*deleted binary*/
1556 1566 .bin.bin2 {
1557 1567 background-color: @alert2;
1558 1568 text-align: center;
1559 1569 }
1560 1570
1561 1571 /*mod binary*/
1562 1572 .bin.bin3 {
1563 1573 background-color: @grey2;
1564 1574 text-align: center;
1565 1575 }
1566 1576
1567 1577 /*rename file*/
1568 1578 .bin.bin4 {
1569 1579 background-color: @alert4;
1570 1580 text-align: center;
1571 1581 }
1572 1582
1573 1583 /*copied file*/
1574 1584 .bin.bin5 {
1575 1585 background-color: @alert4;
1576 1586 text-align: center;
1577 1587 }
1578 1588
1579 1589 /*chmod file*/
1580 1590 .bin.bin6 {
1581 1591 background-color: @grey2;
1582 1592 text-align: center;
1583 1593 }
1584 1594 }
1585 1595 }
1586 1596
1587 1597 .cs_files .cs_added, .cs_files .cs_A,
1588 1598 .cs_files .cs_added, .cs_files .cs_M,
1589 1599 .cs_files .cs_added, .cs_files .cs_D {
1590 1600 height: 16px;
1591 1601 padding-right: 10px;
1592 1602 margin-top: 7px;
1593 1603 text-align: left;
1594 1604 }
1595 1605
1596 1606 .cs_icon_td {
1597 1607 min-width: 16px;
1598 1608 width: 16px;
1599 1609 }
1600 1610
1601 1611 .pull-request-merge {
1602 1612 padding: 10px 0;
1603 1613 margin-top: 10px;
1604 1614 margin-bottom: 20px;
1605 1615 }
1606 1616
1607 1617 .pull-request-merge .pull-request-wrap {
1608 1618 height: 25px;
1609 1619 padding: 5px 0;
1610 1620 }
1611 1621
1612 1622 .pull-request-merge span {
1613 1623 margin-right: 10px;
1614 1624 }
1615 1625 #close_pull_request {
1616 1626 margin-right: 0px;
1617 1627 }
1618 1628
1619 1629 .empty_data {
1620 1630 color: @grey4;
1621 1631 }
1622 1632
1623 1633 #changeset_compare_view_content {
1624 1634 margin-bottom: @space;
1625 1635 clear: both;
1626 1636 width: 100%;
1627 1637 box-sizing: border-box;
1628 1638 .border-radius(@border-radius);
1629 1639
1630 1640 .help-block {
1631 1641 margin: @padding 0;
1632 1642 color: @text-color;
1633 1643 }
1634 1644
1635 1645 .empty_data {
1636 1646 margin: @padding 0;
1637 1647 }
1638 1648
1639 1649 .alert {
1640 1650 margin-bottom: @space;
1641 1651 }
1642 1652 }
1643 1653
1644 1654 .table_disp {
1645 1655 .status {
1646 1656 width: auto;
1647 1657
1648 1658 .flag_status {
1649 1659 float: left;
1650 1660 }
1651 1661 }
1652 1662 }
1653 1663
1654 1664 .status_box_menu {
1655 1665 margin: 0;
1656 1666 }
1657 1667
1658 1668 .notification-table{
1659 1669 margin-bottom: @space;
1660 1670 display: table;
1661 1671 width: 100%;
1662 1672
1663 1673 .container{
1664 1674 display: table-row;
1665 1675
1666 1676 .notification-header{
1667 1677 border-bottom: @border-thickness solid @border-default-color;
1668 1678 }
1669 1679
1670 1680 .notification-subject{
1671 1681 display: table-cell;
1672 1682 }
1673 1683 }
1674 1684 }
1675 1685
1676 1686 // Notifications
1677 1687 .notification-header{
1678 1688 display: table;
1679 1689 width: 100%;
1680 1690 padding: floor(@basefontsize/2) 0;
1681 1691 line-height: 1em;
1682 1692
1683 1693 .desc, .delete-notifications, .read-notifications{
1684 1694 display: table-cell;
1685 1695 text-align: left;
1686 1696 }
1687 1697
1688 1698 .desc{
1689 1699 width: 1163px;
1690 1700 }
1691 1701
1692 1702 .delete-notifications, .read-notifications{
1693 1703 width: 35px;
1694 1704 min-width: 35px; //fixes when only one button is displayed
1695 1705 }
1696 1706 }
1697 1707
1698 1708 .notification-body {
1699 1709 .markdown-block,
1700 1710 .rst-block {
1701 1711 padding: @padding 0;
1702 1712 }
1703 1713
1704 1714 .notification-subject {
1705 1715 padding: @textmargin 0;
1706 1716 border-bottom: @border-thickness solid @border-default-color;
1707 1717 }
1708 1718 }
1709 1719
1710 1720
1711 1721 .notifications_buttons{
1712 1722 float: right;
1713 1723 }
1714 1724
1715 1725 #notification-status{
1716 1726 display: inline;
1717 1727 }
1718 1728
1719 1729 // Repositories
1720 1730
1721 1731 #summary.fields{
1722 1732 display: table;
1723 1733
1724 1734 .field{
1725 1735 display: table-row;
1726 1736
1727 1737 .label-summary{
1728 1738 display: table-cell;
1729 1739 min-width: @label-summary-minwidth;
1730 1740 padding-top: @padding/2;
1731 1741 padding-bottom: @padding/2;
1732 1742 padding-right: @padding/2;
1733 1743 }
1734 1744
1735 1745 .input{
1736 1746 display: table-cell;
1737 1747 padding: @padding/2;
1738 1748
1739 1749 input{
1740 1750 min-width: 29em;
1741 1751 padding: @padding/4;
1742 1752 }
1743 1753 }
1744 1754 .statistics, .downloads{
1745 1755 .disabled{
1746 1756 color: @grey4;
1747 1757 }
1748 1758 }
1749 1759 }
1750 1760 }
1751 1761
1752 1762 #summary{
1753 1763 width: 70%;
1754 1764 }
1755 1765
1756 1766
1757 1767 // Journal
1758 1768 .journal.title {
1759 1769 h5 {
1760 1770 float: left;
1761 1771 margin: 0;
1762 1772 width: 70%;
1763 1773 }
1764 1774
1765 1775 ul {
1766 1776 float: right;
1767 1777 display: inline-block;
1768 1778 margin: 0;
1769 1779 width: 30%;
1770 1780 text-align: right;
1771 1781
1772 1782 li {
1773 1783 display: inline;
1774 1784 font-size: @journal-fontsize;
1775 1785 line-height: 1em;
1776 1786
1777 1787 &:before { content: none; }
1778 1788 }
1779 1789 }
1780 1790 }
1781 1791
1782 1792 .filterexample {
1783 1793 position: absolute;
1784 1794 top: 95px;
1785 1795 left: @contentpadding;
1786 1796 color: @rcblue;
1787 1797 font-size: 11px;
1788 1798 font-family: @text-regular;
1789 1799 cursor: help;
1790 1800
1791 1801 &:hover {
1792 1802 color: @rcdarkblue;
1793 1803 }
1794 1804
1795 1805 @media (max-width:768px) {
1796 1806 position: relative;
1797 1807 top: auto;
1798 1808 left: auto;
1799 1809 display: block;
1800 1810 }
1801 1811 }
1802 1812
1803 1813
1804 1814 #journal{
1805 1815 margin-bottom: @space;
1806 1816
1807 1817 .journal_day{
1808 1818 margin-bottom: @textmargin/2;
1809 1819 padding-bottom: @textmargin/2;
1810 1820 font-size: @journal-fontsize;
1811 1821 border-bottom: @border-thickness solid @border-default-color;
1812 1822 }
1813 1823
1814 1824 .journal_container{
1815 1825 margin-bottom: @space;
1816 1826
1817 1827 .journal_user{
1818 1828 display: inline-block;
1819 1829 }
1820 1830 .journal_action_container{
1821 1831 display: block;
1822 1832 margin-top: @textmargin;
1823 1833
1824 1834 div{
1825 1835 display: inline;
1826 1836 }
1827 1837
1828 1838 div.journal_action_params{
1829 1839 display: block;
1830 1840 }
1831 1841
1832 1842 div.journal_repo:after{
1833 1843 content: "\A";
1834 1844 white-space: pre;
1835 1845 }
1836 1846
1837 1847 div.date{
1838 1848 display: block;
1839 1849 margin-bottom: @textmargin;
1840 1850 }
1841 1851 }
1842 1852 }
1843 1853 }
1844 1854
1845 1855 // Files
1846 1856 .edit-file-title {
1847 1857 border-bottom: @border-thickness solid @border-default-color;
1848 1858
1849 1859 .breadcrumbs {
1850 1860 margin-bottom: 0;
1851 1861 }
1852 1862 }
1853 1863
1854 1864 .edit-file-fieldset {
1855 1865 margin-top: @sidebarpadding;
1856 1866
1857 1867 .fieldset {
1858 1868 .left-label {
1859 1869 width: 13%;
1860 1870 }
1861 1871 .right-content {
1862 1872 width: 87%;
1863 1873 max-width: 100%;
1864 1874 }
1865 1875 .filename-label {
1866 1876 margin-top: 13px;
1867 1877 }
1868 1878 .commit-message-label {
1869 1879 margin-top: 4px;
1870 1880 }
1871 1881 .file-upload-input {
1872 1882 input {
1873 1883 display: none;
1874 1884 }
1875 1885 }
1876 1886 p {
1877 1887 margin-top: 5px;
1878 1888 }
1879 1889
1880 1890 }
1881 1891 .custom-path-link {
1882 1892 margin-left: 5px;
1883 1893 }
1884 1894 #commit {
1885 1895 resize: vertical;
1886 1896 }
1887 1897 }
1888 1898
1889 1899 .delete-file-preview {
1890 1900 max-height: 250px;
1891 1901 }
1892 1902
1893 1903 .new-file,
1894 1904 #filter_activate,
1895 1905 #filter_deactivate {
1896 1906 float: left;
1897 1907 margin: 0 0 0 15px;
1898 1908 }
1899 1909
1900 1910 h3.files_location{
1901 1911 line-height: 2.4em;
1902 1912 }
1903 1913
1904 1914 .browser-nav {
1905 1915 display: table;
1906 1916 margin-bottom: @space;
1907 1917
1908 1918
1909 1919 .info_box {
1910 1920 display: inline-table;
1911 1921 height: 2.5em;
1912 1922
1913 1923 .browser-cur-rev, .info_box_elem {
1914 1924 display: table-cell;
1915 1925 vertical-align: middle;
1916 1926 }
1917 1927
1918 1928 .info_box_elem {
1919 1929 border-top: @border-thickness solid @rcblue;
1920 1930 border-bottom: @border-thickness solid @rcblue;
1921 1931
1922 1932 #at_rev, a {
1923 1933 padding: 0.6em 0.9em;
1924 1934 margin: 0;
1925 1935 .box-shadow(none);
1926 1936 border: 0;
1927 1937 height: 12px;
1928 1938 }
1929 1939
1930 1940 input#at_rev {
1931 1941 max-width: 50px;
1932 1942 text-align: right;
1933 1943 }
1934 1944
1935 1945 &.previous {
1936 1946 border: @border-thickness solid @rcblue;
1937 1947 .disabled {
1938 1948 color: @grey4;
1939 1949 cursor: not-allowed;
1940 1950 }
1941 1951 }
1942 1952
1943 1953 &.next {
1944 1954 border: @border-thickness solid @rcblue;
1945 1955 .disabled {
1946 1956 color: @grey4;
1947 1957 cursor: not-allowed;
1948 1958 }
1949 1959 }
1950 1960 }
1951 1961
1952 1962 .browser-cur-rev {
1953 1963
1954 1964 span{
1955 1965 margin: 0;
1956 1966 color: @rcblue;
1957 1967 height: 12px;
1958 1968 display: inline-block;
1959 1969 padding: 0.7em 1em ;
1960 1970 border: @border-thickness solid @rcblue;
1961 1971 margin-right: @padding;
1962 1972 }
1963 1973 }
1964 1974 }
1965 1975
1966 1976 .search_activate {
1967 1977 display: table-cell;
1968 1978 vertical-align: middle;
1969 1979
1970 1980 input, label{
1971 1981 margin: 0;
1972 1982 padding: 0;
1973 1983 }
1974 1984
1975 1985 input{
1976 1986 margin-left: @textmargin;
1977 1987 }
1978 1988
1979 1989 }
1980 1990 }
1981 1991
1982 1992 .browser-cur-rev{
1983 1993 margin-bottom: @textmargin;
1984 1994 }
1985 1995
1986 1996 #node_filter_box_loading{
1987 1997 .info_text;
1988 1998 }
1989 1999
1990 2000 .browser-search {
1991 2001 margin: -25px 0px 5px 0px;
1992 2002 }
1993 2003
1994 2004 .node-filter {
1995 2005 font-size: @repo-title-fontsize;
1996 2006 padding: 4px 0px 0px 0px;
1997 2007
1998 2008 .node-filter-path {
1999 2009 float: left;
2000 2010 color: @grey4;
2001 2011 }
2002 2012 .node-filter-input {
2003 2013 float: left;
2004 2014 margin: -2px 0px 0px 2px;
2005 2015 input {
2006 2016 padding: 2px;
2007 2017 border: none;
2008 2018 font-size: @repo-title-fontsize;
2009 2019 }
2010 2020 }
2011 2021 }
2012 2022
2013 2023
2014 2024 .browser-result{
2015 2025 td a{
2016 2026 margin-left: 0.5em;
2017 2027 display: inline-block;
2018 2028
2019 2029 em{
2020 2030 font-family: @text-bold;
2021 2031 }
2022 2032 }
2023 2033 }
2024 2034
2025 2035 .browser-highlight{
2026 2036 background-color: @grey5-alpha;
2027 2037 }
2028 2038
2029 2039
2030 2040 // Search
2031 2041
2032 2042 .search-form{
2033 2043 #q {
2034 2044 width: @search-form-width;
2035 2045 }
2036 2046 .fields{
2037 2047 margin: 0 0 @space;
2038 2048 }
2039 2049
2040 2050 label{
2041 2051 display: inline-block;
2042 2052 margin-right: @textmargin;
2043 2053 padding-top: 0.25em;
2044 2054 }
2045 2055
2046 2056
2047 2057 .results{
2048 2058 clear: both;
2049 2059 margin: 0 0 @padding;
2050 2060 }
2051 2061 }
2052 2062
2053 2063 div.search-feedback-items {
2054 2064 display: inline-block;
2055 2065 padding:0px 0px 0px 96px;
2056 2066 }
2057 2067
2058 2068 div.search-code-body {
2059 2069 background-color: #ffffff; padding: 5px 0 5px 10px;
2060 2070 pre {
2061 2071 .match { background-color: #faffa6;}
2062 2072 .break { display: block; width: 100%; background-color: #DDE7EF; color: #747474; }
2063 2073 }
2064 2074 }
2065 2075
2066 2076 .expand_commit.search {
2067 2077 .show_more.open {
2068 2078 height: auto;
2069 2079 max-height: none;
2070 2080 }
2071 2081 }
2072 2082
2073 2083 .search-results {
2074 2084
2075 2085 h2 {
2076 2086 margin-bottom: 0;
2077 2087 }
2078 2088 .codeblock {
2079 2089 border: none;
2080 2090 background: transparent;
2081 2091 }
2082 2092
2083 2093 .codeblock-header {
2084 2094 border: none;
2085 2095 background: transparent;
2086 2096 }
2087 2097
2088 2098 .code-body {
2089 2099 border: @border-thickness solid @border-default-color;
2090 2100 .border-radius(@border-radius);
2091 2101 }
2092 2102
2093 2103 .td-commit {
2094 2104 &:extend(pre);
2095 2105 border-bottom: @border-thickness solid @border-default-color;
2096 2106 }
2097 2107
2098 2108 .message {
2099 2109 height: auto;
2100 2110 max-width: 350px;
2101 2111 white-space: normal;
2102 2112 text-overflow: initial;
2103 2113 overflow: visible;
2104 2114
2105 2115 .match { background-color: #faffa6;}
2106 2116 .break { background-color: #DDE7EF; width: 100%; color: #747474; display: block; }
2107 2117 }
2108 2118
2109 2119 }
2110 2120
2111 2121 table.rctable td.td-search-results div {
2112 2122 max-width: 100%;
2113 2123 }
2114 2124
2115 2125 #tip-box, .tip-box{
2116 2126 padding: @menupadding/2;
2117 2127 display: block;
2118 2128 border: @border-thickness solid @border-highlight-color;
2119 2129 .border-radius(@border-radius);
2120 2130 background-color: white;
2121 2131 z-index: 99;
2122 2132 white-space: pre-wrap;
2123 2133 }
2124 2134
2125 2135 #linktt {
2126 2136 width: 79px;
2127 2137 }
2128 2138
2129 2139 #help_kb .modal-content{
2130 2140 max-width: 750px;
2131 2141 margin: 10% auto;
2132 2142
2133 2143 table{
2134 2144 td,th{
2135 2145 border-bottom: none;
2136 2146 line-height: 2.5em;
2137 2147 }
2138 2148 th{
2139 2149 padding-bottom: @textmargin/2;
2140 2150 }
2141 2151 td.keys{
2142 2152 text-align: center;
2143 2153 }
2144 2154 }
2145 2155
2146 2156 .block-left{
2147 2157 width: 45%;
2148 2158 margin-right: 5%;
2149 2159 }
2150 2160 .modal-footer{
2151 2161 clear: both;
2152 2162 }
2153 2163 .key.tag{
2154 2164 padding: 0.5em;
2155 2165 background-color: @rcblue;
2156 2166 color: white;
2157 2167 border-color: @rcblue;
2158 2168 .box-shadow(none);
2159 2169 }
2160 2170 }
2161 2171
2162 2172
2163 2173
2164 2174 //--- IMPORTS FOR REFACTORED STYLES ------------------//
2165 2175
2166 2176 @import 'statistics-graph';
2167 2177 @import 'tables';
2168 2178 @import 'forms';
2169 2179 @import 'diff';
2170 2180 @import 'summary';
2171 2181 @import 'navigation';
2172 2182
2173 2183 //--- SHOW/HIDE SECTIONS --//
2174 2184
2175 2185 .btn-collapse {
2176 2186 float: right;
2177 2187 text-align: right;
2178 2188 font-family: @text-light;
2179 2189 font-size: @basefontsize;
2180 2190 cursor: pointer;
2181 2191 border: none;
2182 2192 color: @rcblue;
2183 2193 }
2184 2194
2185 2195 table.rctable,
2186 2196 table.dataTable {
2187 2197 .btn-collapse {
2188 2198 float: right;
2189 2199 text-align: right;
2190 2200 }
2191 2201 }
2192 2202
2193 2203
2194 2204 // TODO: johbo: Fix for IE10, this avoids that we see a border
2195 2205 // and padding around checkboxes and radio boxes. Move to the right place,
2196 2206 // or better: Remove this once we did the form refactoring.
2197 2207 input[type=checkbox],
2198 2208 input[type=radio] {
2199 2209 padding: 0;
2200 2210 border: none;
2201 2211 }
2202 2212
2203 2213 .toggle-ajax-spinner{
2204 2214 height: 16px;
2205 2215 width: 16px;
2206 2216 }
@@ -1,527 +1,559 b''
1 1 <%inherit file="/base/base.html"/>
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 <script type="text/javascript">
32 32 // TODO: marcink switch this to pyroutes
33 33 AJAX_COMMENT_DELETE_URL = "${url('pullrequest_comment_delete',repo_name=c.repo_name,comment_id='__COMMENT_ID__')}";
34 34 templateContext.pull_request_data.pull_request_id = ${c.pull_request.pull_request_id};
35 35 </script>
36 36 <div class="box">
37 37 <div class="title">
38 38 ${self.repo_page_title(c.rhodecode_db_repo)}
39 39 </div>
40 40
41 41 ${self.breadcrumbs()}
42 42
43 43
44 44 <div class="box pr-summary">
45 45 <div class="summary-details block-left">
46 46 <%summary = lambda n:{False:'summary-short'}.get(n)%>
47 47 <div class="pr-details-title">
48 ${_('Pull request #%s') % c.pull_request.pull_request_id} ${_('From')} ${h.format_date(c.pull_request.created_on)}
48 <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 49 %if c.allowed_to_update:
50 50 <div id="delete_pullrequest" class="pull-right action_button ${'' if c.allowed_to_delete else 'disabled' }" style="clear:inherit;padding: 0">
51 51 % if c.allowed_to_delete:
52 52 ${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 53 ${h.submit('remove_%s' % c.pull_request.pull_request_id, _('Delete'),
54 54 class_="btn btn-link btn-danger",onclick="return confirm('"+_('Confirm to delete this pull request')+"');")}
55 55 ${h.end_form()}
56 56 % else:
57 57 ${_('Delete')}
58 58 % endif
59 59 </div>
60 60 <div id="open_edit_pullrequest" class="pull-right action_button">${_('Edit')}</div>
61 61 <div id="close_edit_pullrequest" class="pull-right action_button" style="display: none;padding: 0">${_('Cancel edit')}</div>
62 62 %endif
63 63 </div>
64 64
65 65 <div id="summary" class="fields pr-details-content">
66 66 <div class="field">
67 67 <div class="label-summary">
68 68 <label>${_('Origin')}:</label>
69 69 </div>
70 70 <div class="input">
71 71 <div class="pr-origininfo">
72 72 ## branch link is only valid if it is a branch
73 73 <span class="tag">
74 74 %if c.pull_request.source_ref_parts.type == 'branch':
75 75 <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 76 %else:
77 77 ${c.pull_request.source_ref_parts.type}: ${c.pull_request.source_ref_parts.name}
78 78 %endif
79 79 </span>
80 80 <span class="clone-url">
81 81 <a href="${h.url('summary_home', repo_name=c.pull_request.source_repo.repo_name)}">${c.pull_request.source_repo.clone_url()}</a>
82 82 </span>
83 83 </div>
84 84 <div class="pr-pullinfo">
85 85 %if h.is_hg(c.pull_request.source_repo):
86 86 <input type="text" value="hg pull -r ${h.short_id(c.source_ref)} ${c.pull_request.source_repo.clone_url()}" readonly="readonly">
87 87 %elif h.is_git(c.pull_request.source_repo):
88 88 <input type="text" value="git pull ${c.pull_request.source_repo.clone_url()} ${c.pull_request.source_ref_parts.name}" readonly="readonly">
89 89 %endif
90 90 </div>
91 91 </div>
92 92 </div>
93 93 <div class="field">
94 94 <div class="label-summary">
95 95 <label>${_('Target')}:</label>
96 96 </div>
97 97 <div class="input">
98 98 <div class="pr-targetinfo">
99 99 ## branch link is only valid if it is a branch
100 100 <span class="tag">
101 101 %if c.pull_request.target_ref_parts.type == 'branch':
102 102 <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 103 %else:
104 104 ${c.pull_request.target_ref_parts.type}: ${c.pull_request.target_ref_parts.name}
105 105 %endif
106 106 </span>
107 107 <span class="clone-url">
108 108 <a href="${h.url('summary_home', repo_name=c.pull_request.target_repo.repo_name)}">${c.pull_request.target_repo.clone_url()}</a>
109 109 </span>
110 110 </div>
111 111 </div>
112 112 </div>
113 113
114 114 ## Link to the shadow repository.
115 %if not c.pull_request.is_closed() and c.pull_request.shadow_merge_ref:
116 <div class="field">
117 <div class="label-summary">
118 <label>Merge:</label>
115 <div class="field">
116 <div class="label-summary">
117 <label>${_('Merge')}:</label>
118 </div>
119 <div class="input">
120 % if not c.pull_request.is_closed() and c.pull_request.shadow_merge_ref:
121 <div class="pr-mergeinfo">
122 %if h.is_hg(c.pull_request.target_repo):
123 <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 %elif h.is_git(c.pull_request.target_repo):
125 <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 %endif
119 127 </div>
120 <div class="input">
121 <div class="pr-mergeinfo">
122 %if h.is_hg(c.pull_request.target_repo):
123 <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 %elif h.is_git(c.pull_request.target_repo):
125 <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 %endif
127 </div>
128 % else:
129 <div class="">
130 ${_('Shadow repository data not available')}.
128 131 </div>
132 % endif
129 133 </div>
130 %endif
134 </div>
131 135
132 136 <div class="field">
133 137 <div class="label-summary">
134 138 <label>${_('Review')}:</label>
135 139 </div>
136 140 <div class="input">
137 141 %if c.pull_request_review_status:
138 142 <div class="${'flag_status %s' % c.pull_request_review_status} tooltip pull-left"></div>
139 143 <span class="changeset-status-lbl tooltip">
140 144 %if c.pull_request.is_closed():
141 145 ${_('Closed')},
142 146 %endif
143 147 ${h.commit_status_lbl(c.pull_request_review_status)}
144 148 </span>
145 149 - ${ungettext('calculated based on %s reviewer vote', 'calculated based on %s reviewers votes', len(c.pull_request_reviewers)) % len(c.pull_request_reviewers)}
146 150 %endif
147 151 </div>
148 152 </div>
149 153 <div class="field">
150 154 <div class="pr-description-label label-summary">
151 155 <label>${_('Description')}:</label>
152 156 </div>
153 157 <div id="pr-desc" class="input">
154 158 <div class="pr-description">${h.urlify_commit_message(c.pull_request.description, c.repo_name)}</div>
155 159 </div>
156 160 <div id="pr-desc-edit" class="input textarea editor" style="display: none;">
157 161 <textarea id="pr-description-input" size="30">${c.pull_request.description}</textarea>
158 162 </div>
159 163 </div>
160 164 <div class="field">
161 165 <div class="label-summary">
162 166 <label>${_('Comments')}:</label>
163 167 </div>
164 168 <div class="input">
165 169 <div>
166 170 <div class="comments-number">
167 171 %if c.comments:
168 172 <a href="#comments">${ungettext("%d General Comment", "%d General Comments", len(c.comments)) % len(c.comments)}</a>,
169 173 %else:
170 174 ${ungettext("%d General Comment", "%d General Comments", len(c.comments)) % len(c.comments)}
171 175 %endif
172 176
173 177 %if c.inline_cnt:
174 178 <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>
175 179 %else:
176 180 ${ungettext("%d Inline Comment", "%d Inline Comments", c.inline_cnt) % c.inline_cnt}
177 181 %endif
178 182
179 183 %if c.outdated_cnt:
180 184 , ${ungettext("%d Outdated Comment", "%d Outdated Comments", c.outdated_cnt) % c.outdated_cnt} <span id="show-outdated-comments" class="btn btn-link">${_('(Show)')}</span>
181 185 %endif
182 186 </div>
183 187 </div>
184 188 </div>
185 189
186 190 </div>
187 191
188 192 <div class="field">
189 193 <div class="label-summary">
190 <label>${_('Versions')}:</label>
194 <label>${_('Versions')} (${len(c.versions)}):</label>
191 195 </div>
196
192 197 <div>
198 % if c.show_version_changes:
193 199 <table>
194 200 <tr>
195 201 <td>
196 % if c.at_version == None:
202 % if c.at_version in [None, 'latest']:
197 203 <i class="icon-ok link"></i>
198 204 % endif
199 205 </td>
200 <td><code><a href="${h.url.current()}">latest</a></code></td>
206 <td><code><a href="${h.url.current(version='latest')}">latest</a></code></td>
201 207 <td>
202 208 <code>${c.pull_request_latest.source_ref_parts.commit_id[:6]}</code>
203 209 </td>
204 <td>${_('created')} ${h.age_component(c.pull_request.created_on)}</td>
210 <td>${_('created')} ${h.age_component(c.pull_request_latest.updated_on)}</td>
205 211 </tr>
206 212 % for ver in reversed(c.pull_request.versions()):
207 213 <tr>
208 214 <td>
209 215 % if c.at_version == ver.pull_request_version_id:
210 216 <i class="icon-ok link"></i>
211 217 % endif
212 218 </td>
213 219 <td><code><a href="${h.url.current(version=ver.pull_request_version_id)}">version ${ver.pull_request_version_id}</a></code></td>
214 220 <td>
215 221 <code>${ver.source_ref_parts.commit_id[:6]}</code>
216 222 </td>
217 <td>${_('created')} ${h.age_component(ver.created_on)}</td>
223 <td>${_('created')} ${h.age_component(ver.updated_on)}</td>
218 224 </tr>
219 225 % endfor
220 226 </table>
227
228 % if c.at_version:
229 <pre>
230 Changed commits:
231 * added: ${len(c.changes.added)}
232 * removed: ${len(c.changes.removed)}
233
234 % if not (c.file_changes.added+c.file_changes.modified+c.file_changes.removed):
235 No file changes found
236 % else:
237 Changed files:
238 %for file_name in c.file_changes.added:
239 * A <a href="#${'a_' + h.FID('', file_name)}">${file_name}</a>
240 %endfor
241 %for file_name in c.file_changes.modified:
242 * M <a href="#${'a_' + h.FID('', file_name)}">${file_name}</a>
243 %endfor
244 %for file_name in c.file_changes.removed:
245 * R ${file_name}
246 %endfor
247 % endif
248 </pre>
249 % endif
250 % else:
251 ${_('Pull request versions not available')}.
252 % endif
221 253 </div>
222 254 </div>
223 255
224 256 <div id="pr-save" class="field" style="display: none;">
225 257 <div class="label-summary"></div>
226 258 <div class="input">
227 259 <span id="edit_pull_request" class="btn btn-small">${_('Save Changes')}</span>
228 260 </div>
229 261 </div>
230 262 </div>
231 263 </div>
232 264 <div>
233 265 ## AUTHOR
234 266 <div class="reviewers-title block-right">
235 267 <div class="pr-details-title">
236 268 ${_('Author')}
237 269 </div>
238 270 </div>
239 271 <div class="block-right pr-details-content reviewers">
240 272 <ul class="group_members">
241 273 <li>
242 274 ${self.gravatar_with_user(c.pull_request.author.email, 16)}
243 275 </li>
244 276 </ul>
245 277 </div>
246 278 ## REVIEWERS
247 279 <div class="reviewers-title block-right">
248 280 <div class="pr-details-title">
249 281 ${_('Pull request reviewers')}
250 282 %if c.allowed_to_update:
251 283 <span id="open_edit_reviewers" class="block-right action_button">${_('Edit')}</span>
252 284 <span id="close_edit_reviewers" class="block-right action_button" style="display: none;">${_('Close')}</span>
253 285 %endif
254 286 </div>
255 287 </div>
256 288 <div id="reviewers" class="block-right pr-details-content reviewers">
257 289 ## members goes here !
258 290 <input type="hidden" name="__start__" value="review_members:sequence">
259 291 <ul id="review_members" class="group_members">
260 292 %for member,reasons,status in c.pull_request_reviewers:
261 293 <li id="reviewer_${member.user_id}">
262 294 <div class="reviewers_member">
263 295 <div class="reviewer_status tooltip" title="${h.tooltip(h.commit_status_lbl(status[0][1].status if status else 'not_reviewed'))}">
264 296 <div class="${'flag_status %s' % (status[0][1].status if status else 'not_reviewed')} pull-left reviewer_member_status"></div>
265 297 </div>
266 298 <div id="reviewer_${member.user_id}_name" class="reviewer_name">
267 299 ${self.gravatar_with_user(member.email, 16)}
268 300 </div>
269 301 <input type="hidden" name="__start__" value="reviewer:mapping">
270 302 <input type="hidden" name="__start__" value="reasons:sequence">
271 303 %for reason in reasons:
272 304 <div class="reviewer_reason">- ${reason}</div>
273 305 <input type="hidden" name="reason" value="${reason}">
274 306
275 307 %endfor
276 308 <input type="hidden" name="__end__" value="reasons:sequence">
277 309 <input id="reviewer_${member.user_id}_input" type="hidden" value="${member.user_id}" name="user_id" />
278 310 <input type="hidden" name="__end__" value="reviewer:mapping">
279 311 %if c.allowed_to_update:
280 312 <div class="reviewer_member_remove action_button" onclick="removeReviewMember(${member.user_id}, true)" style="visibility: hidden;">
281 313 <i class="icon-remove-sign" ></i>
282 314 </div>
283 315 %endif
284 316 </div>
285 317 </li>
286 318 %endfor
287 319 </ul>
288 320 <input type="hidden" name="__end__" value="review_members:sequence">
289 321 %if not c.pull_request.is_closed():
290 322 <div id="add_reviewer_input" class='ac' style="display: none;">
291 323 %if c.allowed_to_update:
292 324 <div class="reviewer_ac">
293 325 ${h.text('user', class_='ac-input', placeholder=_('Add reviewer'))}
294 326 <div id="reviewers_container"></div>
295 327 </div>
296 328 <div>
297 329 <span id="update_pull_request" class="btn btn-small">${_('Save Changes')}</span>
298 330 </div>
299 331 %endif
300 332 </div>
301 333 %endif
302 334 </div>
303 335 </div>
304 336 </div>
305 337 <div class="box">
306 338 ##DIFF
307 339 <div class="table" >
308 340 <div id="changeset_compare_view_content">
309 341 ##CS
310 342 % if c.missing_requirements:
311 343 <div class="box">
312 344 <div class="alert alert-warning">
313 345 <div>
314 346 <strong>${_('Missing requirements:')}</strong>
315 347 ${_('These commits cannot be displayed, because this repository uses the Mercurial largefiles extension, which was not enabled.')}
316 348 </div>
317 349 </div>
318 350 </div>
319 351 % elif c.missing_commits:
320 352 <div class="box">
321 353 <div class="alert alert-warning">
322 354 <div>
323 355 <strong>${_('Missing commits')}:</strong>
324 356 ${_('This pull request cannot be displayed, because one or more commits no longer exist in the source repository.')}
325 357 ${_('Please update this pull request, push the commits back into the source repository, or consider closing this pull request.')}
326 358 </div>
327 359 </div>
328 360 </div>
329 361 % endif
330 362 <div class="compare_view_commits_title">
331 363 % if c.allowed_to_update and not c.pull_request.is_closed():
332 <button id="update_commits" class="btn pull-right">${_('Update commits')}</button>
364 <a id="update_commits" class="btn btn-primary pull-right">${_('Update commits')}</a>
333 365 % else:
334 <button class="btn disabled pull-right" disabled="disabled">${_('Update commits')}</button>
366 <a class="tooltip btn disabled pull-right" disabled="disabled" title="${_('Update is disabled for current view')}">${_('Update commits')}</a>
335 367 % endif
336 368 % if len(c.commit_ranges):
337 369 <h2>${ungettext('Compare View: %s commit','Compare View: %s commits', len(c.commit_ranges)) % len(c.commit_ranges)}</h2>
338 370 % endif
339 371 </div>
340 372 % if not c.missing_commits:
341 373 <%include file="/compare/compare_commits.html" />
342 374 <div class="cs_files">
343 375 <%namespace name="cbdiffs" file="/codeblocks/diffs.html"/>
344 376 ${cbdiffs.render_diffset_menu()}
345 377 ${cbdiffs.render_diffset(
346 378 c.diffset, use_comments=True,
347 379 collapse_when_files_over=30,
348 380 disable_new_comments=not c.allowed_to_comment)}
349 381
350 382 </div>
351 383 % endif
352 384 </div>
353 385
354 386 ## template for inline comment form
355 387 <%namespace name="comment" file="/changeset/changeset_file_comment.html"/>
356 388
357 389 ## render general comments
358 390 ${comment.generate_comments(include_pull_request=True, is_pull_request=True)}
359 391
360 392 % if not c.pull_request.is_closed():
361 393 ## main comment form and it status
362 394 ${comment.comments(h.url('pullrequest_comment', repo_name=c.repo_name,
363 395 pull_request_id=c.pull_request.pull_request_id),
364 396 c.pull_request_review_status,
365 397 is_pull_request=True, change_status=c.allowed_to_change_status)}
366 398 %endif
367 399
368 400 <script type="text/javascript">
369 401 if (location.hash) {
370 402 var result = splitDelimitedHash(location.hash);
371 403 var line = $('html').find(result.loc);
372 404 if (line.length > 0){
373 405 offsetScroll(line, 70);
374 406 }
375 407 }
376 408 $(function(){
377 409 ReviewerAutoComplete('user');
378 410 // custom code mirror
379 411 var codeMirrorInstance = initPullRequestsCodeMirror('#pr-description-input');
380 412
381 413 var PRDetails = {
382 414 editButton: $('#open_edit_pullrequest'),
383 415 closeButton: $('#close_edit_pullrequest'),
384 416 deleteButton: $('#delete_pullrequest'),
385 417 viewFields: $('#pr-desc, #pr-title'),
386 418 editFields: $('#pr-desc-edit, #pr-title-edit, #pr-save'),
387 419
388 420 init: function() {
389 421 var that = this;
390 422 this.editButton.on('click', function(e) { that.edit(); });
391 423 this.closeButton.on('click', function(e) { that.view(); });
392 424 },
393 425
394 426 edit: function(event) {
395 427 this.viewFields.hide();
396 428 this.editButton.hide();
397 429 this.deleteButton.hide();
398 430 this.closeButton.show();
399 431 this.editFields.show();
400 432 codeMirrorInstance.refresh();
401 433 },
402 434
403 435 view: function(event) {
404 436 this.editButton.show();
405 437 this.deleteButton.show();
406 438 this.editFields.hide();
407 439 this.closeButton.hide();
408 440 this.viewFields.show();
409 441 }
410 442 };
411 443
412 444 var ReviewersPanel = {
413 445 editButton: $('#open_edit_reviewers'),
414 446 closeButton: $('#close_edit_reviewers'),
415 447 addButton: $('#add_reviewer_input'),
416 448 removeButtons: $('.reviewer_member_remove'),
417 449
418 450 init: function() {
419 451 var that = this;
420 452 this.editButton.on('click', function(e) { that.edit(); });
421 453 this.closeButton.on('click', function(e) { that.close(); });
422 454 },
423 455
424 456 edit: function(event) {
425 457 this.editButton.hide();
426 458 this.closeButton.show();
427 459 this.addButton.show();
428 460 this.removeButtons.css('visibility', 'visible');
429 461 },
430 462
431 463 close: function(event) {
432 464 this.editButton.show();
433 465 this.closeButton.hide();
434 466 this.addButton.hide();
435 467 this.removeButtons.css('visibility', 'hidden');
436 468 }
437 469 };
438 470
439 471 PRDetails.init();
440 472 ReviewersPanel.init();
441 473
442 474 $('#show-outdated-comments').on('click', function(e){
443 475 var button = $(this);
444 476 var outdated = $('.comment-outdated');
445 477 if (button.html() === "(Show)") {
446 478 button.html("(Hide)");
447 479 outdated.show();
448 480 } else {
449 481 button.html("(Show)");
450 482 outdated.hide();
451 483 }
452 484 });
453 485
454 486 $('.show-inline-comments').on('change', function(e){
455 487 var show = 'none';
456 488 var target = e.currentTarget;
457 489 if(target.checked){
458 490 show = ''
459 491 }
460 492 var boxid = $(target).attr('id_for');
461 493 var comments = $('#{0} .inline-comments'.format(boxid));
462 494 var fn_display = function(idx){
463 495 $(this).css('display', show);
464 496 };
465 497 $(comments).each(fn_display);
466 498 var btns = $('#{0} .inline-comments-button'.format(boxid));
467 499 $(btns).each(fn_display);
468 500 });
469 501
470 502 $('#merge_pull_request_form').submit(function() {
471 503 if (!$('#merge_pull_request').attr('disabled')) {
472 504 $('#merge_pull_request').attr('disabled', 'disabled');
473 505 }
474 506 return true;
475 507 });
476 508
477 509 $('#edit_pull_request').on('click', function(e){
478 510 var title = $('#pr-title-input').val();
479 511 var description = codeMirrorInstance.getValue();
480 512 editPullRequest(
481 513 "${c.repo_name}", "${c.pull_request.pull_request_id}",
482 514 title, description);
483 515 });
484 516
485 517 $('#update_pull_request').on('click', function(e){
486 518 updateReviewers(undefined, "${c.repo_name}", "${c.pull_request.pull_request_id}");
487 519 });
488 520
489 521 $('#update_commits').on('click', function(e){
490 522 var isDisabled = !$(e.currentTarget).attr('disabled');
491 523 $(e.currentTarget).text(_gettext('Updating...'));
492 524 $(e.currentTarget).attr('disabled', 'disabled');
493 525 if(isDisabled){
494 526 updateCommits("${c.repo_name}", "${c.pull_request.pull_request_id}");
495 527 }
496 528
497 529 });
498 530 // fixing issue with caches on firefox
499 531 $('#update_commits').removeAttr("disabled");
500 532
501 533 $('#close_pull_request').on('click', function(e){
502 534 closePullRequest("${c.repo_name}", "${c.pull_request.pull_request_id}");
503 535 });
504 536
505 537 $('.show-inline-comments').on('click', function(e){
506 538 var boxid = $(this).attr('data-comment-id');
507 539 var button = $(this);
508 540
509 541 if(button.hasClass("comments-visible")) {
510 542 $('#{0} .inline-comments'.format(boxid)).each(function(index){
511 543 $(this).hide();
512 544 });
513 545 button.removeClass("comments-visible");
514 546 } else {
515 547 $('#{0} .inline-comments'.format(boxid)).each(function(index){
516 548 $(this).show();
517 549 });
518 550 button.addClass("comments-visible");
519 551 }
520 552 });
521 553 })
522 554 </script>
523 555
524 556 </div>
525 557 </div>
526 558
527 559 </%def>
@@ -1,27 +1,27 b''
1 1 ## -*- coding: utf-8 -*-
2 Auto status change to |under_review|
2 Pull request updated. Auto status change to |under_review|
3 3
4 4 .. role:: added
5 5 .. role:: removed
6 6 .. parsed-literal::
7 7
8 8 Changed commits:
9 9 * :added:`${len(added_commits)} added`
10 10 * :removed:`${len(removed_commits)} removed`
11 11
12 12 %if not changed_files:
13 13 No file changes found
14 14 %else:
15 15 Changed files:
16 16 %for file_name in added_files:
17 17 * `A ${file_name} <#${'a_' + h.FID('', file_name)}>`_
18 18 %endfor
19 19 %for file_name in modified_files:
20 20 * `M ${file_name} <#${'a_' + h.FID('', file_name)}>`_
21 21 %endfor
22 22 %for file_name in removed_files:
23 23 * R ${file_name}
24 24 %endfor
25 25 %endif
26 26
27 27 .. |under_review| replace:: *"${under_review_label}"* No newline at end of file
@@ -1,179 +1,179 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2016 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import pytest
22 22
23 23 from rhodecode.lib.markup_renderer import MarkupRenderer, RstTemplateRenderer
24 24
25 25
26 26 @pytest.mark.parametrize(
27 27 "filename, expected_renderer",
28 28 [
29 29 ('readme.md', 'markdown'),
30 30 ('readme.Md', 'markdown'),
31 31 ('readme.MdoWn', 'markdown'),
32 32 ('readme.rst', 'rst'),
33 33 ('readme.Rst', 'rst'),
34 34 ('readme.rest', 'rst'),
35 35 ('readme.rest', 'rst'),
36 36 ('readme', 'rst'),
37 37 ('README', 'rst'),
38 38
39 39 ('markdown.xml', 'plain'),
40 40 ('rest.xml', 'plain'),
41 41 ('readme.xml', 'plain'),
42 42
43 43 ('readme.mdx', 'plain'),
44 44 ('readme.rstx', 'plain'),
45 45 ('readmex', 'plain'),
46 46 ])
47 47 def test_detect_renderer(filename, expected_renderer):
48 48 detected_renderer = MarkupRenderer()._detect_renderer(
49 49 '', filename=filename).__name__
50 50 assert expected_renderer == detected_renderer
51 51
52 52
53 53 def test_markdown_xss_link():
54 54 xss_md = "[link](javascript:alert('XSS: pwned!'))"
55 55 rendered_html = MarkupRenderer.markdown(xss_md)
56 56 assert 'href="javascript:alert(\'XSS: pwned!\')"' not in rendered_html
57 57
58 58
59 59 def test_markdown_xss_inline_html():
60 60 xss_md = '\n'.join([
61 61 '> <a name="n"',
62 62 '> href="javascript:alert(\'XSS: pwned!\')">link</a>'])
63 63 rendered_html = MarkupRenderer.markdown(xss_md)
64 64 assert 'href="javascript:alert(\'XSS: pwned!\')">' not in rendered_html
65 65
66 66
67 67 def test_markdown_inline_html():
68 68 xss_md = '\n'.join(['> <a name="n"',
69 69 '> href="https://rhodecode.com">link</a>'])
70 70 rendered_html = MarkupRenderer.markdown(xss_md)
71 71 assert '[HTML_REMOVED]link[HTML_REMOVED]' in rendered_html
72 72
73 73
74 74 def test_rst_xss_link():
75 75 xss_rst = "`Link<javascript:alert('XSS: pwned!')>`_"
76 76 rendered_html = MarkupRenderer.rst(xss_rst)
77 77 assert "href=javascript:alert('XSS: pwned!')" not in rendered_html
78 78
79 79
80 80 @pytest.mark.xfail(reason='Bug in docutils. Waiting answer from the author')
81 81 def test_rst_xss_inline_html():
82 82 xss_rst = '<a href="javascript:alert(\'XSS: pwned!\')">link</a>'
83 83 rendered_html = MarkupRenderer.rst(xss_rst)
84 84 assert 'href="javascript:alert(' not in rendered_html
85 85
86 86
87 87 def test_rst_xss_raw_directive():
88 88 xss_rst = '\n'.join([
89 89 '.. raw:: html',
90 90 '',
91 91 ' <a href="javascript:alert(\'XSS: pwned!\')">link</a>'])
92 92 rendered_html = MarkupRenderer.rst(xss_rst)
93 93 assert 'href="javascript:alert(' not in rendered_html
94 94
95 95
96 96 def test_render_rst_template_without_files():
97 97 expected = u'''\
98 Auto status change to |under_review|
98 Pull request updated. Auto status change to |under_review|
99 99
100 100 .. role:: added
101 101 .. role:: removed
102 102 .. parsed-literal::
103 103
104 104 Changed commits:
105 105 * :added:`2 added`
106 106 * :removed:`3 removed`
107 107
108 108 No file changes found
109 109
110 110 .. |under_review| replace:: *"NEW STATUS"*'''
111 111
112 112 params = {
113 113 'under_review_label': 'NEW STATUS',
114 114 'added_commits': ['a', 'b'],
115 115 'removed_commits': ['a', 'b', 'c'],
116 116 'changed_files': [],
117 117 'added_files': [],
118 118 'modified_files': [],
119 119 'removed_files': [],
120 120 }
121 121 renderer = RstTemplateRenderer()
122 122 rendered = renderer.render('pull_request_update.mako', **params)
123 123 assert expected == rendered
124 124
125 125
126 126 def test_render_rst_template_with_files():
127 127 expected = u'''\
128 Auto status change to |under_review|
128 Pull request updated. Auto status change to |under_review|
129 129
130 130 .. role:: added
131 131 .. role:: removed
132 132 .. parsed-literal::
133 133
134 134 Changed commits:
135 135 * :added:`1 added`
136 136 * :removed:`3 removed`
137 137
138 138 Changed files:
139 139 * `A /path/a.py <#a_c--68ed34923b68>`_
140 140 * `A /path/b.js <#a_c--64f90608b607>`_
141 141 * `M /path/d.js <#a_c--85842bf30c6e>`_
142 142 * `M /path/Δ™.py <#a_c--d713adf009cd>`_
143 143 * R /path/ΕΊ.py
144 144
145 145 .. |under_review| replace:: *"NEW STATUS"*'''
146 146
147 147 added = ['/path/a.py', '/path/b.js']
148 148 modified = ['/path/d.js', u'/path/Δ™.py']
149 149 removed = [u'/path/ΕΊ.py']
150 150
151 151 params = {
152 152 'under_review_label': 'NEW STATUS',
153 153 'added_commits': ['a'],
154 154 'removed_commits': ['a', 'b', 'c'],
155 155 'changed_files': added + modified + removed,
156 156 'added_files': added,
157 157 'modified_files': modified,
158 158 'removed_files': removed,
159 159 }
160 160 renderer = RstTemplateRenderer()
161 161 rendered = renderer.render('pull_request_update.mako', **params)
162 162
163 163 assert expected == rendered
164 164
165 165
166 166 def test_render_rst_auto_status_template():
167 167 expected = u'''\
168 168 Auto status change to |new_status|
169 169
170 170 .. |new_status| replace:: *"NEW STATUS"*'''
171 171
172 172 params = {
173 173 'new_status_label': 'NEW STATUS',
174 174 'pull_request': None,
175 175 'commit_id': None,
176 176 }
177 177 renderer = RstTemplateRenderer()
178 178 rendered = renderer.render('auto_status_change.mako', **params)
179 179 assert expected == rendered
@@ -1,846 +1,846 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2016 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import mock
22 22 import pytest
23 23 import textwrap
24 24
25 25 import rhodecode
26 26 from rhodecode.lib.utils2 import safe_unicode
27 27 from rhodecode.lib.vcs.backends import get_backend
28 28 from rhodecode.lib.vcs.backends.base import (
29 29 MergeResponse, MergeFailureReason, Reference)
30 30 from rhodecode.lib.vcs.exceptions import RepositoryError
31 31 from rhodecode.lib.vcs.nodes import FileNode
32 32 from rhodecode.model.comment import ChangesetCommentsModel
33 33 from rhodecode.model.db import PullRequest, Session
34 34 from rhodecode.model.pull_request import PullRequestModel
35 35 from rhodecode.model.user import UserModel
36 36 from rhodecode.tests import TEST_USER_ADMIN_LOGIN
37 37
38 38
39 39 pytestmark = [
40 40 pytest.mark.backends("git", "hg"),
41 41 ]
42 42
43 43
44 44 class TestPullRequestModel:
45 45
46 46 @pytest.fixture
47 47 def pull_request(self, request, backend, pr_util):
48 48 """
49 49 A pull request combined with multiples patches.
50 50 """
51 51 BackendClass = get_backend(backend.alias)
52 52 self.merge_patcher = mock.patch.object(BackendClass, 'merge')
53 53 self.workspace_remove_patcher = mock.patch.object(
54 54 BackendClass, 'cleanup_merge_workspace')
55 55
56 56 self.workspace_remove_mock = self.workspace_remove_patcher.start()
57 57 self.merge_mock = self.merge_patcher.start()
58 58 self.comment_patcher = mock.patch(
59 59 'rhodecode.model.changeset_status.ChangesetStatusModel.set_status')
60 60 self.comment_patcher.start()
61 61 self.notification_patcher = mock.patch(
62 62 'rhodecode.model.notification.NotificationModel.create')
63 63 self.notification_patcher.start()
64 64 self.helper_patcher = mock.patch(
65 65 'rhodecode.lib.helpers.url')
66 66 self.helper_patcher.start()
67 67
68 68 self.hook_patcher = mock.patch.object(PullRequestModel,
69 69 '_trigger_pull_request_hook')
70 70 self.hook_mock = self.hook_patcher.start()
71 71
72 72 self.invalidation_patcher = mock.patch(
73 73 'rhodecode.model.pull_request.ScmModel.mark_for_invalidation')
74 74 self.invalidation_mock = self.invalidation_patcher.start()
75 75
76 76 self.pull_request = pr_util.create_pull_request(
77 77 mergeable=True, name_suffix=u'Δ…Δ‡')
78 78 self.source_commit = self.pull_request.source_ref_parts.commit_id
79 79 self.target_commit = self.pull_request.target_ref_parts.commit_id
80 80 self.workspace_id = 'pr-%s' % self.pull_request.pull_request_id
81 81
82 82 @request.addfinalizer
83 83 def cleanup_pull_request():
84 84 calls = [mock.call(
85 85 self.pull_request, self.pull_request.author, 'create')]
86 86 self.hook_mock.assert_has_calls(calls)
87 87
88 88 self.workspace_remove_patcher.stop()
89 89 self.merge_patcher.stop()
90 90 self.comment_patcher.stop()
91 91 self.notification_patcher.stop()
92 92 self.helper_patcher.stop()
93 93 self.hook_patcher.stop()
94 94 self.invalidation_patcher.stop()
95 95
96 96 return self.pull_request
97 97
98 98 def test_get_all(self, pull_request):
99 99 prs = PullRequestModel().get_all(pull_request.target_repo)
100 100 assert isinstance(prs, list)
101 101 assert len(prs) == 1
102 102
103 103 def test_count_all(self, pull_request):
104 104 pr_count = PullRequestModel().count_all(pull_request.target_repo)
105 105 assert pr_count == 1
106 106
107 107 def test_get_awaiting_review(self, pull_request):
108 108 prs = PullRequestModel().get_awaiting_review(pull_request.target_repo)
109 109 assert isinstance(prs, list)
110 110 assert len(prs) == 1
111 111
112 112 def test_count_awaiting_review(self, pull_request):
113 113 pr_count = PullRequestModel().count_awaiting_review(
114 114 pull_request.target_repo)
115 115 assert pr_count == 1
116 116
117 117 def test_get_awaiting_my_review(self, pull_request):
118 118 PullRequestModel().update_reviewers(
119 119 pull_request, [(pull_request.author, ['author'])])
120 120 prs = PullRequestModel().get_awaiting_my_review(
121 121 pull_request.target_repo, user_id=pull_request.author.user_id)
122 122 assert isinstance(prs, list)
123 123 assert len(prs) == 1
124 124
125 125 def test_count_awaiting_my_review(self, pull_request):
126 126 PullRequestModel().update_reviewers(
127 127 pull_request, [(pull_request.author, ['author'])])
128 128 pr_count = PullRequestModel().count_awaiting_my_review(
129 129 pull_request.target_repo, user_id=pull_request.author.user_id)
130 130 assert pr_count == 1
131 131
132 132 def test_delete_calls_cleanup_merge(self, pull_request):
133 133 PullRequestModel().delete(pull_request)
134 134
135 135 self.workspace_remove_mock.assert_called_once_with(
136 136 self.workspace_id)
137 137
138 138 def test_close_calls_cleanup_and_hook(self, pull_request):
139 139 PullRequestModel().close_pull_request(
140 140 pull_request, pull_request.author)
141 141
142 142 self.workspace_remove_mock.assert_called_once_with(
143 143 self.workspace_id)
144 144 self.hook_mock.assert_called_with(
145 145 self.pull_request, self.pull_request.author, 'close')
146 146
147 147 def test_merge_status(self, pull_request):
148 148 self.merge_mock.return_value = MergeResponse(
149 149 True, False, None, MergeFailureReason.NONE)
150 150
151 151 assert pull_request._last_merge_source_rev is None
152 152 assert pull_request._last_merge_target_rev is None
153 153 assert pull_request._last_merge_status is None
154 154
155 155 status, msg = PullRequestModel().merge_status(pull_request)
156 156 assert status is True
157 157 assert msg.eval() == 'This pull request can be automatically merged.'
158 158 self.merge_mock.assert_called_once_with(
159 159 pull_request.target_ref_parts,
160 160 pull_request.source_repo.scm_instance(),
161 161 pull_request.source_ref_parts, self.workspace_id, dry_run=True,
162 162 use_rebase=False)
163 163
164 164 assert pull_request._last_merge_source_rev == self.source_commit
165 165 assert pull_request._last_merge_target_rev == self.target_commit
166 166 assert pull_request._last_merge_status is MergeFailureReason.NONE
167 167
168 168 self.merge_mock.reset_mock()
169 169 status, msg = PullRequestModel().merge_status(pull_request)
170 170 assert status is True
171 171 assert msg.eval() == 'This pull request can be automatically merged.'
172 172 assert self.merge_mock.called is False
173 173
174 174 def test_merge_status_known_failure(self, pull_request):
175 175 self.merge_mock.return_value = MergeResponse(
176 176 False, False, None, MergeFailureReason.MERGE_FAILED)
177 177
178 178 assert pull_request._last_merge_source_rev is None
179 179 assert pull_request._last_merge_target_rev is None
180 180 assert pull_request._last_merge_status is None
181 181
182 182 status, msg = PullRequestModel().merge_status(pull_request)
183 183 assert status is False
184 184 assert (
185 185 msg.eval() ==
186 186 'This pull request cannot be merged because of conflicts.')
187 187 self.merge_mock.assert_called_once_with(
188 188 pull_request.target_ref_parts,
189 189 pull_request.source_repo.scm_instance(),
190 190 pull_request.source_ref_parts, self.workspace_id, dry_run=True,
191 191 use_rebase=False)
192 192
193 193 assert pull_request._last_merge_source_rev == self.source_commit
194 194 assert pull_request._last_merge_target_rev == self.target_commit
195 195 assert (
196 196 pull_request._last_merge_status is MergeFailureReason.MERGE_FAILED)
197 197
198 198 self.merge_mock.reset_mock()
199 199 status, msg = PullRequestModel().merge_status(pull_request)
200 200 assert status is False
201 201 assert (
202 202 msg.eval() ==
203 203 'This pull request cannot be merged because of conflicts.')
204 204 assert self.merge_mock.called is False
205 205
206 206 def test_merge_status_unknown_failure(self, pull_request):
207 207 self.merge_mock.return_value = MergeResponse(
208 208 False, False, None, MergeFailureReason.UNKNOWN)
209 209
210 210 assert pull_request._last_merge_source_rev is None
211 211 assert pull_request._last_merge_target_rev is None
212 212 assert pull_request._last_merge_status is None
213 213
214 214 status, msg = PullRequestModel().merge_status(pull_request)
215 215 assert status is False
216 216 assert msg.eval() == (
217 217 'This pull request cannot be merged because of an unhandled'
218 218 ' exception.')
219 219 self.merge_mock.assert_called_once_with(
220 220 pull_request.target_ref_parts,
221 221 pull_request.source_repo.scm_instance(),
222 222 pull_request.source_ref_parts, self.workspace_id, dry_run=True,
223 223 use_rebase=False)
224 224
225 225 assert pull_request._last_merge_source_rev is None
226 226 assert pull_request._last_merge_target_rev is None
227 227 assert pull_request._last_merge_status is None
228 228
229 229 self.merge_mock.reset_mock()
230 230 status, msg = PullRequestModel().merge_status(pull_request)
231 231 assert status is False
232 232 assert msg.eval() == (
233 233 'This pull request cannot be merged because of an unhandled'
234 234 ' exception.')
235 235 assert self.merge_mock.called is True
236 236
237 237 def test_merge_status_when_target_is_locked(self, pull_request):
238 238 pull_request.target_repo.locked = [1, u'12345.50', 'lock_web']
239 239 status, msg = PullRequestModel().merge_status(pull_request)
240 240 assert status is False
241 241 assert msg.eval() == (
242 242 'This pull request cannot be merged because the target repository'
243 243 ' is locked.')
244 244
245 245 def test_merge_status_requirements_check_target(self, pull_request):
246 246
247 247 def has_largefiles(self, repo):
248 248 return repo == pull_request.source_repo
249 249
250 250 patcher = mock.patch.object(
251 251 PullRequestModel, '_has_largefiles', has_largefiles)
252 252 with patcher:
253 253 status, msg = PullRequestModel().merge_status(pull_request)
254 254
255 255 assert status is False
256 256 assert msg == 'Target repository large files support is disabled.'
257 257
258 258 def test_merge_status_requirements_check_source(self, pull_request):
259 259
260 260 def has_largefiles(self, repo):
261 261 return repo == pull_request.target_repo
262 262
263 263 patcher = mock.patch.object(
264 264 PullRequestModel, '_has_largefiles', has_largefiles)
265 265 with patcher:
266 266 status, msg = PullRequestModel().merge_status(pull_request)
267 267
268 268 assert status is False
269 269 assert msg == 'Source repository large files support is disabled.'
270 270
271 271 def test_merge(self, pull_request, merge_extras):
272 272 user = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
273 273 merge_ref = Reference(
274 274 'type', 'name', '6126b7bfcc82ad2d3deaee22af926b082ce54cc6')
275 275 self.merge_mock.return_value = MergeResponse(
276 276 True, True, merge_ref, MergeFailureReason.NONE)
277 277
278 278 merge_extras['repository'] = pull_request.target_repo.repo_name
279 279 PullRequestModel().merge(
280 280 pull_request, pull_request.author, extras=merge_extras)
281 281
282 282 message = (
283 283 u'Merge pull request #{pr_id} from {source_repo} {source_ref_name}'
284 284 u'\n\n {pr_title}'.format(
285 285 pr_id=pull_request.pull_request_id,
286 286 source_repo=safe_unicode(
287 287 pull_request.source_repo.scm_instance().name),
288 288 source_ref_name=pull_request.source_ref_parts.name,
289 289 pr_title=safe_unicode(pull_request.title)
290 290 )
291 291 )
292 292 self.merge_mock.assert_called_once_with(
293 293 pull_request.target_ref_parts,
294 294 pull_request.source_repo.scm_instance(),
295 295 pull_request.source_ref_parts, self.workspace_id,
296 296 user_name=user.username, user_email=user.email, message=message,
297 297 use_rebase=False
298 298 )
299 299 self.invalidation_mock.assert_called_once_with(
300 300 pull_request.target_repo.repo_name)
301 301
302 302 self.hook_mock.assert_called_with(
303 303 self.pull_request, self.pull_request.author, 'merge')
304 304
305 305 pull_request = PullRequest.get(pull_request.pull_request_id)
306 306 assert (
307 307 pull_request.merge_rev ==
308 308 '6126b7bfcc82ad2d3deaee22af926b082ce54cc6')
309 309
310 310 def test_merge_failed(self, pull_request, merge_extras):
311 311 user = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
312 312 merge_ref = Reference(
313 313 'type', 'name', '6126b7bfcc82ad2d3deaee22af926b082ce54cc6')
314 314 self.merge_mock.return_value = MergeResponse(
315 315 False, False, merge_ref, MergeFailureReason.MERGE_FAILED)
316 316
317 317 merge_extras['repository'] = pull_request.target_repo.repo_name
318 318 PullRequestModel().merge(
319 319 pull_request, pull_request.author, extras=merge_extras)
320 320
321 321 message = (
322 322 u'Merge pull request #{pr_id} from {source_repo} {source_ref_name}'
323 323 u'\n\n {pr_title}'.format(
324 324 pr_id=pull_request.pull_request_id,
325 325 source_repo=safe_unicode(
326 326 pull_request.source_repo.scm_instance().name),
327 327 source_ref_name=pull_request.source_ref_parts.name,
328 328 pr_title=safe_unicode(pull_request.title)
329 329 )
330 330 )
331 331 self.merge_mock.assert_called_once_with(
332 332 pull_request.target_ref_parts,
333 333 pull_request.source_repo.scm_instance(),
334 334 pull_request.source_ref_parts, self.workspace_id,
335 335 user_name=user.username, user_email=user.email, message=message,
336 336 use_rebase=False
337 337 )
338 338
339 339 pull_request = PullRequest.get(pull_request.pull_request_id)
340 340 assert self.invalidation_mock.called is False
341 341 assert pull_request.merge_rev is None
342 342
343 343 def test_get_commit_ids(self, pull_request):
344 344 # The PR has been not merget yet, so expect an exception
345 345 with pytest.raises(ValueError):
346 346 PullRequestModel()._get_commit_ids(pull_request)
347 347
348 348 # Merge revision is in the revisions list
349 349 pull_request.merge_rev = pull_request.revisions[0]
350 350 commit_ids = PullRequestModel()._get_commit_ids(pull_request)
351 351 assert commit_ids == pull_request.revisions
352 352
353 353 # Merge revision is not in the revisions list
354 354 pull_request.merge_rev = 'f000' * 10
355 355 commit_ids = PullRequestModel()._get_commit_ids(pull_request)
356 356 assert commit_ids == pull_request.revisions + [pull_request.merge_rev]
357 357
358 358 def test_get_diff_from_pr_version(self, pull_request):
359 359 diff = PullRequestModel()._get_diff_from_pr_or_version(
360 360 pull_request, context=6)
361 361 assert 'file_1' in diff.raw
362 362
363 363 def test_generate_title_returns_unicode(self):
364 364 title = PullRequestModel().generate_pullrequest_title(
365 365 source='source-dummy',
366 366 source_ref='source-ref-dummy',
367 367 target='target-dummy',
368 368 )
369 369 assert type(title) == unicode
370 370
371 371
372 372 class TestIntegrationMerge(object):
373 373 @pytest.mark.parametrize('extra_config', (
374 374 {'vcs.hooks.protocol': 'http', 'vcs.hooks.direct_calls': False},
375 375 {'vcs.hooks.protocol': 'Pyro4', 'vcs.hooks.direct_calls': False},
376 376 ))
377 377 def test_merge_triggers_push_hooks(
378 378 self, pr_util, user_admin, capture_rcextensions, merge_extras,
379 379 extra_config):
380 380 pull_request = pr_util.create_pull_request(
381 381 approved=True, mergeable=True)
382 382 # TODO: johbo: Needed for sqlite, try to find an automatic way for it
383 383 merge_extras['repository'] = pull_request.target_repo.repo_name
384 384 Session().commit()
385 385
386 386 with mock.patch.dict(rhodecode.CONFIG, extra_config, clear=False):
387 387 merge_state = PullRequestModel().merge(
388 388 pull_request, user_admin, extras=merge_extras)
389 389
390 390 assert merge_state.executed
391 391 assert 'pre_push' in capture_rcextensions
392 392 assert 'post_push' in capture_rcextensions
393 393
394 394 def test_merge_can_be_rejected_by_pre_push_hook(
395 395 self, pr_util, user_admin, capture_rcextensions, merge_extras):
396 396 pull_request = pr_util.create_pull_request(
397 397 approved=True, mergeable=True)
398 398 # TODO: johbo: Needed for sqlite, try to find an automatic way for it
399 399 merge_extras['repository'] = pull_request.target_repo.repo_name
400 400 Session().commit()
401 401
402 402 with mock.patch('rhodecode.EXTENSIONS.PRE_PUSH_HOOK') as pre_pull:
403 403 pre_pull.side_effect = RepositoryError("Disallow push!")
404 404 merge_status = PullRequestModel().merge(
405 405 pull_request, user_admin, extras=merge_extras)
406 406
407 407 assert not merge_status.executed
408 408 assert 'pre_push' not in capture_rcextensions
409 409 assert 'post_push' not in capture_rcextensions
410 410
411 411 def test_merge_fails_if_target_is_locked(
412 412 self, pr_util, user_regular, merge_extras):
413 413 pull_request = pr_util.create_pull_request(
414 414 approved=True, mergeable=True)
415 415 locked_by = [user_regular.user_id + 1, 12345.50, 'lock_web']
416 416 pull_request.target_repo.locked = locked_by
417 417 # TODO: johbo: Check if this can work based on the database, currently
418 418 # all data is pre-computed, that's why just updating the DB is not
419 419 # enough.
420 420 merge_extras['locked_by'] = locked_by
421 421 merge_extras['repository'] = pull_request.target_repo.repo_name
422 422 # TODO: johbo: Needed for sqlite, try to find an automatic way for it
423 423 Session().commit()
424 424 merge_status = PullRequestModel().merge(
425 425 pull_request, user_regular, extras=merge_extras)
426 426 assert not merge_status.executed
427 427
428 428
429 429 @pytest.mark.parametrize('use_outdated, inlines_count, outdated_count', [
430 430 (False, 1, 0),
431 431 (True, 0, 1),
432 432 ])
433 433 def test_outdated_comments(
434 434 pr_util, use_outdated, inlines_count, outdated_count):
435 435 pull_request = pr_util.create_pull_request()
436 436 pr_util.create_inline_comment(file_path='not_in_updated_diff')
437 437
438 438 with outdated_comments_patcher(use_outdated) as outdated_comment_mock:
439 439 pr_util.add_one_commit()
440 440 assert_inline_comments(
441 441 pull_request, visible=inlines_count, outdated=outdated_count)
442 442 outdated_comment_mock.assert_called_with(pull_request)
443 443
444 444
445 445 @pytest.fixture
446 446 def merge_extras(user_regular):
447 447 """
448 448 Context for the vcs operation when running a merge.
449 449 """
450 450 extras = {
451 451 'ip': '127.0.0.1',
452 452 'username': user_regular.username,
453 453 'action': 'push',
454 454 'repository': 'fake_target_repo_name',
455 455 'scm': 'git',
456 456 'config': 'fake_config_ini_path',
457 457 'make_lock': None,
458 458 'locked_by': [None, None, None],
459 459 'server_url': 'http://test.example.com:5000',
460 460 'hooks': ['push', 'pull'],
461 461 'is_shadow_repo': False,
462 462 }
463 463 return extras
464 464
465 465
466 466 class TestUpdateCommentHandling(object):
467 467
468 468 @pytest.fixture(autouse=True, scope='class')
469 469 def enable_outdated_comments(self, request, pylonsapp):
470 470 config_patch = mock.patch.dict(
471 471 'rhodecode.CONFIG', {'rhodecode_use_outdated_comments': True})
472 472 config_patch.start()
473 473
474 474 @request.addfinalizer
475 475 def cleanup():
476 476 config_patch.stop()
477 477
478 478 def test_comment_stays_unflagged_on_unchanged_diff(self, pr_util):
479 479 commits = [
480 480 {'message': 'a'},
481 481 {'message': 'b', 'added': [FileNode('file_b', 'test_content\n')]},
482 482 {'message': 'c', 'added': [FileNode('file_c', 'test_content\n')]},
483 483 ]
484 484 pull_request = pr_util.create_pull_request(
485 485 commits=commits, target_head='a', source_head='b', revisions=['b'])
486 486 pr_util.create_inline_comment(file_path='file_b')
487 487 pr_util.add_one_commit(head='c')
488 488
489 489 assert_inline_comments(pull_request, visible=1, outdated=0)
490 490
491 491 def test_comment_stays_unflagged_on_change_above(self, pr_util):
492 492 original_content = ''.join(
493 493 ['line {}\n'.format(x) for x in range(1, 11)])
494 494 updated_content = 'new_line_at_top\n' + original_content
495 495 commits = [
496 496 {'message': 'a'},
497 497 {'message': 'b', 'added': [FileNode('file_b', original_content)]},
498 498 {'message': 'c', 'changed': [FileNode('file_b', updated_content)]},
499 499 ]
500 500 pull_request = pr_util.create_pull_request(
501 501 commits=commits, target_head='a', source_head='b', revisions=['b'])
502 502
503 503 with outdated_comments_patcher():
504 504 comment = pr_util.create_inline_comment(
505 505 line_no=u'n8', file_path='file_b')
506 506 pr_util.add_one_commit(head='c')
507 507
508 508 assert_inline_comments(pull_request, visible=1, outdated=0)
509 509 assert comment.line_no == u'n9'
510 510
511 511 def test_comment_stays_unflagged_on_change_below(self, pr_util):
512 512 original_content = ''.join(['line {}\n'.format(x) for x in range(10)])
513 513 updated_content = original_content + 'new_line_at_end\n'
514 514 commits = [
515 515 {'message': 'a'},
516 516 {'message': 'b', 'added': [FileNode('file_b', original_content)]},
517 517 {'message': 'c', 'changed': [FileNode('file_b', updated_content)]},
518 518 ]
519 519 pull_request = pr_util.create_pull_request(
520 520 commits=commits, target_head='a', source_head='b', revisions=['b'])
521 521 pr_util.create_inline_comment(file_path='file_b')
522 522 pr_util.add_one_commit(head='c')
523 523
524 524 assert_inline_comments(pull_request, visible=1, outdated=0)
525 525
526 526 @pytest.mark.parametrize('line_no', ['n4', 'o4', 'n10', 'o9'])
527 527 def test_comment_flagged_on_change_around_context(self, pr_util, line_no):
528 528 base_lines = ['line {}\n'.format(x) for x in range(1, 13)]
529 529 change_lines = list(base_lines)
530 530 change_lines.insert(6, 'line 6a added\n')
531 531
532 532 # Changes on the last line of sight
533 533 update_lines = list(change_lines)
534 534 update_lines[0] = 'line 1 changed\n'
535 535 update_lines[-1] = 'line 12 changed\n'
536 536
537 537 def file_b(lines):
538 538 return FileNode('file_b', ''.join(lines))
539 539
540 540 commits = [
541 541 {'message': 'a', 'added': [file_b(base_lines)]},
542 542 {'message': 'b', 'changed': [file_b(change_lines)]},
543 543 {'message': 'c', 'changed': [file_b(update_lines)]},
544 544 ]
545 545
546 546 pull_request = pr_util.create_pull_request(
547 547 commits=commits, target_head='a', source_head='b', revisions=['b'])
548 548 pr_util.create_inline_comment(line_no=line_no, file_path='file_b')
549 549
550 550 with outdated_comments_patcher():
551 551 pr_util.add_one_commit(head='c')
552 552 assert_inline_comments(pull_request, visible=0, outdated=1)
553 553
554 554 @pytest.mark.parametrize("change, content", [
555 555 ('changed', 'changed\n'),
556 556 ('removed', ''),
557 557 ], ids=['changed', 'removed'])
558 558 def test_comment_flagged_on_change(self, pr_util, change, content):
559 559 commits = [
560 560 {'message': 'a'},
561 561 {'message': 'b', 'added': [FileNode('file_b', 'test_content\n')]},
562 562 {'message': 'c', change: [FileNode('file_b', content)]},
563 563 ]
564 564 pull_request = pr_util.create_pull_request(
565 565 commits=commits, target_head='a', source_head='b', revisions=['b'])
566 566 pr_util.create_inline_comment(file_path='file_b')
567 567
568 568 with outdated_comments_patcher():
569 569 pr_util.add_one_commit(head='c')
570 570 assert_inline_comments(pull_request, visible=0, outdated=1)
571 571
572 572
573 573 class TestUpdateChangedFiles(object):
574 574
575 575 def test_no_changes_on_unchanged_diff(self, pr_util):
576 576 commits = [
577 577 {'message': 'a'},
578 578 {'message': 'b',
579 579 'added': [FileNode('file_b', 'test_content b\n')]},
580 580 {'message': 'c',
581 581 'added': [FileNode('file_c', 'test_content c\n')]},
582 582 ]
583 583 # open a PR from a to b, adding file_b
584 584 pull_request = pr_util.create_pull_request(
585 585 commits=commits, target_head='a', source_head='b', revisions=['b'],
586 586 name_suffix='per-file-review')
587 587
588 588 # modify PR adding new file file_c
589 589 pr_util.add_one_commit(head='c')
590 590
591 591 assert_pr_file_changes(
592 592 pull_request,
593 593 added=['file_c'],
594 594 modified=[],
595 595 removed=[])
596 596
597 597 def test_modify_and_undo_modification_diff(self, pr_util):
598 598 commits = [
599 599 {'message': 'a'},
600 600 {'message': 'b',
601 601 'added': [FileNode('file_b', 'test_content b\n')]},
602 602 {'message': 'c',
603 603 'changed': [FileNode('file_b', 'test_content b modified\n')]},
604 604 {'message': 'd',
605 605 'changed': [FileNode('file_b', 'test_content b\n')]},
606 606 ]
607 607 # open a PR from a to b, adding file_b
608 608 pull_request = pr_util.create_pull_request(
609 609 commits=commits, target_head='a', source_head='b', revisions=['b'],
610 610 name_suffix='per-file-review')
611 611
612 612 # modify PR modifying file file_b
613 613 pr_util.add_one_commit(head='c')
614 614
615 615 assert_pr_file_changes(
616 616 pull_request,
617 617 added=[],
618 618 modified=['file_b'],
619 619 removed=[])
620 620
621 621 # move the head again to d, which rollbacks change,
622 622 # meaning we should indicate no changes
623 623 pr_util.add_one_commit(head='d')
624 624
625 625 assert_pr_file_changes(
626 626 pull_request,
627 627 added=[],
628 628 modified=[],
629 629 removed=[])
630 630
631 631 def test_updated_all_files_in_pr(self, pr_util):
632 632 commits = [
633 633 {'message': 'a'},
634 634 {'message': 'b', 'added': [
635 635 FileNode('file_a', 'test_content a\n'),
636 636 FileNode('file_b', 'test_content b\n'),
637 637 FileNode('file_c', 'test_content c\n')]},
638 638 {'message': 'c', 'changed': [
639 639 FileNode('file_a', 'test_content a changed\n'),
640 640 FileNode('file_b', 'test_content b changed\n'),
641 641 FileNode('file_c', 'test_content c changed\n')]},
642 642 ]
643 643 # open a PR from a to b, changing 3 files
644 644 pull_request = pr_util.create_pull_request(
645 645 commits=commits, target_head='a', source_head='b', revisions=['b'],
646 646 name_suffix='per-file-review')
647 647
648 648 pr_util.add_one_commit(head='c')
649 649
650 650 assert_pr_file_changes(
651 651 pull_request,
652 652 added=[],
653 653 modified=['file_a', 'file_b', 'file_c'],
654 654 removed=[])
655 655
656 656 def test_updated_and_removed_all_files_in_pr(self, pr_util):
657 657 commits = [
658 658 {'message': 'a'},
659 659 {'message': 'b', 'added': [
660 660 FileNode('file_a', 'test_content a\n'),
661 661 FileNode('file_b', 'test_content b\n'),
662 662 FileNode('file_c', 'test_content c\n')]},
663 663 {'message': 'c', 'removed': [
664 664 FileNode('file_a', 'test_content a changed\n'),
665 665 FileNode('file_b', 'test_content b changed\n'),
666 666 FileNode('file_c', 'test_content c changed\n')]},
667 667 ]
668 668 # open a PR from a to b, removing 3 files
669 669 pull_request = pr_util.create_pull_request(
670 670 commits=commits, target_head='a', source_head='b', revisions=['b'],
671 671 name_suffix='per-file-review')
672 672
673 673 pr_util.add_one_commit(head='c')
674 674
675 675 assert_pr_file_changes(
676 676 pull_request,
677 677 added=[],
678 678 modified=[],
679 679 removed=['file_a', 'file_b', 'file_c'])
680 680
681 681
682 682 def test_update_writes_snapshot_into_pull_request_version(pr_util):
683 683 model = PullRequestModel()
684 684 pull_request = pr_util.create_pull_request()
685 685 pr_util.update_source_repository()
686 686
687 687 model.update_commits(pull_request)
688 688
689 689 # Expect that it has a version entry now
690 690 assert len(model.get_versions(pull_request)) == 1
691 691
692 692
693 693 def test_update_skips_new_version_if_unchanged(pr_util):
694 694 pull_request = pr_util.create_pull_request()
695 695 model = PullRequestModel()
696 696 model.update_commits(pull_request)
697 697
698 698 # Expect that it still has no versions
699 699 assert len(model.get_versions(pull_request)) == 0
700 700
701 701
702 702 def test_update_assigns_comments_to_the_new_version(pr_util):
703 703 model = PullRequestModel()
704 704 pull_request = pr_util.create_pull_request()
705 705 comment = pr_util.create_comment()
706 706 pr_util.update_source_repository()
707 707
708 708 model.update_commits(pull_request)
709 709
710 710 # Expect that the comment is linked to the pr version now
711 711 assert comment.pull_request_version == model.get_versions(pull_request)[0]
712 712
713 713
714 714 def test_update_adds_a_comment_to_the_pull_request_about_the_change(pr_util):
715 715 model = PullRequestModel()
716 716 pull_request = pr_util.create_pull_request()
717 717 pr_util.update_source_repository()
718 718 pr_util.update_source_repository()
719 719
720 720 model.update_commits(pull_request)
721 721
722 722 # Expect to find a new comment about the change
723 723 expected_message = textwrap.dedent(
724 724 """\
725 Auto status change to |under_review|
725 Pull request updated. Auto status change to |under_review|
726 726
727 727 .. role:: added
728 728 .. role:: removed
729 729 .. parsed-literal::
730 730
731 731 Changed commits:
732 732 * :added:`1 added`
733 733 * :removed:`0 removed`
734 734
735 735 Changed files:
736 736 * `A file_2 <#a_c--92ed3b5f07b4>`_
737 737
738 738 .. |under_review| replace:: *"Under Review"*"""
739 739 )
740 740 pull_request_comments = sorted(
741 741 pull_request.comments, key=lambda c: c.modified_at)
742 742 update_comment = pull_request_comments[-1]
743 743 assert update_comment.text == expected_message
744 744
745 745
746 746 def test_create_version_from_snapshot_updates_attributes(pr_util):
747 747 pull_request = pr_util.create_pull_request()
748 748
749 749 # Avoiding default values
750 750 pull_request.status = PullRequest.STATUS_CLOSED
751 751 pull_request._last_merge_source_rev = "0" * 40
752 752 pull_request._last_merge_target_rev = "1" * 40
753 753 pull_request._last_merge_status = 1
754 754 pull_request.merge_rev = "2" * 40
755 755
756 756 # Remember automatic values
757 757 created_on = pull_request.created_on
758 758 updated_on = pull_request.updated_on
759 759
760 760 # Create a new version of the pull request
761 761 version = PullRequestModel()._create_version_from_snapshot(pull_request)
762 762
763 763 # Check attributes
764 764 assert version.title == pr_util.create_parameters['title']
765 765 assert version.description == pr_util.create_parameters['description']
766 766 assert version.status == PullRequest.STATUS_CLOSED
767 767
768 768 # versions get updated created_on
769 769 assert version.created_on != created_on
770 770
771 771 assert version.updated_on == updated_on
772 772 assert version.user_id == pull_request.user_id
773 773 assert version.revisions == pr_util.create_parameters['revisions']
774 774 assert version.source_repo == pr_util.source_repository
775 775 assert version.source_ref == pr_util.create_parameters['source_ref']
776 776 assert version.target_repo == pr_util.target_repository
777 777 assert version.target_ref == pr_util.create_parameters['target_ref']
778 778 assert version._last_merge_source_rev == pull_request._last_merge_source_rev
779 779 assert version._last_merge_target_rev == pull_request._last_merge_target_rev
780 780 assert version._last_merge_status == pull_request._last_merge_status
781 781 assert version.merge_rev == pull_request.merge_rev
782 782 assert version.pull_request == pull_request
783 783
784 784
785 785 def test_link_comments_to_version_only_updates_unlinked_comments(pr_util):
786 786 version1 = pr_util.create_version_of_pull_request()
787 787 comment_linked = pr_util.create_comment(linked_to=version1)
788 788 comment_unlinked = pr_util.create_comment()
789 789 version2 = pr_util.create_version_of_pull_request()
790 790
791 791 PullRequestModel()._link_comments_to_version(version2)
792 792
793 793 # Expect that only the new comment is linked to version2
794 794 assert (
795 795 comment_unlinked.pull_request_version_id ==
796 796 version2.pull_request_version_id)
797 797 assert (
798 798 comment_linked.pull_request_version_id ==
799 799 version1.pull_request_version_id)
800 800 assert (
801 801 comment_unlinked.pull_request_version_id !=
802 802 comment_linked.pull_request_version_id)
803 803
804 804
805 805 def test_calculate_commits():
806 806 change = PullRequestModel()._calculate_commit_id_changes(
807 807 set([1, 2, 3]), set([1, 3, 4, 5]))
808 808 assert (set([4, 5]), set([1, 3]), set([2])) == (
809 809 change.added, change.common, change.removed)
810 810
811 811
812 812 def assert_inline_comments(pull_request, visible=None, outdated=None):
813 813 if visible is not None:
814 814 inline_comments = ChangesetCommentsModel().get_inline_comments(
815 815 pull_request.target_repo.repo_id, pull_request=pull_request)
816 816 inline_cnt = ChangesetCommentsModel().get_inline_comments_count(
817 817 inline_comments)
818 818 assert inline_cnt == visible
819 819 if outdated is not None:
820 820 outdated_comments = ChangesetCommentsModel().get_outdated_comments(
821 821 pull_request.target_repo.repo_id, pull_request)
822 822 assert len(outdated_comments) == outdated
823 823
824 824
825 825 def assert_pr_file_changes(
826 826 pull_request, added=None, modified=None, removed=None):
827 827 pr_versions = PullRequestModel().get_versions(pull_request)
828 828 # always use first version, ie original PR to calculate changes
829 829 pull_request_version = pr_versions[0]
830 830 old_diff_data, new_diff_data = PullRequestModel()._generate_update_diffs(
831 831 pull_request, pull_request_version)
832 832 file_changes = PullRequestModel()._calculate_file_changes(
833 833 old_diff_data, new_diff_data)
834 834
835 835 assert added == file_changes.added, \
836 836 'expected added:%s vs value:%s' % (added, file_changes.added)
837 837 assert modified == file_changes.modified, \
838 838 'expected modified:%s vs value:%s' % (modified, file_changes.modified)
839 839 assert removed == file_changes.removed, \
840 840 'expected removed:%s vs value:%s' % (removed, file_changes.removed)
841 841
842 842
843 843 def outdated_comments_patcher(use_outdated=True):
844 844 return mock.patch.object(
845 845 ChangesetCommentsModel, 'use_outdated_comments',
846 846 return_value=use_outdated)
General Comments 0
You need to be logged in to leave comments. Login now