##// END OF EJS Templates
events: ported pylons part to pyramid....
events: ported pylons part to pyramid. - fix lack of request context in VCS type events we now use a dummy request but it's sufficient for routes generation - cleanup and re-organized some code - removed all pylons stuff from the events code

File last commit:

r1956:a7a935de default
r1959:b0de121b default
Show More
pullrequests.py
1018 lines | 40.9 KiB | text/x-python | PythonLexer
project: added all source files and assets
r1 # -*- coding: utf-8 -*-
license: updated copyright year to 2017
r1271 # Copyright (C) 2012-2017 RhodeCode GmbH
project: added all source files and assets
r1 #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License, version 3
# (only), as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# This program is dual-licensed. If you wish to learn more about the
# RhodeCode Enterprise Edition, including its added features, Support services,
# and proprietary license terms, please see https://rhodecode.com/licenses/
"""
pull requests controller for rhodecode for initializing pull requests
"""
dan
reviewers: store reviewer reasons to database, fixes #4238
r873 import peppercorn
project: added all source files and assets
r1 import formencode
import logging
pull-requests: updated versioning support....
r1268 import collections
pull-requests: expose version browsing of pull requests....
r1255
project: added all source files and assets
r1 from webob.exc import HTTPNotFound, HTTPForbidden, HTTPBadRequest
from pylons import request, tmpl_context as c, url
from pylons.controllers.util import redirect
from pylons.i18n.translation import _
pull request: send live notification when PR update happens
r814 from pyramid.threadlocal import get_current_registry
security: use new safe escaped user attributes across the application....
r1815 from pyramid.httpexceptions import HTTPFound
project: added all source files and assets
r1 from sqlalchemy.sql import func
from sqlalchemy.sql.expression import or_
dan
events: add an event for pull request comments with review status
r443 from rhodecode import events
dan
diffs: add new diffs to pull request page
r1159 from rhodecode.lib import auth, diffs, helpers as h, codeblocks
project: added all source files and assets
r1 from rhodecode.lib.ext_json import json
from rhodecode.lib.base import (
BaseRepoController, render, vcs_operation_context)
from rhodecode.lib.auth import (
LoginRequired, HasRepoPermissionAnyDecorator, NotAnonymous,
HasAcceptedRepoType, XHRRequired)
pull request: send live notification when PR update happens
r814 from rhodecode.lib.channelstream import channelstream_request
project: added all source files and assets
r1 from rhodecode.lib.utils import jsonify
pull-requests: added version browsing for pull requests....
r1192 from rhodecode.lib.utils2 import (
pull-requests: expose version browsing of pull requests....
r1255 safe_int, safe_str, str2bool, safe_unicode)
from rhodecode.lib.vcs.backends.base import (
EmptyCommit, UpdateFailureReason, EmptyRepository)
project: added all source files and assets
r1 from rhodecode.lib.vcs.exceptions import (
dan
diffs: add new diffs to pull request page
r1159 EmptyRepositoryError, CommitDoesNotExistError, RepositoryRequirementError,
NodeDoesNotExistError)
pull-requests: added version browsing for pull requests....
r1192
project: added all source files and assets
r1 from rhodecode.model.changeset_status import ChangesetStatusModel
comments: renamed ChangesetCommentsModel to CommentsModel to reflect what it actually does....
r1323 from rhodecode.model.comment import CommentsModel
pull-requests: added version browsing for pull requests....
r1192 from rhodecode.model.db import (PullRequest, ChangesetStatus, ChangesetComment,
Repository, PullRequestVersion)
project: added all source files and assets
r1 from rhodecode.model.forms import PullRequestForm
from rhodecode.model.meta import Session
pull-requests: unified merge checks....
r1335 from rhodecode.model.pull_request import PullRequestModel, MergeCheck
project: added all source files and assets
r1
log = logging.getLogger(__name__)
class PullrequestsController(BaseRepoController):
pr-versioning: implemented versioning for pull requests....
r1368
project: added all source files and assets
r1 def __before__(self):
super(PullrequestsController, self).__before__()
pull-requests: add explicit CLOSE pr action instead of closed status from selector....
r1445 c.REVIEW_STATUS_APPROVED = ChangesetStatus.STATUS_APPROVED
c.REVIEW_STATUS_REJECTED = ChangesetStatus.STATUS_REJECTED
project: added all source files and assets
r1
@LoginRequired()
@NotAnonymous()
@HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
'repository.admin')
@HasAcceptedRepoType('git', 'hg')
def index(self):
source_repo = c.rhodecode_db_repo
try:
source_repo.scm_instance().get_commit()
except EmptyRepositoryError:
h.flash(h.literal(_('There are no commits yet')),
category='warning')
repo-summary: re-implemented summary view as pyramid....
r1785 redirect(h.route_path('repo_summary', repo_name=source_repo.repo_name))
project: added all source files and assets
r1
commit_id = request.GET.get('commit')
branch_ref = request.GET.get('branch')
bookmark_ref = request.GET.get('bookmark')
try:
source_repo_data = PullRequestModel().generate_repo_data(
source_repo, commit_id=commit_id,
branch=branch_ref, bookmark=bookmark_ref)
except CommitDoesNotExistError as e:
log.exception(e)
h.flash(_('Commit does not exist'), 'error')
redirect(url('pullrequest_home', repo_name=source_repo.repo_name))
default_target_repo = source_repo
pull-requests: fix problem with empty instances on creating PR from origin repo
r921
if source_repo.parent:
parent_vcs_obj = source_repo.parent.scm_instance()
if parent_vcs_obj and not parent_vcs_obj.is_empty():
# change default if we have a parent repo
default_target_repo = source_repo.parent
project: added all source files and assets
r1
target_repo_data = PullRequestModel().generate_repo_data(
default_target_repo)
selected_source_ref = source_repo_data['refs']['selected_ref']
title_source_ref = selected_source_ref.split(':', 2)[1]
c.default_title = PullRequestModel().generate_pullrequest_title(
source=source_repo.repo_name,
source_ref=title_source_ref,
target=default_target_repo.repo_name
)
c.default_repo_data = {
'source_repo_name': source_repo.repo_name,
'source_refs_json': json.dumps(source_repo_data),
'target_repo_name': default_target_repo.repo_name,
'target_refs_json': json.dumps(target_repo_data),
}
c.default_source_ref = selected_source_ref
templating: use .mako as extensions for template files.
r1282 return render('/pullrequests/pullrequest.mako')
project: added all source files and assets
r1
@LoginRequired()
@NotAnonymous()
@XHRRequired()
@HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
'repository.admin')
@jsonify
def get_repo_refs(self, repo_name, target_repo_name):
repo = Repository.get_by_repo_name(target_repo_name)
if not repo:
raise HTTPNotFound
return PullRequestModel().generate_repo_data(repo)
@LoginRequired()
@NotAnonymous()
@XHRRequired()
@HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
'repository.admin')
@jsonify
def get_repo_destinations(self, repo_name):
repo = Repository.get_by_repo_name(repo_name)
if not repo:
raise HTTPNotFound
filter_query = request.GET.get('query')
query = Repository.query() \
.order_by(func.length(Repository.repo_name)) \
.filter(or_(
Repository.repo_name == repo.repo_name,
Repository.fork_id == repo.repo_id))
if filter_query:
ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
query = query.filter(
Repository.repo_name.ilike(ilike_expression))
add_parent = False
if repo.parent:
if filter_query in repo.parent.repo_name:
pull-requests: fix problem with empty instances on creating PR from origin repo
r921 parent_vcs_obj = repo.parent.scm_instance()
if parent_vcs_obj and not parent_vcs_obj.is_empty():
project: added all source files and assets
r1 add_parent = True
limit = 20 - 1 if add_parent else 20
all_repos = query.limit(limit).all()
if add_parent:
all_repos += [repo.parent]
repos = []
for obj in self.scm_model.get_repos(all_repos):
repos.append({
'id': obj['name'],
'text': obj['name'],
'type': 'repo',
'obj': obj['dbrepo']
})
data = {
'more': False,
'results': [{
'text': _('Repositories'),
'children': repos
}] if repos else []
}
return data
@LoginRequired()
@NotAnonymous()
@HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
'repository.admin')
@HasAcceptedRepoType('git', 'hg')
@auth.CSRFRequired()
def create(self, repo_name):
repo = Repository.get_by_repo_name(repo_name)
if not repo:
raise HTTPNotFound
dan
reviewers: store reviewer reasons to database, fixes #4238
r873 controls = peppercorn.parse(request.POST.items())
project: added all source files and assets
r1 try:
dan
reviewers: store reviewer reasons to database, fixes #4238
r873 _form = PullRequestForm(repo.repo_id)().to_python(controls)
project: added all source files and assets
r1 except formencode.Invalid as errors:
if errors.error_dict.get('revisions'):
msg = 'Revisions: %s' % errors.error_dict['revisions']
elif errors.error_dict.get('pullrequest_title'):
msg = _('Pull request requires a title with min. 3 chars')
else:
msg = _('Error creating pull request: {}').format(errors)
log.exception(msg)
h.flash(msg, 'error')
# would rather just go back to form ...
return redirect(url('pullrequest_home', repo_name=repo_name))
source_repo = _form['source_repo']
source_ref = _form['source_ref']
target_repo = _form['target_repo']
target_ref = _form['target_ref']
commit_ids = _form['revisions'][::-1]
# find the ancestor for this pr
source_db_repo = Repository.get_by_repo_name(_form['source_repo'])
target_db_repo = Repository.get_by_repo_name(_form['target_repo'])
source_scm = source_db_repo.scm_instance()
target_scm = target_db_repo.scm_instance()
source_commit = source_scm.get_commit(source_ref.split(':')[-1])
target_commit = target_scm.get_commit(target_ref.split(':')[-1])
ancestor = source_scm.get_common_ancestor(
source_commit.raw_id, target_commit.raw_id, target_scm)
target_ref_type, target_ref_name, __ = _form['target_ref'].split(':')
target_ref = ':'.join((target_ref_type, target_ref_name, ancestor))
pullrequest_title = _form['pullrequest_title']
title_source_ref = source_ref.split(':', 2)[1]
if not pullrequest_title:
pullrequest_title = PullRequestModel().generate_pullrequest_title(
source=source_repo,
source_ref=title_source_ref,
target=target_repo
)
description = _form['pullrequest_desc']
pull-request: extended default reviewers functionality....
r1769
get_default_reviewers_data, validate_default_reviewers = \
PullRequestModel().get_reviewer_functions()
# recalculate reviewers logic, to make sure we can validate this
reviewer_rules = get_default_reviewers_data(
review-rules: extend code to support the forbid commit authors.
r1787 c.rhodecode_user.get_instance(), source_db_repo,
source_commit, target_db_repo, target_commit)
pull-request: extended default reviewers functionality....
r1769
dan
reviewers: added validation and default review rules via API calls....
r1795 given_reviewers = _form['review_members']
reviewers = validate_default_reviewers(given_reviewers, reviewer_rules)
pull-request: extended default reviewers functionality....
r1769
project: added all source files and assets
r1 try:
pull_request = PullRequestModel().create(
c.rhodecode_user.user_id, source_repo, source_ref, target_repo,
target_ref, commit_ids, reviewers, pullrequest_title,
pull-request: extended default reviewers functionality....
r1769 description, reviewer_rules
project: added all source files and assets
r1 )
Session().commit()
h.flash(_('Successfully opened new pull request'),
category='success')
except Exception as e:
pull-request: extended default reviewers functionality....
r1769 msg = _('Error occurred during creation of this pull request.')
project: added all source files and assets
r1 log.exception(msg)
h.flash(msg, category='error')
return redirect(url('pullrequest_home', repo_name=repo_name))
pull-requests: prepare the migration of pull request to pyramid....
r1813 raise HTTPFound(
h.route_path('pullrequest_show', repo_name=target_repo,
pull_request_id=pull_request.pull_request_id))
project: added all source files and assets
r1
@LoginRequired()
@NotAnonymous()
@HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
'repository.admin')
@auth.CSRFRequired()
@jsonify
def update(self, repo_name, pull_request_id):
pull_request_id = safe_int(pull_request_id)
pull_request = PullRequest.get_or_404(pull_request_id)
# only owner or admin can update it
allowed_to_update = PullRequestModel().check_user_update(
pull_request, c.rhodecode_user)
if allowed_to_update:
dan
reviewers: store reviewer reasons to database, fixes #4238
r873 controls = peppercorn.parse(request.POST.items())
if 'review_members' in controls:
self._update_reviewers(
pull-request: extended default reviewers functionality....
r1769 pull_request_id, controls['review_members'],
pull_request.reviewer_data)
project: added all source files and assets
r1 elif str2bool(request.POST.get('update_commits', 'false')):
self._update_commits(pull_request)
elif str2bool(request.POST.get('edit_pull_request', 'false')):
self._edit_pull_request(pull_request)
else:
raise HTTPBadRequest()
return True
raise HTTPForbidden()
def _edit_pull_request(self, pull_request):
try:
PullRequestModel().edit(
pull_request, request.POST.get('title'),
audit-logs: implemented pull request and comment events.
r1807 request.POST.get('description'), c.rhodecode_user)
project: added all source files and assets
r1 except ValueError:
msg = _(u'Cannot update closed pull requests.')
h.flash(msg, category='error')
return
else:
Session().commit()
msg = _(u'Pull request title & description updated.')
h.flash(msg, category='success')
return
def _update_commits(self, pull_request):
Martin Bornhold
pr: Use new update response object from pr model. #3950
r1076 resp = PullRequestModel().update_commits(pull_request)
Martin Bornhold
pr: Rename update response flag `success` -> `executed`...
r1083 if resp.executed:
pull-requests: change the update commits logic to handle target changes better....
r1601
if resp.target_changed and resp.source_changed:
changed = 'target and source repositories'
elif resp.target_changed and not resp.source_changed:
changed = 'target repository'
elif not resp.target_changed and resp.source_changed:
changed = 'source repository'
else:
changed = 'nothing'
Martin Bornhold
pr: Use new update response object from pr model. #3950
r1076 msg = _(
u'Pull request updated to "{source_commit_id}" with '
pull-requests: change the update commits logic to handle target changes better....
r1601 u'{count_added} added, {count_removed} removed commits. '
u'Source of changes: {change_source}')
Martin Bornhold
pr: Use new update response object from pr model. #3950
r1076 msg = msg.format(
source_commit_id=pull_request.source_ref_parts.commit_id,
count_added=len(resp.changes.added),
pull-requests: change the update commits logic to handle target changes better....
r1601 count_removed=len(resp.changes.removed),
change_source=changed)
Martin Bornhold
pr: Use new update response object from pr model. #3950
r1076 h.flash(msg, category='success')
registry = get_current_registry()
rhodecode_plugins = getattr(registry, 'rhodecode_plugins', {})
channelstream_config = rhodecode_plugins.get('channelstream', {})
if channelstream_config.get('enabled'):
message = msg + (
' - <a onclick="window.location.reload()">'
'<strong>{}</strong></a>'.format(_('Reload page')))
channel = '/repo${}$/pr/{}'.format(
pull_request.target_repo.repo_name,
pull_request.pull_request_id
)
payload = {
'type': 'message',
'user': 'system',
'exclude_users': [request.user.username],
'channel': channel,
'message': {
'message': message,
'level': 'success',
'topic': '/notifications'
}
}
channelstream_request(
channelstream_config, [payload], '/message',
raise_exc=False)
else:
Martin Bornhold
pr: Refactor PR update error message handling.
r1082 msg = PullRequestModel.UPDATE_STATUS_MESSAGES[resp.reason]
warning_reasons = [
UpdateFailureReason.NO_CHANGE,
pull-request: fixed typo in wrong ref type error, and added which...
r1687 UpdateFailureReason.WRONG_REF_TYPE,
Martin Bornhold
pr: Refactor PR update error message handling.
r1082 ]
category = 'warning' if resp.reason in warning_reasons else 'error'
h.flash(msg, category=category)
project: added all source files and assets
r1
@auth.CSRFRequired()
@LoginRequired()
@NotAnonymous()
@HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
'repository.admin')
def merge(self, repo_name, pull_request_id):
"""
POST /{repo_name}/pull-request/{pull_request_id}
Merge will perform a server-side merge of the specified
pull request, if the pull request is approved and mergeable.
pull-requests: unified merge checks....
r1335 After successful merging, the pull request is automatically
project: added all source files and assets
r1 closed, with a relevant comment.
"""
pull_request_id = safe_int(pull_request_id)
pull_request = PullRequest.get_or_404(pull_request_id)
user = c.rhodecode_user
pull-requests: unified merge checks....
r1335 check = MergeCheck.validate(pull_request, user)
merge_possible = not check.failed
for err_type, error_msg in check.errors:
h.flash(error_msg, category=err_type)
if merge_possible:
project: added all source files and assets
r1 log.debug("Pre-conditions checked, trying to merge.")
extras = vcs_operation_context(
request.environ, repo_name=pull_request.target_repo.repo_name,
username=user.username, action='push',
scm=pull_request.target_repo.repo_type)
self._merge_pull_request(pull_request, user, extras)
pull-requests: prepare the migration of pull request to pyramid....
r1813 raise HTTPFound(
h.route_path('pullrequest_show',
repo_name=pull_request.target_repo.repo_name,
pull_request_id=pull_request.pull_request_id))
project: added all source files and assets
r1
def _merge_pull_request(self, pull_request, user, extras):
merge_resp = PullRequestModel().merge(
pull_request, user, extras=extras)
if merge_resp.executed:
log.debug("The merge was successful, closing the pull request.")
PullRequestModel().close_pull_request(
pull_request.pull_request_id, user)
Session().commit()
pull-requests: add a success flash when PR was merged
r166 msg = _('Pull request was successfully merged and closed.')
h.flash(msg, category='success')
project: added all source files and assets
r1 else:
log.debug(
"The merge was not successful. Merge response: %s",
merge_resp)
msg = PullRequestModel().merge_status_message(
merge_resp.failure_reason)
h.flash(msg, category='error')
pull-request: extended default reviewers functionality....
r1769 def _update_reviewers(self, pull_request_id, review_members, reviewer_rules):
get_default_reviewers_data, validate_default_reviewers = \
PullRequestModel().get_reviewer_functions()
try:
reviewers = validate_default_reviewers(review_members, reviewer_rules)
except ValueError as e:
dan
reviewers: added validation and default review rules via API calls....
r1795 log.error('Reviewers Validation: {}'.format(e))
pull-request: extended default reviewers functionality....
r1769 h.flash(e, category='error')
return
audit-logs: implemented pull request and comment events.
r1807 PullRequestModel().update_reviewers(
pull_request_id, reviewers, c.rhodecode_user)
pull-request: extended default reviewers functionality....
r1769 h.flash(_('Pull request reviewers updated.'), category='success')
project: added all source files and assets
r1 Session().commit()
@LoginRequired()
@NotAnonymous()
@HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
'repository.admin')
@auth.CSRFRequired()
@jsonify
def delete(self, repo_name, pull_request_id):
pull_request_id = safe_int(pull_request_id)
pull_request = PullRequest.get_or_404(pull_request_id)
pull-requests: use consistent check who is allowed to delete a pull request.
r1607
pr_closed = pull_request.is_closed()
allowed_to_delete = PullRequestModel().check_user_delete(
pull_request, c.rhodecode_user) and not pr_closed
project: added all source files and assets
r1 # only owner can delete it !
pull-requests: use consistent check who is allowed to delete a pull request.
r1607 if allowed_to_delete:
audit-logs: implemented pull request and comment events.
r1807 PullRequestModel().delete(pull_request, c.rhodecode_user)
project: added all source files and assets
r1 Session().commit()
h.flash(_('Successfully deleted pull request'),
category='success')
return redirect(url('my_account_pullrequests'))
pull-requests: use consistent check who is allowed to delete a pull request.
r1607
h.flash(_('Your are not allowed to delete this pull request'),
category='error')
project: added all source files and assets
r1 raise HTTPForbidden()
pull-requests: added version browsing for pull requests....
r1192 def _get_pr_version(self, pull_request_id, version=None):
pull_request_id = safe_int(pull_request_id)
at_version = None
pull-requests: expose version browsing of pull requests....
r1255
if version and version == 'latest':
pull_request_ver = PullRequest.get(pull_request_id)
pull_request_obj = pull_request_ver
_org_pull_request_obj = pull_request_obj
at_version = 'latest'
elif version:
pull-requests: added version browsing for pull requests....
r1192 pull_request_ver = PullRequestVersion.get_or_404(version)
pull_request_obj = pull_request_ver
_org_pull_request_obj = pull_request_ver.pull_request
at_version = pull_request_ver.pull_request_version_id
else:
pull-request: extended default reviewers functionality....
r1769 _org_pull_request_obj = pull_request_obj = PullRequest.get_or_404(
pull_request_id)
pull-requests: added version browsing for pull requests....
r1192
pull-requests: expose version browsing of pull requests....
r1255 pull_request_display_obj = PullRequest.get_pr_display_object(
pull_request_obj, _org_pull_request_obj)
pr-versioning: implemented versioning for pull requests....
r1368
pull-requests: added version browsing for pull requests....
r1192 return _org_pull_request_obj, pull_request_obj, \
diffs: fixed other file source when using pull requests. It must use...
r1194 pull_request_display_obj, at_version
pull-requests: added version browsing for pull requests....
r1192
pr: small refactor of code.
r1378 def _get_diffset(
self, source_repo, source_ref_id, target_ref_id, target_commit,
source_commit, diff_limit, file_limit, display_inline_comments):
vcs_diff = PullRequestModel().get_diff(
source_repo, source_ref_id, target_ref_id)
diff_processor = diffs.DiffProcessor(
vcs_diff, format='newdiff', diff_limit=diff_limit,
file_limit=file_limit, show_full_diff=c.fulldiff)
_parsed = diff_processor.prepare()
def _node_getter(commit):
def get_node(fname):
try:
return commit.get_node(fname)
except NodeDoesNotExistError:
return None
return get_node
diffset = codeblocks.DiffSet(
repo_name=c.repo_name,
source_repo_name=c.source_repo.repo_name,
source_node_getter=_node_getter(target_commit),
target_node_getter=_node_getter(source_commit),
comments=display_inline_comments
)
diffset = diffset.render_patchset(
_parsed, target_commit.raw_id, source_commit.raw_id)
return diffset
project: added all source files and assets
r1 @LoginRequired()
@HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
'repository.admin')
def show(self, repo_name, pull_request_id):
pull_request_id = safe_int(pull_request_id)
diffs: fixed other file source when using pull requests. It must use...
r1194 version = request.GET.get('version')
pr-versioning: implemented versioning for pull requests....
r1368 from_version = request.GET.get('from_version') or version
pull-request: introduced new merge-checks....
r1334 merge_checks = request.GET.get('merge_checks')
pr-versioning: implemented versioning for pull requests....
r1368 c.fulldiff = str2bool(request.GET.get('fulldiff'))
diffs: fixed other file source when using pull requests. It must use...
r1194 (pull_request_latest,
pull_request_at_ver,
pull_request_display_obj,
pr-versioning: implemented versioning for pull requests....
r1368 at_version) = self._get_pr_version(
pull_request_id, version=version)
pull-requests: forbid browsing versions on closed pull request.
r1446 pr_closed = pull_request_latest.is_closed()
if pr_closed and (version or from_version):
# not allow to browse versions
return redirect(h.url('pullrequest_show', repo_name=repo_name,
pull_request_id=pull_request_id))
pr-versioning: implemented versioning for pull requests....
r1368 versions = pull_request_display_obj.versions()
c.at_version = at_version
c.at_version_num = (at_version
if at_version and at_version != 'latest'
else None)
c.at_version_pos = ChangesetComment.get_index_from_version(
c.at_version_num, versions)
project: added all source files and assets
r1
pr-versioning: implemented versioning for pull requests....
r1368 (prev_pull_request_latest,
prev_pull_request_at_ver,
prev_pull_request_display_obj,
prev_at_version) = self._get_pr_version(
pull_request_id, version=from_version)
c.from_version = prev_at_version
c.from_version_num = (prev_at_version
if prev_at_version and prev_at_version != 'latest'
else None)
c.from_version_pos = ChangesetComment.get_index_from_version(
c.from_version_num, versions)
# define if we're in COMPARE mode or VIEW at version mode
compare = at_version != prev_at_version
templateContext: allow for flexible way to communicate additional info for client code from controllers
r394
project: added all source files and assets
r1 # pull_requests repo_name we opened it against
# ie. target_repo must match
diffs: fixed other file source when using pull requests. It must use...
r1194 if repo_name != pull_request_at_ver.target_repo.repo_name:
project: added all source files and assets
r1 raise HTTPNotFound
Martin Bornhold
pr: Display link to shadow repository on pull request page.
r896 c.shadow_clone_url = PullRequestModel().get_shadow_clone_url(
diffs: fixed other file source when using pull requests. It must use...
r1194 pull_request_at_ver)
pull-requests: added version browsing for pull requests....
r1192
pull-request: introduced new merge-checks....
r1334 c.pull_request = pull_request_display_obj
c.pull_request_latest = pull_request_latest
pr-versioning: implemented versioning for pull requests....
r1368 if compare or (at_version and not at_version == 'latest'):
pull-requests: added version browsing for pull requests....
r1192 c.allowed_to_change_status = False
diffs: fixed other file source when using pull requests. It must use...
r1194 c.allowed_to_update = False
c.allowed_to_merge = False
c.allowed_to_delete = False
c.allowed_to_comment = False
pull-requests: add explicit CLOSE pr action instead of closed status from selector....
r1445 c.allowed_to_close = False
pull-requests: added version browsing for pull requests....
r1192 else:
pull-request: extended default reviewers functionality....
r1769 can_change_status = PullRequestModel().check_user_change_status(
pull_request_at_ver, c.rhodecode_user)
c.allowed_to_change_status = can_change_status and not pr_closed
pull-requests: add explicit CLOSE pr action instead of closed status from selector....
r1445
pull-requests: added version browsing for pull requests....
r1192 c.allowed_to_update = PullRequestModel().check_user_update(
diffs: fixed other file source when using pull requests. It must use...
r1194 pull_request_latest, c.rhodecode_user) and not pr_closed
pull-requests: added version browsing for pull requests....
r1192 c.allowed_to_merge = PullRequestModel().check_user_merge(
diffs: fixed other file source when using pull requests. It must use...
r1194 pull_request_latest, c.rhodecode_user) and not pr_closed
pull-requests: added version browsing for pull requests....
r1192 c.allowed_to_delete = PullRequestModel().check_user_delete(
diffs: fixed other file source when using pull requests. It must use...
r1194 pull_request_latest, c.rhodecode_user) and not pr_closed
c.allowed_to_comment = not pr_closed
pull-reqests: workflow, change who can close a PR, it's only super-admin...
r1686 c.allowed_to_close = c.allowed_to_merge and not pr_closed
project: added all source files and assets
r1
pull-request: extended default reviewers functionality....
r1769 c.forbid_adding_reviewers = False
c.forbid_author_to_review = False
review-rules: extend code to support the forbid commit authors.
r1787 c.forbid_commit_author_to_review = False
pull-request: extended default reviewers functionality....
r1769
if pull_request_latest.reviewer_data and \
'rules' in pull_request_latest.reviewer_data:
rules = pull_request_latest.reviewer_data['rules'] or {}
try:
review-rules: extend code to support the forbid commit authors.
r1787 c.forbid_adding_reviewers = rules.get(
'forbid_adding_reviewers')
c.forbid_author_to_review = rules.get(
'forbid_author_to_review')
c.forbid_commit_author_to_review = rules.get(
'forbid_commit_author_to_review')
pull-request: extended default reviewers functionality....
r1769 except Exception:
pass
pr-versioning: implemented versioning for pull requests....
r1368 # check merge capabilities
_merge_check = MergeCheck.validate(
pull_request_latest, user=c.rhodecode_user)
c.pr_merge_errors = _merge_check.error_details
c.pr_merge_possible = not _merge_check.failed
c.pr_merge_message = _merge_check.merge_msg
project: added all source files and assets
r1
pull-requests: add explicit CLOSE pr action instead of closed status from selector....
r1445 c.pull_request_review_status = _merge_check.review_status
pr-versioning: implemented versioning for pull requests....
r1368 if merge_checks:
return render('/pullrequests/pullrequest_merge_checks.mako')
comments_model = CommentsModel()
# reviewers and statuses
diffs: fixed other file source when using pull requests. It must use...
r1194 c.pull_request_reviewers = pull_request_at_ver.reviewers_statuses()
pr-versioning: implemented versioning for pull requests....
r1368 allowed_reviewers = [x[0].user_id for x in c.pull_request_reviewers]
project: added all source files and assets
r1
comments: use unified aggregation of comments counters....
r1332 # GENERAL COMMENTS with versions #
pr-versioning: implemented versioning for pull requests....
r1368 q = comments_model._all_general_comments_of_pull_request(pull_request_latest)
q = q.order_by(ChangesetComment.comment_id.asc())
pull-requests: comments don't order by versions since we anyway order by unique number.
r1706 general_comments = q
inline-comments: added helper to properly count inline comments.
r1206
comments: use unified aggregation of comments counters....
r1332 # pick comments we want to render at current version
pr-versioning: implemented versioning for pull requests....
r1368 c.comment_versions = comments_model.aggregate_comments(
general_comments, versions, c.at_version_num)
comments: use unified aggregation of comments counters....
r1332 c.comments = c.comment_versions[c.at_version_num]['until']
# INLINE COMMENTS with versions #
pr-versioning: implemented versioning for pull requests....
r1368 q = comments_model._all_inline_comments_of_pull_request(pull_request_latest)
q = q.order_by(ChangesetComment.comment_id.asc())
pull-requests: comments don't order by versions since we anyway order by unique number.
r1706 inline_comments = q
pr-versioning: implemented versioning for pull requests....
r1368 c.inline_versions = comments_model.aggregate_comments(
inline_comments, versions, c.at_version_num, inline=True)
# inject latest version
latest_ver = PullRequest.get_pr_display_object(
pull_request_latest, pull_request_latest)
c.versions = versions + [latest_ver]
dan
pullrequest: remove old diff code from pullrequest controller
r1183
comments: use unified aggregation of comments counters....
r1332 # if we use version, then do not show later comments
# than current version
pr-versioning: implemented versioning for pull requests....
r1368 display_inline_comments = collections.defaultdict(
lambda: collections.defaultdict(list))
comments: use unified aggregation of comments counters....
r1332 for co in inline_comments:
if c.at_version_num:
# pick comments that are at least UPTO given version, so we
# don't render comments for higher version
should_render = co.pull_request_version_id and \
co.pull_request_version_id <= c.at_version_num
else:
# showing all, for 'latest'
should_render = True
pull-requests: added version browsing for pull requests....
r1192
comments: use unified aggregation of comments counters....
r1332 if should_render:
pull-request: introduced new merge-checks....
r1334 display_inline_comments[co.f_path][co.line_no].append(co)
pr-versioning: implemented versioning for pull requests....
r1368 # load diff data into template context, if we use compare mode then
# diff is calculated based on changes between versions of PR
source_repo = pull_request_at_ver.source_repo
source_ref_id = pull_request_at_ver.source_ref_parts.commit_id
target_repo = pull_request_at_ver.target_repo
target_ref_id = pull_request_at_ver.target_ref_parts.commit_id
if compare:
# in compare switch the diff base to latest commit from prev version
target_ref_id = prev_pull_request_display_obj.revisions[0]
# despite opening commits for bookmarks/branches/tags, we always
# convert this to rev to prevent changes after bookmark or branch change
c.source_ref_type = 'rev'
c.source_ref = source_ref_id
c.target_ref_type = 'rev'
c.target_ref = target_ref_id
c.source_repo = source_repo
c.target_repo = target_repo
# diff_limit is the old behavior, will cut off the whole diff
# if the limit is applied otherwise will just hide the
# big files from the front-end
diff_limit = self.cut_off_limit_diff
file_limit = self.cut_off_limit_file
c.commit_ranges = []
source_commit = EmptyCommit()
target_commit = EmptyCommit()
c.missing_requirements = False
pull-requests: show common ancestor inside pull-request view....
r1594 source_scm = source_repo.scm_instance()
target_scm = target_repo.scm_instance()
pr-versioning: implemented versioning for pull requests....
r1368 # try first shadow repo, fallback to regular repo
try:
commits_source_repo = pull_request_latest.get_shadow_repo()
except Exception:
log.debug('Failed to get shadow repo', exc_info=True)
pull-requests: show common ancestor inside pull-request view....
r1594 commits_source_repo = source_scm
pr-versioning: implemented versioning for pull requests....
r1368
c.commits_source_repo = commits_source_repo
commit_cache = {}
try:
pre_load = ["author", "branch", "date", "message"]
show_revs = pull_request_at_ver.revisions
for rev in show_revs:
comm = commits_source_repo.get_commit(
commit_id=rev, pre_load=pre_load)
c.commit_ranges.append(comm)
commit_cache[comm.raw_id] = comm
pull-request: introduced new merge-checks....
r1334
pull-request: extended default reviewers functionality....
r1769 # Order here matters, we first need to get target, and then
# the source
pr-versioning: implemented versioning for pull requests....
r1368 target_commit = commits_source_repo.get_commit(
commit_id=safe_str(target_ref_id))
pull-request: extended default reviewers functionality....
r1769
pr-versioning: implemented versioning for pull requests....
r1368 source_commit = commits_source_repo.get_commit(
commit_id=safe_str(source_ref_id))
pull-request: extended default reviewers functionality....
r1769
pr-versioning: implemented versioning for pull requests....
r1368 except CommitDoesNotExistError:
pull-request: extended default reviewers functionality....
r1769 log.warning(
'Failed to get commit from `{}` repo'.format(
commits_source_repo), exc_info=True)
pr-versioning: implemented versioning for pull requests....
r1368 except RepositoryRequirementError:
log.warning(
'Failed to get all required data from repo', exc_info=True)
c.missing_requirements = True
pull-requests: show common ancestor inside pull-request view....
r1594 c.ancestor = None # set it to None, to hide it from PR view
try:
ancestor_id = source_scm.get_common_ancestor(
source_commit.raw_id, target_commit.raw_id, target_scm)
c.ancestor_commit = source_scm.get_commit(ancestor_id)
except Exception:
c.ancestor_commit = None
pr-versioning: implemented versioning for pull requests....
r1368 c.statuses = source_repo.statuses(
[x.raw_id for x in c.commit_ranges])
# auto collapse if we have more than limit
collapse_limit = diffs.DiffProcessor._collapse_commits_over
c.collapse_all_commits = len(c.commit_ranges) > collapse_limit
c.compare_mode = compare
c.missing_commits = False
if (c.missing_requirements or isinstance(source_commit, EmptyCommit)
or source_commit == target_commit):
c.missing_commits = True
else:
pr: small refactor of code.
r1378 c.diffset = self._get_diffset(
commits_source_repo, source_ref_id, target_ref_id,
target_commit, source_commit,
diff_limit, file_limit, display_inline_comments)
pr-versioning: implemented versioning for pull requests....
r1368
pr: small refactor of code.
r1378 c.limited_diff = c.diffset.limited_diff
pr-versioning: implemented versioning for pull requests....
r1368
# calculate removed files that are bound to comments
comment_deleted_files = [
fname for fname in display_inline_comments
if fname not in c.diffset.file_stats]
c.deleted_files_comments = collections.defaultdict(dict)
for fname, per_line_comments in display_inline_comments.items():
if fname in comment_deleted_files:
c.deleted_files_comments[fname]['stats'] = 0
c.deleted_files_comments[fname]['comments'] = list()
for lno, comments in per_line_comments.items():
c.deleted_files_comments[fname]['comments'].extend(
comments)
project: added all source files and assets
r1
dan
diffs: add new diffs to pull request page
r1159 # this is a hack to properly display links, when creating PR, the
# compare view and others uses different notation, and
templating: use .mako as extensions for template files.
r1282 # compare_commits.mako renders links based on the target_repo.
dan
diffs: add new diffs to pull request page
r1159 # We need to swap that here to generate it properly on the html side
c.target_repo = c.source_repo
pull-requests: add explicit CLOSE pr action instead of closed status from selector....
r1445 c.commit_statuses = ChangesetStatus.STATUSES
project: added all source files and assets
r1
pr-versioning: implemented versioning for pull requests....
r1368 c.show_version_changes = not pr_closed
if c.show_version_changes:
cur_obj = pull_request_at_ver
prev_obj = prev_pull_request_at_ver
old_commit_ids = prev_obj.revisions
new_commit_ids = cur_obj.revisions
commit_changes = PullRequestModel()._calculate_commit_id_changes(
old_commit_ids, new_commit_ids)
c.commit_changes_summary = commit_changes
# calculate the diff for commits between versions
c.commit_changes = []
mark = lambda cs, fw: list(
h.itertools.izip_longest([], cs, fillvalue=fw))
for c_type, raw_id in mark(commit_changes.added, 'a') \
+ mark(commit_changes.removed, 'r') \
+ mark(commit_changes.common, 'c'):
pull-requests: expose version browsing of pull requests....
r1255
pr-versioning: implemented versioning for pull requests....
r1368 if raw_id in commit_cache:
commit = commit_cache[raw_id]
else:
try:
commit = commits_source_repo.get_commit(raw_id)
except CommitDoesNotExistError:
# in case we fail extracting still use "dummy" commit
# for display in commit diff
commit = h.AttributeDict(
{'raw_id': raw_id,
'message': 'EMPTY or MISSING COMMIT'})
c.commit_changes.append([c_type, commit])
pull-requests: expose version browsing of pull requests....
r1255
pr-versioning: implemented versioning for pull requests....
r1368 # current user review statuses for each version
c.review_versions = {}
if c.rhodecode_user.user_id in allowed_reviewers:
for co in general_comments:
if co.author.user_id == c.rhodecode_user.user_id:
# each comment has a status change
status = co.status_change
if status:
_ver_pr = status[0].comment.pull_request_version_id
c.review_versions[_ver_pr] = status[0]
pull-requests: expose version browsing of pull requests....
r1255
templating: use .mako as extensions for template files.
r1282 return render('/pullrequests/pullrequest_show.mako')
project: added all source files and assets
r1
@LoginRequired()
@NotAnonymous()
pr-versioning: implemented versioning for pull requests....
r1368 @HasRepoPermissionAnyDecorator(
'repository.read', 'repository.write', 'repository.admin')
project: added all source files and assets
r1 @auth.CSRFRequired()
@jsonify
def comment(self, repo_name, pull_request_id):
pull_request_id = safe_int(pull_request_id)
pull_request = PullRequest.get_or_404(pull_request_id)
if pull_request.is_closed():
pull-request-api: updated logic of closing a PR via API call....
r1792 log.debug('comment: forbidden because pull request is closed')
project: added all source files and assets
r1 raise HTTPForbidden()
status = request.POST.get('changeset_status', None)
text = request.POST.get('text')
comments: add comments type into comments.
r1324 comment_type = request.POST.get('comment_type')
comments: enabled resolution for general comments, and finalized how general comment is build
r1326 resolves_comment_id = request.POST.get('resolves_comment_id', None)
pull-requests: add explicit CLOSE pr action instead of closed status from selector....
r1445 close_pull_request = request.POST.get('close_pull_request')
comments: allow submitting id of comment which submitted comment resolved....
r1325
pull-request-api: updated logic of closing a PR via API call....
r1792 # the logic here should work like following, if we submit close
# pr comment, use `close_pull_request_with_comment` function
# else handle regular comment logic
user = c.rhodecode_user
repo = c.rhodecode_db_repo
pull-reqests: workflow, change who can close a PR, it's only super-admin...
r1686
pull-request-api: updated logic of closing a PR via API call....
r1792 if close_pull_request:
# only owner or admin or person with write permissions
allowed_to_close = PullRequestModel().check_user_update(
pull_request, c.rhodecode_user)
if not allowed_to_close:
log.debug('comment: forbidden because not allowed to close '
'pull request %s', pull_request_id)
raise HTTPForbidden()
comment, status = PullRequestModel().close_pull_request_with_comment(
pull_request, user, repo, message=text)
Session().flush()
events.trigger(
events.PullRequestCommentEvent(pull_request, comment))
project: added all source files and assets
r1
pull-request-api: updated logic of closing a PR via API call....
r1792 else:
# regular comment case, could be inline, or one with status.
# for that one we check also permissions
allowed_to_change_status = PullRequestModel().check_user_change_status(
pull_request, c.rhodecode_user)
if status and allowed_to_change_status:
message = (_('Status change %(transition_icon)s %(status)s')
% {'transition_icon': '>',
'status': ChangesetStatus.get_status_lbl(status)})
text = text or message
project: added all source files and assets
r1
pull-request-api: updated logic of closing a PR via API call....
r1792 comment = CommentsModel().create(
text=text,
repo=c.rhodecode_db_repo.repo_id,
user=c.rhodecode_user.user_id,
pull_request=pull_request_id,
f_path=request.POST.get('f_path'),
line_no=request.POST.get('line'),
status_change=(ChangesetStatus.get_status_lbl(status)
if status and allowed_to_change_status else None),
status_change_type=(status
if status and allowed_to_change_status else None),
comment_type=comment_type,
resolves_comment_id=resolves_comment_id
)
if allowed_to_change_status:
# calculate old status before we change it
old_calculated_status = pull_request.calculated_review_status()
project: added all source files and assets
r1
pull-request-api: updated logic of closing a PR via API call....
r1792 # get status if set !
if status:
ChangesetStatusModel().set_status(
c.rhodecode_db_repo.repo_id,
status,
c.rhodecode_user.user_id,
comment,
pull_request=pull_request_id
)
project: added all source files and assets
r1
pull-request-api: updated logic of closing a PR via API call....
r1792 Session().flush()
events.trigger(
events.PullRequestCommentEvent(pull_request, comment))
project: added all source files and assets
r1
pull-request-api: updated logic of closing a PR via API call....
r1792 # we now calculate the status of pull request, and based on that
# calculation we set the commits status
calculated_status = pull_request.calculated_review_status()
if old_calculated_status != calculated_status:
PullRequestModel()._trigger_pull_request_hook(
pull_request, c.rhodecode_user, 'review_status_change')
project: added all source files and assets
r1
Session().commit()
if not request.is_xhr:
pull-requests: prepare the migration of pull request to pyramid....
r1813 raise HTTPFound(
h.route_path('pullrequest_show',
repo_name=repo_name,
pull_request_id=pull_request_id))
project: added all source files and assets
r1
data = {
'target_id': h.safeid(h.safe_unicode(request.POST.get('f_path'))),
}
pull-request-api: updated logic of closing a PR via API call....
r1792 if comment:
c.co = comment
rendered_comment = render('changeset/changeset_comment_block.mako')
data.update(comment.get_dict())
data.update({'rendered_text': rendered_comment})
project: added all source files and assets
r1
return data
@LoginRequired()
@NotAnonymous()
@HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
'repository.admin')
@auth.CSRFRequired()
@jsonify
def delete_comment(self, repo_name, comment_id):
core: no longer rely on webob exception inside get_or_404 function....
r1956 comment = ChangesetComment.get_or_404(comment_id)
security: make sure the admin of repo can only delete comments which are from the same repo....
r1818 if not comment:
log.debug('Comment with id:%s not found, skipping', comment_id)
# comment already deleted in another call probably
return True
project: added all source files and assets
r1
security: make sure the admin of repo can only delete comments which are from the same repo....
r1818 if comment.pull_request.is_closed():
project: added all source files and assets
r1 # don't allow deleting comments on closed pull request
raise HTTPForbidden()
is_repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name)
security: make sure the admin of repo can only delete comments which are from the same repo....
r1818 super_admin = h.HasPermissionAny('hg.admin')()
comment_owner = comment.author.user_id == c.rhodecode_user.user_id
is_repo_comment = comment.repo.repo_name == c.repo_name
comment_repo_admin = is_repo_admin and is_repo_comment
if super_admin or comment_owner or comment_repo_admin:
old_calculated_status = comment.pull_request.calculated_review_status()
CommentsModel().delete(comment=comment, user=c.rhodecode_user)
project: added all source files and assets
r1 Session().commit()
security: make sure the admin of repo can only delete comments which are from the same repo....
r1818 calculated_status = comment.pull_request.calculated_review_status()
project: added all source files and assets
r1 if old_calculated_status != calculated_status:
PullRequestModel()._trigger_pull_request_hook(
security: make sure the admin of repo can only delete comments which are from the same repo....
r1818 comment.pull_request, c.rhodecode_user, 'review_status_change')
project: added all source files and assets
r1 return True
else:
security: use 404 instead of 403 in case missing permissions for comment deletion....
r1826 log.warning('No permissions for user %s to delete comment_id: %s',
c.rhodecode_user, comment_id)
raise HTTPNotFound()