##// END OF EJS Templates
pull-requests: introduce operation state for pull requests to prevent from...
marcink -
r3371:e7214a9f default
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
@@ -0,0 +1,37 b''
1 import logging
2
3 from sqlalchemy import *
4
5 from rhodecode.model import meta
6 from rhodecode.lib.dbmigrate.versions import _reset_base, notify
7
8 log = logging.getLogger(__name__)
9
10
11 def upgrade(migrate_engine):
12 """
13 Upgrade operations go here.
14 Don't create your own engine; bind migrate_engine to your metadata
15 """
16 _reset_base(migrate_engine)
17 from rhodecode.lib.dbmigrate.schema import db_4_13_0_0 as db
18
19 pull_request = db.PullRequest.__table__
20 pull_request_version = db.PullRequestVersion.__table__
21
22 repo_state_1 = Column("pull_request_state", String(255), nullable=True)
23 repo_state_1.create(table=pull_request)
24
25 repo_state_2 = Column("pull_request_state", String(255), nullable=True)
26 repo_state_2.create(table=pull_request_version)
27
28 fixups(db, meta.Session)
29
30
31 def downgrade(migrate_engine):
32 meta = MetaData()
33 meta.bind = migrate_engine
34
35
36 def fixups(models, _SESSION):
37 pass
@@ -0,0 +1,41 b''
1 import logging
2
3 from sqlalchemy import *
4
5 from rhodecode.model import meta
6 from rhodecode.lib.dbmigrate.versions import _reset_base, notify
7
8 log = logging.getLogger(__name__)
9
10
11 def upgrade(migrate_engine):
12 """
13 Upgrade operations go here.
14 Don't create your own engine; bind migrate_engine to your metadata
15 """
16 _reset_base(migrate_engine)
17 from rhodecode.lib.dbmigrate.schema import db_4_16_0_0 as db
18
19 fixups(db, meta.Session)
20
21
22 def downgrade(migrate_engine):
23 meta = MetaData()
24 meta.bind = migrate_engine
25
26
27 def fixups(models, _SESSION):
28 # move the builtin token to external tokens
29
30 log.info('Updating pull request pull_request_state to %s',
31 models.PullRequest.STATE_CREATED)
32 qry = _SESSION().query(models.PullRequest)
33 qry.update({"pull_request_state": models.PullRequest.STATE_CREATED})
34 _SESSION().commit()
35
36 log.info('Updating pull_request_version pull_request_state to %s',
37 models.PullRequest.STATE_CREATED)
38 qry = _SESSION().query(models.PullRequestVersion)
39 qry.update({"pull_request_state": models.PullRequest.STATE_CREATED})
40 _SESSION().commit()
41
@@ -1,63 +1,57 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 """
22
23 RhodeCode, a web based repository management software
24 versioning implementation: http://www.python.org/dev/peps/pep-0386/
25 """
26
27 21 import os
28 22 import sys
29 23 import platform
30 24
31 25 VERSION = tuple(open(os.path.join(
32 26 os.path.dirname(__file__), 'VERSION')).read().split('.'))
33 27
34 28 BACKENDS = {
35 29 'hg': 'Mercurial repository',
36 30 'git': 'Git repository',
37 31 'svn': 'Subversion repository',
38 32 }
39 33
40 34 CELERY_ENABLED = False
41 35 CELERY_EAGER = False
42 36
43 37 # link to config for pyramid
44 38 CONFIG = {}
45 39
46 40 # Populated with the settings dictionary from application init in
47 41 # rhodecode.conf.environment.load_pyramid_environment
48 42 PYRAMID_SETTINGS = {}
49 43
50 44 # Linked module for extensions
51 45 EXTENSIONS = {}
52 46
53 47 __version__ = ('.'.join((str(each) for each in VERSION[:3])))
54 __dbversion__ = 91 # defines current db version for migrations
48 __dbversion__ = 93 # defines current db version for migrations
55 49 __platform__ = platform.system()
56 50 __license__ = 'AGPLv3, and Commercial License'
57 51 __author__ = 'RhodeCode GmbH'
58 52 __url__ = 'https://code.rhodecode.com'
59 53
60 54 is_windows = __platform__ in ['Windows']
61 55 is_unix = not is_windows
62 56 is_test = False
63 57 disable_error_handler = False
@@ -1,142 +1,143 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21
22 22 import pytest
23 23 import urlobject
24 24
25 25 from rhodecode.api.tests.utils import (
26 26 build_data, api_call, assert_error, assert_ok)
27 27 from rhodecode.lib import helpers as h
28 28 from rhodecode.lib.utils2 import safe_unicode
29 29
30 30 pytestmark = pytest.mark.backends("git", "hg")
31 31
32 32
33 33 @pytest.mark.usefixtures("testuser_api", "app")
34 34 class TestGetPullRequest(object):
35 35
36 36 def test_api_get_pull_request(self, pr_util, http_host_only_stub):
37 37 from rhodecode.model.pull_request import PullRequestModel
38 38 pull_request = pr_util.create_pull_request(mergeable=True)
39 39 id_, params = build_data(
40 40 self.apikey, 'get_pull_request',
41 41 pullrequestid=pull_request.pull_request_id)
42 42
43 43 response = api_call(self.app, params)
44 44
45 45 assert response.status == '200 OK'
46 46
47 47 url_obj = urlobject.URLObject(
48 48 h.route_url(
49 49 'pullrequest_show',
50 50 repo_name=pull_request.target_repo.repo_name,
51 51 pull_request_id=pull_request.pull_request_id))
52 52
53 53 pr_url = safe_unicode(
54 54 url_obj.with_netloc(http_host_only_stub))
55 55 source_url = safe_unicode(
56 56 pull_request.source_repo.clone_url().with_netloc(http_host_only_stub))
57 57 target_url = safe_unicode(
58 58 pull_request.target_repo.clone_url().with_netloc(http_host_only_stub))
59 59 shadow_url = safe_unicode(
60 60 PullRequestModel().get_shadow_clone_url(pull_request))
61 61
62 62 expected = {
63 63 'pull_request_id': pull_request.pull_request_id,
64 64 'url': pr_url,
65 65 'title': pull_request.title,
66 66 'description': pull_request.description,
67 67 'status': pull_request.status,
68 'state': pull_request.pull_request_state,
68 69 'created_on': pull_request.created_on,
69 70 'updated_on': pull_request.updated_on,
70 71 'commit_ids': pull_request.revisions,
71 72 'review_status': pull_request.calculated_review_status(),
72 73 'mergeable': {
73 74 'status': True,
74 75 'message': 'This pull request can be automatically merged.',
75 76 },
76 77 'source': {
77 78 'clone_url': source_url,
78 79 'repository': pull_request.source_repo.repo_name,
79 80 'reference': {
80 81 'name': pull_request.source_ref_parts.name,
81 82 'type': pull_request.source_ref_parts.type,
82 83 'commit_id': pull_request.source_ref_parts.commit_id,
83 84 },
84 85 },
85 86 'target': {
86 87 'clone_url': target_url,
87 88 'repository': pull_request.target_repo.repo_name,
88 89 'reference': {
89 90 'name': pull_request.target_ref_parts.name,
90 91 'type': pull_request.target_ref_parts.type,
91 92 'commit_id': pull_request.target_ref_parts.commit_id,
92 93 },
93 94 },
94 95 'merge': {
95 96 'clone_url': shadow_url,
96 97 'reference': {
97 98 'name': pull_request.shadow_merge_ref.name,
98 99 'type': pull_request.shadow_merge_ref.type,
99 100 'commit_id': pull_request.shadow_merge_ref.commit_id,
100 101 },
101 102 },
102 103 'author': pull_request.author.get_api_data(include_secrets=False,
103 104 details='basic'),
104 105 'reviewers': [
105 106 {
106 107 'user': reviewer.get_api_data(include_secrets=False,
107 108 details='basic'),
108 109 'reasons': reasons,
109 110 'review_status': st[0][1].status if st else 'not_reviewed',
110 111 }
111 112 for obj, reviewer, reasons, mandatory, st in
112 113 pull_request.reviewers_statuses()
113 114 ]
114 115 }
115 116 assert_ok(id_, expected, response.body)
116 117
117 118 def test_api_get_pull_request_repo_error(self, pr_util):
118 119 pull_request = pr_util.create_pull_request()
119 120 id_, params = build_data(
120 121 self.apikey, 'get_pull_request',
121 122 repoid=666, pullrequestid=pull_request.pull_request_id)
122 123 response = api_call(self.app, params)
123 124
124 125 expected = 'repository `666` does not exist'
125 126 assert_error(id_, expected, given=response.body)
126 127
127 128 def test_api_get_pull_request_pull_request_error(self):
128 129 id_, params = build_data(
129 130 self.apikey, 'get_pull_request', pullrequestid=666)
130 131 response = api_call(self.app, params)
131 132
132 133 expected = 'pull request `666` does not exist'
133 134 assert_error(id_, expected, given=response.body)
134 135
135 136 def test_api_get_pull_request_pull_request_error_just_pr_id(self):
136 137 id_, params = build_data(
137 138 self.apikey, 'get_pull_request',
138 139 pullrequestid=666)
139 140 response = api_call(self.app, params)
140 141
141 142 expected = 'pull request `666` does not exist'
142 143 assert_error(id_, expected, given=response.body)
@@ -1,137 +1,157 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import pytest
22 22
23 23 from rhodecode.model.db import UserLog, PullRequest
24 24 from rhodecode.model.meta import Session
25 25 from rhodecode.tests import TEST_USER_ADMIN_LOGIN
26 26 from rhodecode.api.tests.utils import (
27 27 build_data, api_call, assert_error, assert_ok)
28 28
29 29
30 30 @pytest.mark.usefixtures("testuser_api", "app")
31 31 class TestMergePullRequest(object):
32
32 33 @pytest.mark.backends("git", "hg")
33 34 def test_api_merge_pull_request_merge_failed(self, pr_util, no_notifications):
34 35 pull_request = pr_util.create_pull_request(mergeable=True)
35 author = pull_request.user_id
36 repo = pull_request.target_repo.repo_id
37 36 pull_request_id = pull_request.pull_request_id
38 37 pull_request_repo = pull_request.target_repo.repo_name
39 38
40 39 id_, params = build_data(
41 40 self.apikey, 'merge_pull_request',
42 41 repoid=pull_request_repo,
43 42 pullrequestid=pull_request_id)
44 43
45 44 response = api_call(self.app, params)
46 45
47 46 # The above api call detaches the pull request DB object from the
48 47 # session because of an unconditional transaction rollback in our
49 # middleware. Therefore we need to add it back here if we want to use
50 # it.
48 # middleware. Therefore we need to add it back here if we want to use it.
51 49 Session().add(pull_request)
52 50
53 51 expected = 'merge not possible for following reasons: ' \
54 52 'Pull request reviewer approval is pending.'
55 53 assert_error(id_, expected, given=response.body)
56 54
57 55 @pytest.mark.backends("git", "hg")
56 def test_api_merge_pull_request_merge_failed_disallowed_state(
57 self, pr_util, no_notifications):
58 pull_request = pr_util.create_pull_request(mergeable=True, approved=True)
59 pull_request_id = pull_request.pull_request_id
60 pull_request_repo = pull_request.target_repo.repo_name
61
62 pr = PullRequest.get(pull_request_id)
63 pr.pull_request_state = pull_request.STATE_UPDATING
64 Session().add(pr)
65 Session().commit()
66
67 id_, params = build_data(
68 self.apikey, 'merge_pull_request',
69 repoid=pull_request_repo,
70 pullrequestid=pull_request_id)
71
72 response = api_call(self.app, params)
73 expected = 'Operation forbidden because pull request is in state {}, '\
74 'only state {} is allowed.'.format(PullRequest.STATE_UPDATING,
75 PullRequest.STATE_CREATED)
76 assert_error(id_, expected, given=response.body)
77
78 @pytest.mark.backends("git", "hg")
58 79 def test_api_merge_pull_request(self, pr_util, no_notifications):
59 80 pull_request = pr_util.create_pull_request(mergeable=True, approved=True)
60 81 author = pull_request.user_id
61 82 repo = pull_request.target_repo.repo_id
62 83 pull_request_id = pull_request.pull_request_id
63 84 pull_request_repo = pull_request.target_repo.repo_name
64 85
65 86 id_, params = build_data(
66 87 self.apikey, 'comment_pull_request',
67 88 repoid=pull_request_repo,
68 89 pullrequestid=pull_request_id,
69 90 status='approved')
70 91
71 92 response = api_call(self.app, params)
72 93 expected = {
73 94 'comment_id': response.json.get('result', {}).get('comment_id'),
74 95 'pull_request_id': pull_request_id,
75 96 'status': {'given': 'approved', 'was_changed': True}
76 97 }
77 98 assert_ok(id_, expected, given=response.body)
78 99
79 100 id_, params = build_data(
80 101 self.apikey, 'merge_pull_request',
81 102 repoid=pull_request_repo,
82 103 pullrequestid=pull_request_id)
83 104
84 105 response = api_call(self.app, params)
85 106
86 107 pull_request = PullRequest.get(pull_request_id)
87 108
88 109 expected = {
89 110 'executed': True,
90 111 'failure_reason': 0,
91 112 'possible': True,
92 113 'merge_commit_id': pull_request.shadow_merge_ref.commit_id,
93 114 'merge_ref': pull_request.shadow_merge_ref._asdict()
94 115 }
95 116
96 117 assert_ok(id_, expected, response.body)
97 118
98 119 journal = UserLog.query()\
99 120 .filter(UserLog.user_id == author)\
100 121 .filter(UserLog.repository_id == repo) \
101 122 .order_by('user_log_id') \
102 123 .all()
103 124 assert journal[-2].action == 'repo.pull_request.merge'
104 125 assert journal[-1].action == 'repo.pull_request.close'
105 126
106 127 id_, params = build_data(
107 128 self.apikey, 'merge_pull_request',
108 129 repoid=pull_request_repo, pullrequestid=pull_request_id)
109 130 response = api_call(self.app, params)
110 131
111 132 expected = 'merge not possible for following reasons: This pull request is closed.'
112 133 assert_error(id_, expected, given=response.body)
113 134
114 135 @pytest.mark.backends("git", "hg")
115 136 def test_api_merge_pull_request_repo_error(self, pr_util):
116 137 pull_request = pr_util.create_pull_request()
117 138 id_, params = build_data(
118 139 self.apikey, 'merge_pull_request',
119 140 repoid=666, pullrequestid=pull_request.pull_request_id)
120 141 response = api_call(self.app, params)
121 142
122 143 expected = 'repository `666` does not exist'
123 144 assert_error(id_, expected, given=response.body)
124 145
125 146 @pytest.mark.backends("git", "hg")
126 def test_api_merge_pull_request_non_admin_with_userid_error(self,
127 pr_util):
147 def test_api_merge_pull_request_non_admin_with_userid_error(self, pr_util):
128 148 pull_request = pr_util.create_pull_request(mergeable=True)
129 149 id_, params = build_data(
130 150 self.apikey_regular, 'merge_pull_request',
131 151 repoid=pull_request.target_repo.repo_name,
132 152 pullrequestid=pull_request.pull_request_id,
133 153 userid=TEST_USER_ADMIN_LOGIN)
134 154 response = api_call(self.app, params)
135 155
136 156 expected = 'userid is not the same as your user'
137 157 assert_error(id_, expected, given=response.body)
@@ -1,937 +1,957 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21
22 22 import logging
23 23
24 24 from rhodecode import events
25 25 from rhodecode.api import jsonrpc_method, JSONRPCError, JSONRPCValidationError
26 26 from rhodecode.api.utils import (
27 27 has_superadmin_permission, Optional, OAttr, get_repo_or_error,
28 28 get_pull_request_or_error, get_commit_or_error, get_user_or_error,
29 29 validate_repo_permissions, resolve_ref_or_error)
30 30 from rhodecode.lib.auth import (HasRepoPermissionAnyApi)
31 31 from rhodecode.lib.base import vcs_operation_context
32 32 from rhodecode.lib.utils2 import str2bool
33 33 from rhodecode.model.changeset_status import ChangesetStatusModel
34 34 from rhodecode.model.comment import CommentsModel
35 from rhodecode.model.db import Session, ChangesetStatus, ChangesetComment
35 from rhodecode.model.db import Session, ChangesetStatus, ChangesetComment, PullRequest
36 36 from rhodecode.model.pull_request import PullRequestModel, MergeCheck
37 37 from rhodecode.model.settings import SettingsModel
38 38 from rhodecode.model.validation_schema import Invalid
39 39 from rhodecode.model.validation_schema.schemas.reviewer_schema import(
40 40 ReviewerListSchema)
41 41
42 42 log = logging.getLogger(__name__)
43 43
44 44
45 45 @jsonrpc_method()
46 46 def get_pull_request(request, apiuser, pullrequestid, repoid=Optional(None)):
47 47 """
48 48 Get a pull request based on the given ID.
49 49
50 50 :param apiuser: This is filled automatically from the |authtoken|.
51 51 :type apiuser: AuthUser
52 52 :param repoid: Optional, repository name or repository ID from where
53 53 the pull request was opened.
54 54 :type repoid: str or int
55 55 :param pullrequestid: ID of the requested pull request.
56 56 :type pullrequestid: int
57 57
58 58 Example output:
59 59
60 60 .. code-block:: bash
61 61
62 62 "id": <id_given_in_input>,
63 63 "result":
64 64 {
65 65 "pull_request_id": "<pull_request_id>",
66 66 "url": "<url>",
67 67 "title": "<title>",
68 68 "description": "<description>",
69 69 "status" : "<status>",
70 70 "created_on": "<date_time_created>",
71 71 "updated_on": "<date_time_updated>",
72 72 "commit_ids": [
73 73 ...
74 74 "<commit_id>",
75 75 "<commit_id>",
76 76 ...
77 77 ],
78 78 "review_status": "<review_status>",
79 79 "mergeable": {
80 80 "status": "<bool>",
81 81 "message": "<message>",
82 82 },
83 83 "source": {
84 84 "clone_url": "<clone_url>",
85 85 "repository": "<repository_name>",
86 86 "reference":
87 87 {
88 88 "name": "<name>",
89 89 "type": "<type>",
90 90 "commit_id": "<commit_id>",
91 91 }
92 92 },
93 93 "target": {
94 94 "clone_url": "<clone_url>",
95 95 "repository": "<repository_name>",
96 96 "reference":
97 97 {
98 98 "name": "<name>",
99 99 "type": "<type>",
100 100 "commit_id": "<commit_id>",
101 101 }
102 102 },
103 103 "merge": {
104 104 "clone_url": "<clone_url>",
105 105 "reference":
106 106 {
107 107 "name": "<name>",
108 108 "type": "<type>",
109 109 "commit_id": "<commit_id>",
110 110 }
111 111 },
112 112 "author": <user_obj>,
113 113 "reviewers": [
114 114 ...
115 115 {
116 116 "user": "<user_obj>",
117 117 "review_status": "<review_status>",
118 118 }
119 119 ...
120 120 ]
121 121 },
122 122 "error": null
123 123 """
124 124
125 125 pull_request = get_pull_request_or_error(pullrequestid)
126 126 if Optional.extract(repoid):
127 127 repo = get_repo_or_error(repoid)
128 128 else:
129 129 repo = pull_request.target_repo
130 130
131 if not PullRequestModel().check_user_read(
132 pull_request, apiuser, api=True):
131 if not PullRequestModel().check_user_read(pull_request, apiuser, api=True):
133 132 raise JSONRPCError('repository `%s` or pull request `%s` '
134 133 'does not exist' % (repoid, pullrequestid))
135 data = pull_request.get_api_data()
134
135 # NOTE(marcink): only calculate and return merge state if the pr state is 'created'
136 # otherwise we can lock the repo on calculation of merge state while update/merge
137 # is happening.
138 merge_state = pull_request.pull_request_state == pull_request.STATE_CREATED
139 data = pull_request.get_api_data(with_merge_state=merge_state)
136 140 return data
137 141
138 142
139 143 @jsonrpc_method()
140 144 def get_pull_requests(request, apiuser, repoid, status=Optional('new')):
141 145 """
142 146 Get all pull requests from the repository specified in `repoid`.
143 147
144 148 :param apiuser: This is filled automatically from the |authtoken|.
145 149 :type apiuser: AuthUser
146 150 :param repoid: Optional repository name or repository ID.
147 151 :type repoid: str or int
148 152 :param status: Only return pull requests with the specified status.
149 153 Valid options are.
150 154 * ``new`` (default)
151 155 * ``open``
152 156 * ``closed``
153 157 :type status: str
154 158
155 159 Example output:
156 160
157 161 .. code-block:: bash
158 162
159 163 "id": <id_given_in_input>,
160 164 "result":
161 165 [
162 166 ...
163 167 {
164 168 "pull_request_id": "<pull_request_id>",
165 169 "url": "<url>",
166 170 "title" : "<title>",
167 171 "description": "<description>",
168 172 "status": "<status>",
169 173 "created_on": "<date_time_created>",
170 174 "updated_on": "<date_time_updated>",
171 175 "commit_ids": [
172 176 ...
173 177 "<commit_id>",
174 178 "<commit_id>",
175 179 ...
176 180 ],
177 181 "review_status": "<review_status>",
178 182 "mergeable": {
179 183 "status": "<bool>",
180 184 "message: "<message>",
181 185 },
182 186 "source": {
183 187 "clone_url": "<clone_url>",
184 188 "reference":
185 189 {
186 190 "name": "<name>",
187 191 "type": "<type>",
188 192 "commit_id": "<commit_id>",
189 193 }
190 194 },
191 195 "target": {
192 196 "clone_url": "<clone_url>",
193 197 "reference":
194 198 {
195 199 "name": "<name>",
196 200 "type": "<type>",
197 201 "commit_id": "<commit_id>",
198 202 }
199 203 },
200 204 "merge": {
201 205 "clone_url": "<clone_url>",
202 206 "reference":
203 207 {
204 208 "name": "<name>",
205 209 "type": "<type>",
206 210 "commit_id": "<commit_id>",
207 211 }
208 212 },
209 213 "author": <user_obj>,
210 214 "reviewers": [
211 215 ...
212 216 {
213 217 "user": "<user_obj>",
214 218 "review_status": "<review_status>",
215 219 }
216 220 ...
217 221 ]
218 222 }
219 223 ...
220 224 ],
221 225 "error": null
222 226
223 227 """
224 228 repo = get_repo_or_error(repoid)
225 229 if not has_superadmin_permission(apiuser):
226 230 _perms = (
227 231 'repository.admin', 'repository.write', 'repository.read',)
228 232 validate_repo_permissions(apiuser, repoid, repo, _perms)
229 233
230 234 status = Optional.extract(status)
231 235 pull_requests = PullRequestModel().get_all(repo, statuses=[status])
232 236 data = [pr.get_api_data() for pr in pull_requests]
233 237 return data
234 238
235 239
236 240 @jsonrpc_method()
237 241 def merge_pull_request(
238 242 request, apiuser, pullrequestid, repoid=Optional(None),
239 243 userid=Optional(OAttr('apiuser'))):
240 244 """
241 245 Merge the pull request specified by `pullrequestid` into its target
242 246 repository.
243 247
244 248 :param apiuser: This is filled automatically from the |authtoken|.
245 249 :type apiuser: AuthUser
246 250 :param repoid: Optional, repository name or repository ID of the
247 251 target repository to which the |pr| is to be merged.
248 252 :type repoid: str or int
249 253 :param pullrequestid: ID of the pull request which shall be merged.
250 254 :type pullrequestid: int
251 255 :param userid: Merge the pull request as this user.
252 256 :type userid: Optional(str or int)
253 257
254 258 Example output:
255 259
256 260 .. code-block:: bash
257 261
258 262 "id": <id_given_in_input>,
259 263 "result": {
260 264 "executed": "<bool>",
261 265 "failure_reason": "<int>",
262 266 "merge_commit_id": "<merge_commit_id>",
263 267 "possible": "<bool>",
264 268 "merge_ref": {
265 269 "commit_id": "<commit_id>",
266 270 "type": "<type>",
267 271 "name": "<name>"
268 272 }
269 273 },
270 274 "error": null
271 275 """
272 276 pull_request = get_pull_request_or_error(pullrequestid)
273 277 if Optional.extract(repoid):
274 278 repo = get_repo_or_error(repoid)
275 279 else:
276 280 repo = pull_request.target_repo
277 281
278 282 if not isinstance(userid, Optional):
279 283 if (has_superadmin_permission(apiuser) or
280 284 HasRepoPermissionAnyApi('repository.admin')(
281 285 user=apiuser, repo_name=repo.repo_name)):
282 286 apiuser = get_user_or_error(userid)
283 287 else:
284 288 raise JSONRPCError('userid is not the same as your user')
285 289
286 check = MergeCheck.validate(
287 pull_request, auth_user=apiuser, translator=request.translate)
290 if pull_request.pull_request_state != PullRequest.STATE_CREATED:
291 raise JSONRPCError(
292 'Operation forbidden because pull request is in state {}, '
293 'only state {} is allowed.'.format(
294 pull_request.pull_request_state, PullRequest.STATE_CREATED))
295
296 with pull_request.set_state(PullRequest.STATE_UPDATING):
297 check = MergeCheck.validate(
298 pull_request, auth_user=apiuser,
299 translator=request.translate)
288 300 merge_possible = not check.failed
289 301
290 302 if not merge_possible:
291 303 error_messages = []
292 304 for err_type, error_msg in check.errors:
293 305 error_msg = request.translate(error_msg)
294 306 error_messages.append(error_msg)
295 307
296 308 reasons = ','.join(error_messages)
297 309 raise JSONRPCError(
298 310 'merge not possible for following reasons: {}'.format(reasons))
299 311
300 312 target_repo = pull_request.target_repo
301 313 extras = vcs_operation_context(
302 314 request.environ, repo_name=target_repo.repo_name,
303 315 username=apiuser.username, action='push',
304 316 scm=target_repo.repo_type)
305 merge_response = PullRequestModel().merge_repo(
306 pull_request, apiuser, extras=extras)
317 with pull_request.set_state(PullRequest.STATE_UPDATING):
318 merge_response = PullRequestModel().merge_repo(
319 pull_request, apiuser, extras=extras)
307 320 if merge_response.executed:
308 321 PullRequestModel().close_pull_request(
309 322 pull_request.pull_request_id, apiuser)
310 323
311 324 Session().commit()
312 325
313 326 # In previous versions the merge response directly contained the merge
314 327 # commit id. It is now contained in the merge reference object. To be
315 328 # backwards compatible we have to extract it again.
316 329 merge_response = merge_response.asdict()
317 330 merge_response['merge_commit_id'] = merge_response['merge_ref'].commit_id
318 331
319 332 return merge_response
320 333
321 334
322 335 @jsonrpc_method()
323 336 def get_pull_request_comments(
324 337 request, apiuser, pullrequestid, repoid=Optional(None)):
325 338 """
326 339 Get all comments of pull request specified with the `pullrequestid`
327 340
328 341 :param apiuser: This is filled automatically from the |authtoken|.
329 342 :type apiuser: AuthUser
330 343 :param repoid: Optional repository name or repository ID.
331 344 :type repoid: str or int
332 345 :param pullrequestid: The pull request ID.
333 346 :type pullrequestid: int
334 347
335 348 Example output:
336 349
337 350 .. code-block:: bash
338 351
339 352 id : <id_given_in_input>
340 353 result : [
341 354 {
342 355 "comment_author": {
343 356 "active": true,
344 357 "full_name_or_username": "Tom Gore",
345 358 "username": "admin"
346 359 },
347 360 "comment_created_on": "2017-01-02T18:43:45.533",
348 361 "comment_f_path": null,
349 362 "comment_id": 25,
350 363 "comment_lineno": null,
351 364 "comment_status": {
352 365 "status": "under_review",
353 366 "status_lbl": "Under Review"
354 367 },
355 368 "comment_text": "Example text",
356 369 "comment_type": null,
357 370 "pull_request_version": null
358 371 }
359 372 ],
360 373 error : null
361 374 """
362 375
363 376 pull_request = get_pull_request_or_error(pullrequestid)
364 377 if Optional.extract(repoid):
365 378 repo = get_repo_or_error(repoid)
366 379 else:
367 380 repo = pull_request.target_repo
368 381
369 382 if not PullRequestModel().check_user_read(
370 383 pull_request, apiuser, api=True):
371 384 raise JSONRPCError('repository `%s` or pull request `%s` '
372 385 'does not exist' % (repoid, pullrequestid))
373 386
374 387 (pull_request_latest,
375 388 pull_request_at_ver,
376 389 pull_request_display_obj,
377 390 at_version) = PullRequestModel().get_pr_version(
378 391 pull_request.pull_request_id, version=None)
379 392
380 393 versions = pull_request_display_obj.versions()
381 394 ver_map = {
382 395 ver.pull_request_version_id: cnt
383 396 for cnt, ver in enumerate(versions, 1)
384 397 }
385 398
386 399 # GENERAL COMMENTS with versions #
387 400 q = CommentsModel()._all_general_comments_of_pull_request(pull_request)
388 401 q = q.order_by(ChangesetComment.comment_id.asc())
389 402 general_comments = q.all()
390 403
391 404 # INLINE COMMENTS with versions #
392 405 q = CommentsModel()._all_inline_comments_of_pull_request(pull_request)
393 406 q = q.order_by(ChangesetComment.comment_id.asc())
394 407 inline_comments = q.all()
395 408
396 409 data = []
397 410 for comment in inline_comments + general_comments:
398 411 full_data = comment.get_api_data()
399 412 pr_version_id = None
400 413 if comment.pull_request_version_id:
401 414 pr_version_id = 'v{}'.format(
402 415 ver_map[comment.pull_request_version_id])
403 416
404 417 # sanitize some entries
405 418
406 419 full_data['pull_request_version'] = pr_version_id
407 420 full_data['comment_author'] = {
408 421 'username': full_data['comment_author'].username,
409 422 'full_name_or_username': full_data['comment_author'].full_name_or_username,
410 423 'active': full_data['comment_author'].active,
411 424 }
412 425
413 426 if full_data['comment_status']:
414 427 full_data['comment_status'] = {
415 428 'status': full_data['comment_status'][0].status,
416 429 'status_lbl': full_data['comment_status'][0].status_lbl,
417 430 }
418 431 else:
419 432 full_data['comment_status'] = {}
420 433
421 434 data.append(full_data)
422 435 return data
423 436
424 437
425 438 @jsonrpc_method()
426 439 def comment_pull_request(
427 440 request, apiuser, pullrequestid, repoid=Optional(None),
428 441 message=Optional(None), commit_id=Optional(None), status=Optional(None),
429 442 comment_type=Optional(ChangesetComment.COMMENT_TYPE_NOTE),
430 443 resolves_comment_id=Optional(None),
431 444 userid=Optional(OAttr('apiuser'))):
432 445 """
433 446 Comment on the pull request specified with the `pullrequestid`,
434 447 in the |repo| specified by the `repoid`, and optionally change the
435 448 review status.
436 449
437 450 :param apiuser: This is filled automatically from the |authtoken|.
438 451 :type apiuser: AuthUser
439 452 :param repoid: Optional repository name or repository ID.
440 453 :type repoid: str or int
441 454 :param pullrequestid: The pull request ID.
442 455 :type pullrequestid: int
443 456 :param commit_id: Specify the commit_id for which to set a comment. If
444 457 given commit_id is different than latest in the PR status
445 458 change won't be performed.
446 459 :type commit_id: str
447 460 :param message: The text content of the comment.
448 461 :type message: str
449 462 :param status: (**Optional**) Set the approval status of the pull
450 463 request. One of: 'not_reviewed', 'approved', 'rejected',
451 464 'under_review'
452 465 :type status: str
453 466 :param comment_type: Comment type, one of: 'note', 'todo'
454 467 :type comment_type: Optional(str), default: 'note'
455 468 :param userid: Comment on the pull request as this user
456 469 :type userid: Optional(str or int)
457 470
458 471 Example output:
459 472
460 473 .. code-block:: bash
461 474
462 475 id : <id_given_in_input>
463 476 result : {
464 477 "pull_request_id": "<Integer>",
465 478 "comment_id": "<Integer>",
466 479 "status": {"given": <given_status>,
467 480 "was_changed": <bool status_was_actually_changed> },
468 481 },
469 482 error : null
470 483 """
471 484 pull_request = get_pull_request_or_error(pullrequestid)
472 485 if Optional.extract(repoid):
473 486 repo = get_repo_or_error(repoid)
474 487 else:
475 488 repo = pull_request.target_repo
476 489
477 490 if not isinstance(userid, Optional):
478 491 if (has_superadmin_permission(apiuser) or
479 492 HasRepoPermissionAnyApi('repository.admin')(
480 493 user=apiuser, repo_name=repo.repo_name)):
481 494 apiuser = get_user_or_error(userid)
482 495 else:
483 496 raise JSONRPCError('userid is not the same as your user')
484 497
485 498 if not PullRequestModel().check_user_read(
486 499 pull_request, apiuser, api=True):
487 500 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
488 501 message = Optional.extract(message)
489 502 status = Optional.extract(status)
490 503 commit_id = Optional.extract(commit_id)
491 504 comment_type = Optional.extract(comment_type)
492 505 resolves_comment_id = Optional.extract(resolves_comment_id)
493 506
494 507 if not message and not status:
495 508 raise JSONRPCError(
496 509 'Both message and status parameters are missing. '
497 510 'At least one is required.')
498 511
499 512 if (status not in (st[0] for st in ChangesetStatus.STATUSES) and
500 513 status is not None):
501 514 raise JSONRPCError('Unknown comment status: `%s`' % status)
502 515
503 516 if commit_id and commit_id not in pull_request.revisions:
504 517 raise JSONRPCError(
505 518 'Invalid commit_id `%s` for this pull request.' % commit_id)
506 519
507 520 allowed_to_change_status = PullRequestModel().check_user_change_status(
508 521 pull_request, apiuser)
509 522
510 523 # if commit_id is passed re-validated if user is allowed to change status
511 524 # based on latest commit_id from the PR
512 525 if commit_id:
513 526 commit_idx = pull_request.revisions.index(commit_id)
514 527 if commit_idx != 0:
515 528 allowed_to_change_status = False
516 529
517 530 if resolves_comment_id:
518 531 comment = ChangesetComment.get(resolves_comment_id)
519 532 if not comment:
520 533 raise JSONRPCError(
521 534 'Invalid resolves_comment_id `%s` for this pull request.'
522 535 % resolves_comment_id)
523 536 if comment.comment_type != ChangesetComment.COMMENT_TYPE_TODO:
524 537 raise JSONRPCError(
525 538 'Comment `%s` is wrong type for setting status to resolved.'
526 539 % resolves_comment_id)
527 540
528 541 text = message
529 542 status_label = ChangesetStatus.get_status_lbl(status)
530 543 if status and allowed_to_change_status:
531 544 st_message = ('Status change %(transition_icon)s %(status)s'
532 545 % {'transition_icon': '>', 'status': status_label})
533 546 text = message or st_message
534 547
535 548 rc_config = SettingsModel().get_all_settings()
536 549 renderer = rc_config.get('rhodecode_markup_renderer', 'rst')
537 550
538 551 status_change = status and allowed_to_change_status
539 552 comment = CommentsModel().create(
540 553 text=text,
541 554 repo=pull_request.target_repo.repo_id,
542 555 user=apiuser.user_id,
543 556 pull_request=pull_request.pull_request_id,
544 557 f_path=None,
545 558 line_no=None,
546 559 status_change=(status_label if status_change else None),
547 560 status_change_type=(status if status_change else None),
548 561 closing_pr=False,
549 562 renderer=renderer,
550 563 comment_type=comment_type,
551 564 resolves_comment_id=resolves_comment_id,
552 565 auth_user=apiuser
553 566 )
554 567
555 568 if allowed_to_change_status and status:
556 569 ChangesetStatusModel().set_status(
557 570 pull_request.target_repo.repo_id,
558 571 status,
559 572 apiuser.user_id,
560 573 comment,
561 574 pull_request=pull_request.pull_request_id
562 575 )
563 576 Session().flush()
564 577
565 578 Session().commit()
566 579 data = {
567 580 'pull_request_id': pull_request.pull_request_id,
568 581 'comment_id': comment.comment_id if comment else None,
569 582 'status': {'given': status, 'was_changed': status_change},
570 583 }
571 584 return data
572 585
573 586
574 587 @jsonrpc_method()
575 588 def create_pull_request(
576 589 request, apiuser, source_repo, target_repo, source_ref, target_ref,
577 590 title=Optional(''), description=Optional(''), description_renderer=Optional(''),
578 591 reviewers=Optional(None)):
579 592 """
580 593 Creates a new pull request.
581 594
582 595 Accepts refs in the following formats:
583 596
584 597 * branch:<branch_name>:<sha>
585 598 * branch:<branch_name>
586 599 * bookmark:<bookmark_name>:<sha> (Mercurial only)
587 600 * bookmark:<bookmark_name> (Mercurial only)
588 601
589 602 :param apiuser: This is filled automatically from the |authtoken|.
590 603 :type apiuser: AuthUser
591 604 :param source_repo: Set the source repository name.
592 605 :type source_repo: str
593 606 :param target_repo: Set the target repository name.
594 607 :type target_repo: str
595 608 :param source_ref: Set the source ref name.
596 609 :type source_ref: str
597 610 :param target_ref: Set the target ref name.
598 611 :type target_ref: str
599 612 :param title: Optionally Set the pull request title, it's generated otherwise
600 613 :type title: str
601 614 :param description: Set the pull request description.
602 615 :type description: Optional(str)
603 616 :type description_renderer: Optional(str)
604 617 :param description_renderer: Set pull request renderer for the description.
605 618 It should be 'rst', 'markdown' or 'plain'. If not give default
606 619 system renderer will be used
607 620 :param reviewers: Set the new pull request reviewers list.
608 621 Reviewer defined by review rules will be added automatically to the
609 622 defined list.
610 623 :type reviewers: Optional(list)
611 624 Accepts username strings or objects of the format:
612 625
613 626 [{'username': 'nick', 'reasons': ['original author'], 'mandatory': <bool>}]
614 627 """
615 628
616 629 source_db_repo = get_repo_or_error(source_repo)
617 630 target_db_repo = get_repo_or_error(target_repo)
618 631 if not has_superadmin_permission(apiuser):
619 632 _perms = ('repository.admin', 'repository.write', 'repository.read',)
620 633 validate_repo_permissions(apiuser, source_repo, source_db_repo, _perms)
621 634
622 635 full_source_ref = resolve_ref_or_error(source_ref, source_db_repo)
623 636 full_target_ref = resolve_ref_or_error(target_ref, target_db_repo)
624 637
625 638 source_scm = source_db_repo.scm_instance()
626 639 target_scm = target_db_repo.scm_instance()
627 640
628 641 source_commit = get_commit_or_error(full_source_ref, source_db_repo)
629 642 target_commit = get_commit_or_error(full_target_ref, target_db_repo)
630 643
631 644 ancestor = source_scm.get_common_ancestor(
632 645 source_commit.raw_id, target_commit.raw_id, target_scm)
633 646 if not ancestor:
634 647 raise JSONRPCError('no common ancestor found')
635 648
636 649 # recalculate target ref based on ancestor
637 650 target_ref_type, target_ref_name, __ = full_target_ref.split(':')
638 651 full_target_ref = ':'.join((target_ref_type, target_ref_name, ancestor))
639 652
640 653 commit_ranges = target_scm.compare(
641 654 target_commit.raw_id, source_commit.raw_id, source_scm,
642 655 merge=True, pre_load=[])
643 656
644 657 if not commit_ranges:
645 658 raise JSONRPCError('no commits found')
646 659
647 660 reviewer_objects = Optional.extract(reviewers) or []
648 661
649 662 # serialize and validate passed in given reviewers
650 663 if reviewer_objects:
651 664 schema = ReviewerListSchema()
652 665 try:
653 666 reviewer_objects = schema.deserialize(reviewer_objects)
654 667 except Invalid as err:
655 668 raise JSONRPCValidationError(colander_exc=err)
656 669
657 670 # validate users
658 671 for reviewer_object in reviewer_objects:
659 672 user = get_user_or_error(reviewer_object['username'])
660 673 reviewer_object['user_id'] = user.user_id
661 674
662 675 get_default_reviewers_data, validate_default_reviewers = \
663 676 PullRequestModel().get_reviewer_functions()
664 677
665 678 # recalculate reviewers logic, to make sure we can validate this
666 679 reviewer_rules = get_default_reviewers_data(
667 680 apiuser.get_instance(), source_db_repo,
668 681 source_commit, target_db_repo, target_commit)
669 682
670 683 # now MERGE our given with the calculated
671 684 reviewer_objects = reviewer_rules['reviewers'] + reviewer_objects
672 685
673 686 try:
674 687 reviewers = validate_default_reviewers(
675 688 reviewer_objects, reviewer_rules)
676 689 except ValueError as e:
677 690 raise JSONRPCError('Reviewers Validation: {}'.format(e))
678 691
679 692 title = Optional.extract(title)
680 693 if not title:
681 694 title_source_ref = source_ref.split(':', 2)[1]
682 695 title = PullRequestModel().generate_pullrequest_title(
683 696 source=source_repo,
684 697 source_ref=title_source_ref,
685 698 target=target_repo
686 699 )
687 700 # fetch renderer, if set fallback to plain in case of PR
688 701 rc_config = SettingsModel().get_all_settings()
689 702 default_system_renderer = rc_config.get('rhodecode_markup_renderer', 'plain')
690 703 description = Optional.extract(description)
691 704 description_renderer = Optional.extract(description_renderer) or default_system_renderer
692 705
693 706 pull_request = PullRequestModel().create(
694 707 created_by=apiuser.user_id,
695 708 source_repo=source_repo,
696 709 source_ref=full_source_ref,
697 710 target_repo=target_repo,
698 711 target_ref=full_target_ref,
699 712 revisions=[commit.raw_id for commit in reversed(commit_ranges)],
700 713 reviewers=reviewers,
701 714 title=title,
702 715 description=description,
703 716 description_renderer=description_renderer,
704 717 reviewer_data=reviewer_rules,
705 718 auth_user=apiuser
706 719 )
707 720
708 721 Session().commit()
709 722 data = {
710 723 'msg': 'Created new pull request `{}`'.format(title),
711 724 'pull_request_id': pull_request.pull_request_id,
712 725 }
713 726 return data
714 727
715 728
716 729 @jsonrpc_method()
717 730 def update_pull_request(
718 731 request, apiuser, pullrequestid, repoid=Optional(None),
719 732 title=Optional(''), description=Optional(''), description_renderer=Optional(''),
720 733 reviewers=Optional(None), update_commits=Optional(None)):
721 734 """
722 735 Updates a pull request.
723 736
724 737 :param apiuser: This is filled automatically from the |authtoken|.
725 738 :type apiuser: AuthUser
726 739 :param repoid: Optional repository name or repository ID.
727 740 :type repoid: str or int
728 741 :param pullrequestid: The pull request ID.
729 742 :type pullrequestid: int
730 743 :param title: Set the pull request title.
731 744 :type title: str
732 745 :param description: Update pull request description.
733 746 :type description: Optional(str)
734 747 :type description_renderer: Optional(str)
735 748 :param description_renderer: Update pull request renderer for the description.
736 749 It should be 'rst', 'markdown' or 'plain'
737 750 :param reviewers: Update pull request reviewers list with new value.
738 751 :type reviewers: Optional(list)
739 752 Accepts username strings or objects of the format:
740 753
741 754 [{'username': 'nick', 'reasons': ['original author'], 'mandatory': <bool>}]
742 755
743 756 :param update_commits: Trigger update of commits for this pull request
744 757 :type: update_commits: Optional(bool)
745 758
746 759 Example output:
747 760
748 761 .. code-block:: bash
749 762
750 763 id : <id_given_in_input>
751 764 result : {
752 765 "msg": "Updated pull request `63`",
753 766 "pull_request": <pull_request_object>,
754 767 "updated_reviewers": {
755 768 "added": [
756 769 "username"
757 770 ],
758 771 "removed": []
759 772 },
760 773 "updated_commits": {
761 774 "added": [
762 775 "<sha1_hash>"
763 776 ],
764 777 "common": [
765 778 "<sha1_hash>",
766 779 "<sha1_hash>",
767 780 ],
768 781 "removed": []
769 782 }
770 783 }
771 784 error : null
772 785 """
773 786
774 787 pull_request = get_pull_request_or_error(pullrequestid)
775 788 if Optional.extract(repoid):
776 789 repo = get_repo_or_error(repoid)
777 790 else:
778 791 repo = pull_request.target_repo
779 792
780 793 if not PullRequestModel().check_user_update(
781 794 pull_request, apiuser, api=True):
782 795 raise JSONRPCError(
783 796 'pull request `%s` update failed, no permission to update.' % (
784 797 pullrequestid,))
785 798 if pull_request.is_closed():
786 799 raise JSONRPCError(
787 800 'pull request `%s` update failed, pull request is closed' % (
788 801 pullrequestid,))
789 802
790 803 reviewer_objects = Optional.extract(reviewers) or []
791 804
792 805 if reviewer_objects:
793 806 schema = ReviewerListSchema()
794 807 try:
795 808 reviewer_objects = schema.deserialize(reviewer_objects)
796 809 except Invalid as err:
797 810 raise JSONRPCValidationError(colander_exc=err)
798 811
799 812 # validate users
800 813 for reviewer_object in reviewer_objects:
801 814 user = get_user_or_error(reviewer_object['username'])
802 815 reviewer_object['user_id'] = user.user_id
803 816
804 817 get_default_reviewers_data, get_validated_reviewers = \
805 818 PullRequestModel().get_reviewer_functions()
806 819
807 820 # re-use stored rules
808 821 reviewer_rules = pull_request.reviewer_data
809 822 try:
810 823 reviewers = get_validated_reviewers(
811 824 reviewer_objects, reviewer_rules)
812 825 except ValueError as e:
813 826 raise JSONRPCError('Reviewers Validation: {}'.format(e))
814 827 else:
815 828 reviewers = []
816 829
817 830 title = Optional.extract(title)
818 831 description = Optional.extract(description)
819 832 description_renderer = Optional.extract(description_renderer)
820 833
821 834 if title or description:
822 835 PullRequestModel().edit(
823 836 pull_request,
824 837 title or pull_request.title,
825 838 description or pull_request.description,
826 839 description_renderer or pull_request.description_renderer,
827 840 apiuser)
828 841 Session().commit()
829 842
830 843 commit_changes = {"added": [], "common": [], "removed": []}
831 844 if str2bool(Optional.extract(update_commits)):
832 if PullRequestModel().has_valid_update_type(pull_request):
833 update_response = PullRequestModel().update_commits(
834 pull_request)
835 commit_changes = update_response.changes or commit_changes
836 Session().commit()
845
846 if pull_request.pull_request_state != PullRequest.STATE_CREATED:
847 raise JSONRPCError(
848 'Operation forbidden because pull request is in state {}, '
849 'only state {} is allowed.'.format(
850 pull_request.pull_request_state, PullRequest.STATE_CREATED))
851
852 with pull_request.set_state(PullRequest.STATE_UPDATING):
853 if PullRequestModel().has_valid_update_type(pull_request):
854 update_response = PullRequestModel().update_commits(pull_request)
855 commit_changes = update_response.changes or commit_changes
856 Session().commit()
837 857
838 858 reviewers_changes = {"added": [], "removed": []}
839 859 if reviewers:
840 860 added_reviewers, removed_reviewers = \
841 861 PullRequestModel().update_reviewers(pull_request, reviewers, apiuser)
842 862
843 863 reviewers_changes['added'] = sorted(
844 864 [get_user_or_error(n).username for n in added_reviewers])
845 865 reviewers_changes['removed'] = sorted(
846 866 [get_user_or_error(n).username for n in removed_reviewers])
847 867 Session().commit()
848 868
849 869 data = {
850 870 'msg': 'Updated pull request `{}`'.format(
851 871 pull_request.pull_request_id),
852 872 'pull_request': pull_request.get_api_data(),
853 873 'updated_commits': commit_changes,
854 874 'updated_reviewers': reviewers_changes
855 875 }
856 876
857 877 return data
858 878
859 879
860 880 @jsonrpc_method()
861 881 def close_pull_request(
862 882 request, apiuser, pullrequestid, repoid=Optional(None),
863 883 userid=Optional(OAttr('apiuser')), message=Optional('')):
864 884 """
865 885 Close the pull request specified by `pullrequestid`.
866 886
867 887 :param apiuser: This is filled automatically from the |authtoken|.
868 888 :type apiuser: AuthUser
869 889 :param repoid: Repository name or repository ID to which the pull
870 890 request belongs.
871 891 :type repoid: str or int
872 892 :param pullrequestid: ID of the pull request to be closed.
873 893 :type pullrequestid: int
874 894 :param userid: Close the pull request as this user.
875 895 :type userid: Optional(str or int)
876 896 :param message: Optional message to close the Pull Request with. If not
877 897 specified it will be generated automatically.
878 898 :type message: Optional(str)
879 899
880 900 Example output:
881 901
882 902 .. code-block:: bash
883 903
884 904 "id": <id_given_in_input>,
885 905 "result": {
886 906 "pull_request_id": "<int>",
887 907 "close_status": "<str:status_lbl>,
888 908 "closed": "<bool>"
889 909 },
890 910 "error": null
891 911
892 912 """
893 913 _ = request.translate
894 914
895 915 pull_request = get_pull_request_or_error(pullrequestid)
896 916 if Optional.extract(repoid):
897 917 repo = get_repo_or_error(repoid)
898 918 else:
899 919 repo = pull_request.target_repo
900 920
901 921 if not isinstance(userid, Optional):
902 922 if (has_superadmin_permission(apiuser) or
903 923 HasRepoPermissionAnyApi('repository.admin')(
904 924 user=apiuser, repo_name=repo.repo_name)):
905 925 apiuser = get_user_or_error(userid)
906 926 else:
907 927 raise JSONRPCError('userid is not the same as your user')
908 928
909 929 if pull_request.is_closed():
910 930 raise JSONRPCError(
911 931 'pull request `%s` is already closed' % (pullrequestid,))
912 932
913 933 # only owner or admin or person with write permissions
914 934 allowed_to_close = PullRequestModel().check_user_update(
915 935 pull_request, apiuser, api=True)
916 936
917 937 if not allowed_to_close:
918 938 raise JSONRPCError(
919 939 'pull request `%s` close failed, no permission to close.' % (
920 940 pullrequestid,))
921 941
922 942 # message we're using to close the PR, else it's automatically generated
923 943 message = Optional.extract(message)
924 944
925 945 # finally close the PR, with proper message comment
926 946 comment, status = PullRequestModel().close_pull_request_with_comment(
927 947 pull_request, apiuser, repo, message=message, auth_user=apiuser)
928 948 status_lbl = ChangesetStatus.get_status_lbl(status)
929 949
930 950 Session().commit()
931 951
932 952 data = {
933 953 'pull_request_id': pull_request.pull_request_id,
934 954 'close_status': status_lbl,
935 955 'closed': True,
936 956 }
937 957 return data
@@ -1,1233 +1,1216 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20 import mock
21 21 import pytest
22 22
23 23 import rhodecode
24 24 from rhodecode.lib.vcs.backends.base import MergeResponse, MergeFailureReason
25 25 from rhodecode.lib.vcs.nodes import FileNode
26 26 from rhodecode.lib import helpers as h
27 27 from rhodecode.model.changeset_status import ChangesetStatusModel
28 28 from rhodecode.model.db import (
29 29 PullRequest, ChangesetStatus, UserLog, Notification, ChangesetComment, Repository)
30 30 from rhodecode.model.meta import Session
31 31 from rhodecode.model.pull_request import PullRequestModel
32 32 from rhodecode.model.user import UserModel
33 33 from rhodecode.tests import (
34 34 assert_session_flash, TEST_USER_ADMIN_LOGIN, TEST_USER_REGULAR_LOGIN)
35 35
36 36
37 37 def route_path(name, params=None, **kwargs):
38 38 import urllib
39 39
40 40 base_url = {
41 41 'repo_changelog': '/{repo_name}/changelog',
42 42 'repo_changelog_file': '/{repo_name}/changelog/{commit_id}/{f_path}',
43 43 'pullrequest_show': '/{repo_name}/pull-request/{pull_request_id}',
44 44 'pullrequest_show_all': '/{repo_name}/pull-request',
45 45 'pullrequest_show_all_data': '/{repo_name}/pull-request-data',
46 46 'pullrequest_repo_refs': '/{repo_name}/pull-request/refs/{target_repo_name:.*?[^/]}',
47 47 'pullrequest_repo_targets': '/{repo_name}/pull-request/repo-destinations',
48 48 'pullrequest_new': '/{repo_name}/pull-request/new',
49 49 'pullrequest_create': '/{repo_name}/pull-request/create',
50 50 'pullrequest_update': '/{repo_name}/pull-request/{pull_request_id}/update',
51 51 'pullrequest_merge': '/{repo_name}/pull-request/{pull_request_id}/merge',
52 52 'pullrequest_delete': '/{repo_name}/pull-request/{pull_request_id}/delete',
53 53 'pullrequest_comment_create': '/{repo_name}/pull-request/{pull_request_id}/comment',
54 54 'pullrequest_comment_delete': '/{repo_name}/pull-request/{pull_request_id}/comment/{comment_id}/delete',
55 55 }[name].format(**kwargs)
56 56
57 57 if params:
58 58 base_url = '{}?{}'.format(base_url, urllib.urlencode(params))
59 59 return base_url
60 60
61 61
62 62 @pytest.mark.usefixtures('app', 'autologin_user')
63 63 @pytest.mark.backends("git", "hg")
64 64 class TestPullrequestsView(object):
65 65
66 66 def test_index(self, backend):
67 67 self.app.get(route_path(
68 68 'pullrequest_new',
69 69 repo_name=backend.repo_name))
70 70
71 71 def test_option_menu_create_pull_request_exists(self, backend):
72 72 repo_name = backend.repo_name
73 73 response = self.app.get(h.route_path('repo_summary', repo_name=repo_name))
74 74
75 75 create_pr_link = '<a href="%s">Create Pull Request</a>' % route_path(
76 76 'pullrequest_new', repo_name=repo_name)
77 77 response.mustcontain(create_pr_link)
78 78
79 79 def test_create_pr_form_with_raw_commit_id(self, backend):
80 80 repo = backend.repo
81 81
82 82 self.app.get(
83 83 route_path('pullrequest_new', repo_name=repo.repo_name,
84 84 commit=repo.get_commit().raw_id),
85 85 status=200)
86 86
87 87 @pytest.mark.parametrize('pr_merge_enabled', [True, False])
88 88 @pytest.mark.parametrize('range_diff', ["0", "1"])
89 89 def test_show(self, pr_util, pr_merge_enabled, range_diff):
90 90 pull_request = pr_util.create_pull_request(
91 91 mergeable=pr_merge_enabled, enable_notifications=False)
92 92
93 93 response = self.app.get(route_path(
94 94 'pullrequest_show',
95 95 repo_name=pull_request.target_repo.scm_instance().name,
96 96 pull_request_id=pull_request.pull_request_id,
97 97 params={'range-diff': range_diff}))
98 98
99 99 for commit_id in pull_request.revisions:
100 100 response.mustcontain(commit_id)
101 101
102 102 assert pull_request.target_ref_parts.type in response
103 103 assert pull_request.target_ref_parts.name in response
104 104 target_clone_url = pull_request.target_repo.clone_url()
105 105 assert target_clone_url in response
106 106
107 107 assert 'class="pull-request-merge"' in response
108 108 if pr_merge_enabled:
109 109 response.mustcontain('Pull request reviewer approval is pending')
110 110 else:
111 111 response.mustcontain('Server-side pull request merging is disabled.')
112 112
113 113 if range_diff == "1":
114 114 response.mustcontain('Turn off: Show the diff as commit range')
115 115
116 116 def test_close_status_visibility(self, pr_util, user_util, csrf_token):
117 117 # Logout
118 118 response = self.app.post(
119 119 h.route_path('logout'),
120 120 params={'csrf_token': csrf_token})
121 121 # Login as regular user
122 122 response = self.app.post(h.route_path('login'),
123 123 {'username': TEST_USER_REGULAR_LOGIN,
124 124 'password': 'test12'})
125 125
126 126 pull_request = pr_util.create_pull_request(
127 127 author=TEST_USER_REGULAR_LOGIN)
128 128
129 129 response = self.app.get(route_path(
130 130 'pullrequest_show',
131 131 repo_name=pull_request.target_repo.scm_instance().name,
132 132 pull_request_id=pull_request.pull_request_id))
133 133
134 134 response.mustcontain('Server-side pull request merging is disabled.')
135 135
136 136 assert_response = response.assert_response()
137 137 # for regular user without a merge permissions, we don't see it
138 138 assert_response.no_element_exists('#close-pull-request-action')
139 139
140 140 user_util.grant_user_permission_to_repo(
141 141 pull_request.target_repo,
142 142 UserModel().get_by_username(TEST_USER_REGULAR_LOGIN),
143 143 'repository.write')
144 144 response = self.app.get(route_path(
145 145 'pullrequest_show',
146 146 repo_name=pull_request.target_repo.scm_instance().name,
147 147 pull_request_id=pull_request.pull_request_id))
148 148
149 149 response.mustcontain('Server-side pull request merging is disabled.')
150 150
151 151 assert_response = response.assert_response()
152 152 # now regular user has a merge permissions, we have CLOSE button
153 153 assert_response.one_element_exists('#close-pull-request-action')
154 154
155 155 def test_show_invalid_commit_id(self, pr_util):
156 156 # Simulating invalid revisions which will cause a lookup error
157 157 pull_request = pr_util.create_pull_request()
158 158 pull_request.revisions = ['invalid']
159 159 Session().add(pull_request)
160 160 Session().commit()
161 161
162 162 response = self.app.get(route_path(
163 163 'pullrequest_show',
164 164 repo_name=pull_request.target_repo.scm_instance().name,
165 165 pull_request_id=pull_request.pull_request_id))
166 166
167 167 for commit_id in pull_request.revisions:
168 168 response.mustcontain(commit_id)
169 169
170 170 def test_show_invalid_source_reference(self, pr_util):
171 171 pull_request = pr_util.create_pull_request()
172 172 pull_request.source_ref = 'branch:b:invalid'
173 173 Session().add(pull_request)
174 174 Session().commit()
175 175
176 176 self.app.get(route_path(
177 177 'pullrequest_show',
178 178 repo_name=pull_request.target_repo.scm_instance().name,
179 179 pull_request_id=pull_request.pull_request_id))
180 180
181 181 def test_edit_title_description(self, pr_util, csrf_token):
182 182 pull_request = pr_util.create_pull_request()
183 183 pull_request_id = pull_request.pull_request_id
184 184
185 185 response = self.app.post(
186 186 route_path('pullrequest_update',
187 187 repo_name=pull_request.target_repo.repo_name,
188 188 pull_request_id=pull_request_id),
189 189 params={
190 190 'edit_pull_request': 'true',
191 191 'title': 'New title',
192 192 'description': 'New description',
193 193 'csrf_token': csrf_token})
194 194
195 195 assert_session_flash(
196 196 response, u'Pull request title & description updated.',
197 197 category='success')
198 198
199 199 pull_request = PullRequest.get(pull_request_id)
200 200 assert pull_request.title == 'New title'
201 201 assert pull_request.description == 'New description'
202 202
203 203 def test_edit_title_description_closed(self, pr_util, csrf_token):
204 204 pull_request = pr_util.create_pull_request()
205 205 pull_request_id = pull_request.pull_request_id
206 206 repo_name = pull_request.target_repo.repo_name
207 207 pr_util.close()
208 208
209 209 response = self.app.post(
210 210 route_path('pullrequest_update',
211 211 repo_name=repo_name, pull_request_id=pull_request_id),
212 212 params={
213 213 'edit_pull_request': 'true',
214 214 'title': 'New title',
215 215 'description': 'New description',
216 216 'csrf_token': csrf_token}, status=200)
217 217 assert_session_flash(
218 218 response, u'Cannot update closed pull requests.',
219 219 category='error')
220 220
221 221 def test_update_invalid_source_reference(self, pr_util, csrf_token):
222 222 from rhodecode.lib.vcs.backends.base import UpdateFailureReason
223 223
224 224 pull_request = pr_util.create_pull_request()
225 225 pull_request.source_ref = 'branch:invalid-branch:invalid-commit-id'
226 226 Session().add(pull_request)
227 227 Session().commit()
228 228
229 229 pull_request_id = pull_request.pull_request_id
230 230
231 231 response = self.app.post(
232 232 route_path('pullrequest_update',
233 233 repo_name=pull_request.target_repo.repo_name,
234 234 pull_request_id=pull_request_id),
235 235 params={'update_commits': 'true', 'csrf_token': csrf_token})
236 236
237 237 expected_msg = str(PullRequestModel.UPDATE_STATUS_MESSAGES[
238 238 UpdateFailureReason.MISSING_SOURCE_REF])
239 239 assert_session_flash(response, expected_msg, category='error')
240 240
241 241 def test_missing_target_reference(self, pr_util, csrf_token):
242 242 from rhodecode.lib.vcs.backends.base import MergeFailureReason
243 243 pull_request = pr_util.create_pull_request(
244 244 approved=True, mergeable=True)
245 245 unicode_reference = u'branch:invalid-branch:invalid-commit-id'
246 246 pull_request.target_ref = unicode_reference
247 247 Session().add(pull_request)
248 248 Session().commit()
249 249
250 250 pull_request_id = pull_request.pull_request_id
251 251 pull_request_url = route_path(
252 252 'pullrequest_show',
253 253 repo_name=pull_request.target_repo.repo_name,
254 254 pull_request_id=pull_request_id)
255 255
256 256 response = self.app.get(pull_request_url)
257 257 target_ref_id = 'invalid-branch'
258 258 merge_resp = MergeResponse(
259 259 True, True, '', MergeFailureReason.MISSING_TARGET_REF,
260 260 metadata={'target_ref': PullRequest.unicode_to_reference(unicode_reference)})
261 261 response.assert_response().element_contains(
262 262 'span[data-role="merge-message"]', merge_resp.merge_status_message)
263 263
264 264 def test_comment_and_close_pull_request_custom_message_approved(
265 265 self, pr_util, csrf_token, xhr_header):
266 266
267 267 pull_request = pr_util.create_pull_request(approved=True)
268 268 pull_request_id = pull_request.pull_request_id
269 269 author = pull_request.user_id
270 270 repo = pull_request.target_repo.repo_id
271 271
272 272 self.app.post(
273 273 route_path('pullrequest_comment_create',
274 274 repo_name=pull_request.target_repo.scm_instance().name,
275 275 pull_request_id=pull_request_id),
276 276 params={
277 277 'close_pull_request': '1',
278 278 'text': 'Closing a PR',
279 279 'csrf_token': csrf_token},
280 280 extra_environ=xhr_header,)
281 281
282 282 journal = UserLog.query()\
283 283 .filter(UserLog.user_id == author)\
284 284 .filter(UserLog.repository_id == repo) \
285 285 .order_by('user_log_id') \
286 286 .all()
287 287 assert journal[-1].action == 'repo.pull_request.close'
288 288
289 289 pull_request = PullRequest.get(pull_request_id)
290 290 assert pull_request.is_closed()
291 291
292 292 status = ChangesetStatusModel().get_status(
293 293 pull_request.source_repo, pull_request=pull_request)
294 294 assert status == ChangesetStatus.STATUS_APPROVED
295 295 comments = ChangesetComment().query() \
296 296 .filter(ChangesetComment.pull_request == pull_request) \
297 297 .order_by(ChangesetComment.comment_id.asc())\
298 298 .all()
299 299 assert comments[-1].text == 'Closing a PR'
300 300
301 301 def test_comment_force_close_pull_request_rejected(
302 302 self, pr_util, csrf_token, xhr_header):
303 303 pull_request = pr_util.create_pull_request()
304 304 pull_request_id = pull_request.pull_request_id
305 305 PullRequestModel().update_reviewers(
306 306 pull_request_id, [(1, ['reason'], False, []), (2, ['reason2'], False, [])],
307 307 pull_request.author)
308 308 author = pull_request.user_id
309 309 repo = pull_request.target_repo.repo_id
310 310
311 311 self.app.post(
312 312 route_path('pullrequest_comment_create',
313 313 repo_name=pull_request.target_repo.scm_instance().name,
314 314 pull_request_id=pull_request_id),
315 315 params={
316 316 'close_pull_request': '1',
317 317 'csrf_token': csrf_token},
318 318 extra_environ=xhr_header)
319 319
320 320 pull_request = PullRequest.get(pull_request_id)
321 321
322 322 journal = UserLog.query()\
323 323 .filter(UserLog.user_id == author, UserLog.repository_id == repo) \
324 324 .order_by('user_log_id') \
325 325 .all()
326 326 assert journal[-1].action == 'repo.pull_request.close'
327 327
328 328 # check only the latest status, not the review status
329 329 status = ChangesetStatusModel().get_status(
330 330 pull_request.source_repo, pull_request=pull_request)
331 331 assert status == ChangesetStatus.STATUS_REJECTED
332 332
333 333 def test_comment_and_close_pull_request(
334 334 self, pr_util, csrf_token, xhr_header):
335 335 pull_request = pr_util.create_pull_request()
336 336 pull_request_id = pull_request.pull_request_id
337 337
338 338 response = self.app.post(
339 339 route_path('pullrequest_comment_create',
340 340 repo_name=pull_request.target_repo.scm_instance().name,
341 341 pull_request_id=pull_request.pull_request_id),
342 342 params={
343 343 'close_pull_request': 'true',
344 344 'csrf_token': csrf_token},
345 345 extra_environ=xhr_header)
346 346
347 347 assert response.json
348 348
349 349 pull_request = PullRequest.get(pull_request_id)
350 350 assert pull_request.is_closed()
351 351
352 352 # check only the latest status, not the review status
353 353 status = ChangesetStatusModel().get_status(
354 354 pull_request.source_repo, pull_request=pull_request)
355 355 assert status == ChangesetStatus.STATUS_REJECTED
356 356
357 357 def test_create_pull_request(self, backend, csrf_token):
358 358 commits = [
359 359 {'message': 'ancestor'},
360 360 {'message': 'change'},
361 361 {'message': 'change2'},
362 362 ]
363 363 commit_ids = backend.create_master_repo(commits)
364 364 target = backend.create_repo(heads=['ancestor'])
365 365 source = backend.create_repo(heads=['change2'])
366 366
367 367 response = self.app.post(
368 368 route_path('pullrequest_create', repo_name=source.repo_name),
369 369 [
370 370 ('source_repo', source.repo_name),
371 371 ('source_ref', 'branch:default:' + commit_ids['change2']),
372 372 ('target_repo', target.repo_name),
373 373 ('target_ref', 'branch:default:' + commit_ids['ancestor']),
374 374 ('common_ancestor', commit_ids['ancestor']),
375 375 ('pullrequest_title', 'Title'),
376 376 ('pullrequest_desc', 'Description'),
377 377 ('description_renderer', 'markdown'),
378 378 ('__start__', 'review_members:sequence'),
379 379 ('__start__', 'reviewer:mapping'),
380 380 ('user_id', '1'),
381 381 ('__start__', 'reasons:sequence'),
382 382 ('reason', 'Some reason'),
383 383 ('__end__', 'reasons:sequence'),
384 384 ('__start__', 'rules:sequence'),
385 385 ('__end__', 'rules:sequence'),
386 386 ('mandatory', 'False'),
387 387 ('__end__', 'reviewer:mapping'),
388 388 ('__end__', 'review_members:sequence'),
389 389 ('__start__', 'revisions:sequence'),
390 390 ('revisions', commit_ids['change']),
391 391 ('revisions', commit_ids['change2']),
392 392 ('__end__', 'revisions:sequence'),
393 393 ('user', ''),
394 394 ('csrf_token', csrf_token),
395 395 ],
396 396 status=302)
397 397
398 398 location = response.headers['Location']
399 399 pull_request_id = location.rsplit('/', 1)[1]
400 400 assert pull_request_id != 'new'
401 401 pull_request = PullRequest.get(int(pull_request_id))
402 402
403 403 # check that we have now both revisions
404 404 assert pull_request.revisions == [commit_ids['change2'], commit_ids['change']]
405 405 assert pull_request.source_ref == 'branch:default:' + commit_ids['change2']
406 406 expected_target_ref = 'branch:default:' + commit_ids['ancestor']
407 407 assert pull_request.target_ref == expected_target_ref
408 408
409 409 def test_reviewer_notifications(self, backend, csrf_token):
410 410 # We have to use the app.post for this test so it will create the
411 411 # notifications properly with the new PR
412 412 commits = [
413 413 {'message': 'ancestor',
414 414 'added': [FileNode('file_A', content='content_of_ancestor')]},
415 415 {'message': 'change',
416 416 'added': [FileNode('file_a', content='content_of_change')]},
417 417 {'message': 'change-child'},
418 418 {'message': 'ancestor-child', 'parents': ['ancestor'],
419 419 'added': [
420 420 FileNode('file_B', content='content_of_ancestor_child')]},
421 421 {'message': 'ancestor-child-2'},
422 422 ]
423 423 commit_ids = backend.create_master_repo(commits)
424 424 target = backend.create_repo(heads=['ancestor-child'])
425 425 source = backend.create_repo(heads=['change'])
426 426
427 427 response = self.app.post(
428 428 route_path('pullrequest_create', repo_name=source.repo_name),
429 429 [
430 430 ('source_repo', source.repo_name),
431 431 ('source_ref', 'branch:default:' + commit_ids['change']),
432 432 ('target_repo', target.repo_name),
433 433 ('target_ref', 'branch:default:' + commit_ids['ancestor-child']),
434 434 ('common_ancestor', commit_ids['ancestor']),
435 435 ('pullrequest_title', 'Title'),
436 436 ('pullrequest_desc', 'Description'),
437 437 ('description_renderer', 'markdown'),
438 438 ('__start__', 'review_members:sequence'),
439 439 ('__start__', 'reviewer:mapping'),
440 440 ('user_id', '2'),
441 441 ('__start__', 'reasons:sequence'),
442 442 ('reason', 'Some reason'),
443 443 ('__end__', 'reasons:sequence'),
444 444 ('__start__', 'rules:sequence'),
445 445 ('__end__', 'rules:sequence'),
446 446 ('mandatory', 'False'),
447 447 ('__end__', 'reviewer:mapping'),
448 448 ('__end__', 'review_members:sequence'),
449 449 ('__start__', 'revisions:sequence'),
450 450 ('revisions', commit_ids['change']),
451 451 ('__end__', 'revisions:sequence'),
452 452 ('user', ''),
453 453 ('csrf_token', csrf_token),
454 454 ],
455 455 status=302)
456 456
457 457 location = response.headers['Location']
458 458
459 459 pull_request_id = location.rsplit('/', 1)[1]
460 460 assert pull_request_id != 'new'
461 461 pull_request = PullRequest.get(int(pull_request_id))
462 462
463 463 # Check that a notification was made
464 464 notifications = Notification.query()\
465 465 .filter(Notification.created_by == pull_request.author.user_id,
466 466 Notification.type_ == Notification.TYPE_PULL_REQUEST,
467 467 Notification.subject.contains(
468 468 "wants you to review pull request #%s" % pull_request_id))
469 469 assert len(notifications.all()) == 1
470 470
471 471 # Change reviewers and check that a notification was made
472 472 PullRequestModel().update_reviewers(
473 473 pull_request.pull_request_id, [(1, [], False, [])],
474 474 pull_request.author)
475 475 assert len(notifications.all()) == 2
476 476
477 477 def test_create_pull_request_stores_ancestor_commit_id(self, backend,
478 478 csrf_token):
479 479 commits = [
480 480 {'message': 'ancestor',
481 481 'added': [FileNode('file_A', content='content_of_ancestor')]},
482 482 {'message': 'change',
483 483 'added': [FileNode('file_a', content='content_of_change')]},
484 484 {'message': 'change-child'},
485 485 {'message': 'ancestor-child', 'parents': ['ancestor'],
486 486 'added': [
487 487 FileNode('file_B', content='content_of_ancestor_child')]},
488 488 {'message': 'ancestor-child-2'},
489 489 ]
490 490 commit_ids = backend.create_master_repo(commits)
491 491 target = backend.create_repo(heads=['ancestor-child'])
492 492 source = backend.create_repo(heads=['change'])
493 493
494 494 response = self.app.post(
495 495 route_path('pullrequest_create', repo_name=source.repo_name),
496 496 [
497 497 ('source_repo', source.repo_name),
498 498 ('source_ref', 'branch:default:' + commit_ids['change']),
499 499 ('target_repo', target.repo_name),
500 500 ('target_ref', 'branch:default:' + commit_ids['ancestor-child']),
501 501 ('common_ancestor', commit_ids['ancestor']),
502 502 ('pullrequest_title', 'Title'),
503 503 ('pullrequest_desc', 'Description'),
504 504 ('description_renderer', 'markdown'),
505 505 ('__start__', 'review_members:sequence'),
506 506 ('__start__', 'reviewer:mapping'),
507 507 ('user_id', '1'),
508 508 ('__start__', 'reasons:sequence'),
509 509 ('reason', 'Some reason'),
510 510 ('__end__', 'reasons:sequence'),
511 511 ('__start__', 'rules:sequence'),
512 512 ('__end__', 'rules:sequence'),
513 513 ('mandatory', 'False'),
514 514 ('__end__', 'reviewer:mapping'),
515 515 ('__end__', 'review_members:sequence'),
516 516 ('__start__', 'revisions:sequence'),
517 517 ('revisions', commit_ids['change']),
518 518 ('__end__', 'revisions:sequence'),
519 519 ('user', ''),
520 520 ('csrf_token', csrf_token),
521 521 ],
522 522 status=302)
523 523
524 524 location = response.headers['Location']
525 525
526 526 pull_request_id = location.rsplit('/', 1)[1]
527 527 assert pull_request_id != 'new'
528 528 pull_request = PullRequest.get(int(pull_request_id))
529 529
530 530 # target_ref has to point to the ancestor's commit_id in order to
531 531 # show the correct diff
532 532 expected_target_ref = 'branch:default:' + commit_ids['ancestor']
533 533 assert pull_request.target_ref == expected_target_ref
534 534
535 535 # Check generated diff contents
536 536 response = response.follow()
537 537 assert 'content_of_ancestor' not in response.body
538 538 assert 'content_of_ancestor-child' not in response.body
539 539 assert 'content_of_change' in response.body
540 540
541 541 def test_merge_pull_request_enabled(self, pr_util, csrf_token):
542 542 # Clear any previous calls to rcextensions
543 543 rhodecode.EXTENSIONS.calls.clear()
544 544
545 545 pull_request = pr_util.create_pull_request(
546 546 approved=True, mergeable=True)
547 547 pull_request_id = pull_request.pull_request_id
548 548 repo_name = pull_request.target_repo.scm_instance().name,
549 549
550 550 response = self.app.post(
551 551 route_path('pullrequest_merge',
552 552 repo_name=str(repo_name[0]),
553 553 pull_request_id=pull_request_id),
554 554 params={'csrf_token': csrf_token}).follow()
555 555
556 556 pull_request = PullRequest.get(pull_request_id)
557 557
558 558 assert response.status_int == 200
559 559 assert pull_request.is_closed()
560 560 assert_pull_request_status(
561 561 pull_request, ChangesetStatus.STATUS_APPROVED)
562 562
563 563 # Check the relevant log entries were added
564 564 user_logs = UserLog.query().order_by('-user_log_id').limit(3)
565 565 actions = [log.action for log in user_logs]
566 566 pr_commit_ids = PullRequestModel()._get_commit_ids(pull_request)
567 567 expected_actions = [
568 568 u'repo.pull_request.close',
569 569 u'repo.pull_request.merge',
570 570 u'repo.pull_request.comment.create'
571 571 ]
572 572 assert actions == expected_actions
573 573
574 574 user_logs = UserLog.query().order_by('-user_log_id').limit(4)
575 575 actions = [log for log in user_logs]
576 576 assert actions[-1].action == 'user.push'
577 577 assert actions[-1].action_data['commit_ids'] == pr_commit_ids
578 578
579 579 # Check post_push rcextension was really executed
580 580 push_calls = rhodecode.EXTENSIONS.calls['_push_hook']
581 581 assert len(push_calls) == 1
582 582 unused_last_call_args, last_call_kwargs = push_calls[0]
583 583 assert last_call_kwargs['action'] == 'push'
584 584 assert last_call_kwargs['commit_ids'] == pr_commit_ids
585 585
586 586 def test_merge_pull_request_disabled(self, pr_util, csrf_token):
587 587 pull_request = pr_util.create_pull_request(mergeable=False)
588 588 pull_request_id = pull_request.pull_request_id
589 589 pull_request = PullRequest.get(pull_request_id)
590 590
591 591 response = self.app.post(
592 592 route_path('pullrequest_merge',
593 593 repo_name=pull_request.target_repo.scm_instance().name,
594 594 pull_request_id=pull_request.pull_request_id),
595 595 params={'csrf_token': csrf_token}).follow()
596 596
597 597 assert response.status_int == 200
598 598 response.mustcontain(
599 599 'Merge is not currently possible because of below failed checks.')
600 600 response.mustcontain('Server-side pull request merging is disabled.')
601 601
602 602 @pytest.mark.skip_backends('svn')
603 603 def test_merge_pull_request_not_approved(self, pr_util, csrf_token):
604 604 pull_request = pr_util.create_pull_request(mergeable=True)
605 605 pull_request_id = pull_request.pull_request_id
606 606 repo_name = pull_request.target_repo.scm_instance().name
607 607
608 608 response = self.app.post(
609 609 route_path('pullrequest_merge',
610 610 repo_name=repo_name, pull_request_id=pull_request_id),
611 611 params={'csrf_token': csrf_token}).follow()
612 612
613 613 assert response.status_int == 200
614 614
615 615 response.mustcontain(
616 616 'Merge is not currently possible because of below failed checks.')
617 617 response.mustcontain('Pull request reviewer approval is pending.')
618 618
619 619 def test_merge_pull_request_renders_failure_reason(
620 620 self, user_regular, csrf_token, pr_util):
621 621 pull_request = pr_util.create_pull_request(mergeable=True, approved=True)
622 622 pull_request_id = pull_request.pull_request_id
623 623 repo_name = pull_request.target_repo.scm_instance().name
624 624
625 625 merge_resp = MergeResponse(True, False, 'STUB_COMMIT_ID',
626 626 MergeFailureReason.PUSH_FAILED,
627 627 metadata={'target': 'shadow repo',
628 628 'merge_commit': 'xxx'})
629 629 model_patcher = mock.patch.multiple(
630 630 PullRequestModel,
631 631 merge_repo=mock.Mock(return_value=merge_resp),
632 632 merge_status=mock.Mock(return_value=(True, 'WRONG_MESSAGE')))
633 633
634 634 with model_patcher:
635 635 response = self.app.post(
636 636 route_path('pullrequest_merge',
637 637 repo_name=repo_name,
638 638 pull_request_id=pull_request_id),
639 639 params={'csrf_token': csrf_token}, status=302)
640 640
641 641 merge_resp = MergeResponse(True, True, '', MergeFailureReason.PUSH_FAILED,
642 642 metadata={'target': 'shadow repo',
643 643 'merge_commit': 'xxx'})
644 644 assert_session_flash(response, merge_resp.merge_status_message)
645 645
646 646 def test_update_source_revision(self, backend, csrf_token):
647 647 commits = [
648 648 {'message': 'ancestor'},
649 649 {'message': 'change'},
650 650 {'message': 'change-2'},
651 651 ]
652 652 commit_ids = backend.create_master_repo(commits)
653 653 target = backend.create_repo(heads=['ancestor'])
654 654 source = backend.create_repo(heads=['change'])
655 655
656 656 # create pr from a in source to A in target
657 657 pull_request = PullRequest()
658
658 659 pull_request.source_repo = source
659 # TODO: johbo: Make sure that we write the source ref this way!
660 660 pull_request.source_ref = 'branch:{branch}:{commit_id}'.format(
661 661 branch=backend.default_branch_name, commit_id=commit_ids['change'])
662
662 663 pull_request.target_repo = target
663
664 664 pull_request.target_ref = 'branch:{branch}:{commit_id}'.format(
665 branch=backend.default_branch_name,
666 commit_id=commit_ids['ancestor'])
665 branch=backend.default_branch_name, commit_id=commit_ids['ancestor'])
666
667 667 pull_request.revisions = [commit_ids['change']]
668 668 pull_request.title = u"Test"
669 669 pull_request.description = u"Description"
670 pull_request.author = UserModel().get_by_username(
671 TEST_USER_ADMIN_LOGIN)
670 pull_request.author = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
671 pull_request.pull_request_state = PullRequest.STATE_CREATED
672 672 Session().add(pull_request)
673 673 Session().commit()
674 674 pull_request_id = pull_request.pull_request_id
675 675
676 676 # source has ancestor - change - change-2
677 677 backend.pull_heads(source, heads=['change-2'])
678 678
679 679 # update PR
680 680 self.app.post(
681 681 route_path('pullrequest_update',
682 repo_name=target.repo_name,
683 pull_request_id=pull_request_id),
684 params={'update_commits': 'true',
685 'csrf_token': csrf_token})
682 repo_name=target.repo_name, pull_request_id=pull_request_id),
683 params={'update_commits': 'true', 'csrf_token': csrf_token})
684
685 response = self.app.get(
686 route_path('pullrequest_show',
687 repo_name=target.repo_name,
688 pull_request_id=pull_request.pull_request_id))
689
690 assert response.status_int == 200
691 assert 'Pull request updated to' in response.body
692 assert 'with 1 added, 0 removed commits.' in response.body
686 693
687 694 # check that we have now both revisions
688 695 pull_request = PullRequest.get(pull_request_id)
689 assert pull_request.revisions == [
690 commit_ids['change-2'], commit_ids['change']]
691
692 # TODO: johbo: this should be a test on its own
693 response = self.app.get(route_path(
694 'pullrequest_new',
695 repo_name=target.repo_name))
696 assert response.status_int == 200
697 assert 'Pull request updated to' in response.body
698 assert 'with 1 added, 0 removed commits.' in response.body
696 assert pull_request.revisions == [commit_ids['change-2'], commit_ids['change']]
699 697
700 698 def test_update_target_revision(self, backend, csrf_token):
701 699 commits = [
702 700 {'message': 'ancestor'},
703 701 {'message': 'change'},
704 702 {'message': 'ancestor-new', 'parents': ['ancestor']},
705 703 {'message': 'change-rebased'},
706 704 ]
707 705 commit_ids = backend.create_master_repo(commits)
708 706 target = backend.create_repo(heads=['ancestor'])
709 707 source = backend.create_repo(heads=['change'])
710 708
711 709 # create pr from a in source to A in target
712 710 pull_request = PullRequest()
711
713 712 pull_request.source_repo = source
714 # TODO: johbo: Make sure that we write the source ref this way!
715 713 pull_request.source_ref = 'branch:{branch}:{commit_id}'.format(
716 714 branch=backend.default_branch_name, commit_id=commit_ids['change'])
715
717 716 pull_request.target_repo = target
718 # TODO: johbo: Target ref should be branch based, since tip can jump
719 # from branch to branch
720 717 pull_request.target_ref = 'branch:{branch}:{commit_id}'.format(
721 branch=backend.default_branch_name,
722 commit_id=commit_ids['ancestor'])
718 branch=backend.default_branch_name, commit_id=commit_ids['ancestor'])
719
723 720 pull_request.revisions = [commit_ids['change']]
724 721 pull_request.title = u"Test"
725 722 pull_request.description = u"Description"
726 pull_request.author = UserModel().get_by_username(
727 TEST_USER_ADMIN_LOGIN)
723 pull_request.author = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
724 pull_request.pull_request_state = PullRequest.STATE_CREATED
725
728 726 Session().add(pull_request)
729 727 Session().commit()
730 728 pull_request_id = pull_request.pull_request_id
731 729
732 730 # target has ancestor - ancestor-new
733 731 # source has ancestor - ancestor-new - change-rebased
734 732 backend.pull_heads(target, heads=['ancestor-new'])
735 733 backend.pull_heads(source, heads=['change-rebased'])
736 734
737 735 # update PR
738 736 self.app.post(
739 737 route_path('pullrequest_update',
740 repo_name=target.repo_name,
741 pull_request_id=pull_request_id),
742 params={'update_commits': 'true',
743 'csrf_token': csrf_token},
738 repo_name=target.repo_name,
739 pull_request_id=pull_request_id),
740 params={'update_commits': 'true', 'csrf_token': csrf_token},
744 741 status=200)
745 742
746 743 # check that we have now both revisions
747 744 pull_request = PullRequest.get(pull_request_id)
748 745 assert pull_request.revisions == [commit_ids['change-rebased']]
749 746 assert pull_request.target_ref == 'branch:{branch}:{commit_id}'.format(
750 branch=backend.default_branch_name,
751 commit_id=commit_ids['ancestor-new'])
747 branch=backend.default_branch_name, commit_id=commit_ids['ancestor-new'])
752 748
753 # TODO: johbo: This should be a test on its own
754 response = self.app.get(route_path(
755 'pullrequest_new',
756 repo_name=target.repo_name))
749 response = self.app.get(
750 route_path('pullrequest_show',
751 repo_name=target.repo_name,
752 pull_request_id=pull_request.pull_request_id))
757 753 assert response.status_int == 200
758 754 assert 'Pull request updated to' in response.body
759 755 assert 'with 1 added, 1 removed commits.' in response.body
760 756
761 757 def test_update_target_revision_with_removal_of_1_commit_git(self, backend_git, csrf_token):
762 758 backend = backend_git
763 759 commits = [
764 760 {'message': 'master-commit-1'},
765 761 {'message': 'master-commit-2-change-1'},
766 762 {'message': 'master-commit-3-change-2'},
767 763
768 764 {'message': 'feat-commit-1', 'parents': ['master-commit-1']},
769 765 {'message': 'feat-commit-2'},
770 766 ]
771 767 commit_ids = backend.create_master_repo(commits)
772 768 target = backend.create_repo(heads=['master-commit-3-change-2'])
773 769 source = backend.create_repo(heads=['feat-commit-2'])
774 770
775 771 # create pr from a in source to A in target
776 772 pull_request = PullRequest()
777 773 pull_request.source_repo = source
778 # TODO: johbo: Make sure that we write the source ref this way!
774
779 775 pull_request.source_ref = 'branch:{branch}:{commit_id}'.format(
780 776 branch=backend.default_branch_name,
781 777 commit_id=commit_ids['master-commit-3-change-2'])
782 778
783 779 pull_request.target_repo = target
784 # TODO: johbo: Target ref should be branch based, since tip can jump
785 # from branch to branch
786 780 pull_request.target_ref = 'branch:{branch}:{commit_id}'.format(
787 branch=backend.default_branch_name,
788 commit_id=commit_ids['feat-commit-2'])
781 branch=backend.default_branch_name, commit_id=commit_ids['feat-commit-2'])
789 782
790 783 pull_request.revisions = [
791 784 commit_ids['feat-commit-1'],
792 785 commit_ids['feat-commit-2']
793 786 ]
794 787 pull_request.title = u"Test"
795 788 pull_request.description = u"Description"
796 pull_request.author = UserModel().get_by_username(
797 TEST_USER_ADMIN_LOGIN)
789 pull_request.author = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
790 pull_request.pull_request_state = PullRequest.STATE_CREATED
798 791 Session().add(pull_request)
799 792 Session().commit()
800 793 pull_request_id = pull_request.pull_request_id
801 794
802 795 # PR is created, now we simulate a force-push into target,
803 796 # that drops a 2 last commits
804 797 vcsrepo = target.scm_instance()
805 798 vcsrepo.config.clear_section('hooks')
806 799 vcsrepo.run_git_command(['reset', '--soft', 'HEAD~2'])
807 800
808 801 # update PR
809 802 self.app.post(
810 803 route_path('pullrequest_update',
811 804 repo_name=target.repo_name,
812 805 pull_request_id=pull_request_id),
813 params={'update_commits': 'true',
814 'csrf_token': csrf_token},
806 params={'update_commits': 'true', 'csrf_token': csrf_token},
815 807 status=200)
816 808
817 response = self.app.get(route_path(
818 'pullrequest_new',
819 repo_name=target.repo_name))
809 response = self.app.get(route_path('pullrequest_new', repo_name=target.repo_name))
820 810 assert response.status_int == 200
821 811 response.mustcontain('Pull request updated to')
822 812 response.mustcontain('with 0 added, 0 removed commits.')
823 813
824 814 def test_update_of_ancestor_reference(self, backend, csrf_token):
825 815 commits = [
826 816 {'message': 'ancestor'},
827 817 {'message': 'change'},
828 818 {'message': 'change-2'},
829 819 {'message': 'ancestor-new', 'parents': ['ancestor']},
830 820 {'message': 'change-rebased'},
831 821 ]
832 822 commit_ids = backend.create_master_repo(commits)
833 823 target = backend.create_repo(heads=['ancestor'])
834 824 source = backend.create_repo(heads=['change'])
835 825
836 826 # create pr from a in source to A in target
837 827 pull_request = PullRequest()
838 828 pull_request.source_repo = source
839 # TODO: johbo: Make sure that we write the source ref this way!
829
840 830 pull_request.source_ref = 'branch:{branch}:{commit_id}'.format(
841 branch=backend.default_branch_name,
842 commit_id=commit_ids['change'])
831 branch=backend.default_branch_name, commit_id=commit_ids['change'])
843 832 pull_request.target_repo = target
844 # TODO: johbo: Target ref should be branch based, since tip can jump
845 # from branch to branch
846 833 pull_request.target_ref = 'branch:{branch}:{commit_id}'.format(
847 branch=backend.default_branch_name,
848 commit_id=commit_ids['ancestor'])
834 branch=backend.default_branch_name, commit_id=commit_ids['ancestor'])
849 835 pull_request.revisions = [commit_ids['change']]
850 836 pull_request.title = u"Test"
851 837 pull_request.description = u"Description"
852 pull_request.author = UserModel().get_by_username(
853 TEST_USER_ADMIN_LOGIN)
838 pull_request.author = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
839 pull_request.pull_request_state = PullRequest.STATE_CREATED
854 840 Session().add(pull_request)
855 841 Session().commit()
856 842 pull_request_id = pull_request.pull_request_id
857 843
858 844 # target has ancestor - ancestor-new
859 845 # source has ancestor - ancestor-new - change-rebased
860 846 backend.pull_heads(target, heads=['ancestor-new'])
861 847 backend.pull_heads(source, heads=['change-rebased'])
862 848
863 849 # update PR
864 850 self.app.post(
865 851 route_path('pullrequest_update',
866 repo_name=target.repo_name,
867 pull_request_id=pull_request_id),
868 params={'update_commits': 'true',
869 'csrf_token': csrf_token},
852 repo_name=target.repo_name, pull_request_id=pull_request_id),
853 params={'update_commits': 'true', 'csrf_token': csrf_token},
870 854 status=200)
871 855
872 856 # Expect the target reference to be updated correctly
873 857 pull_request = PullRequest.get(pull_request_id)
874 858 assert pull_request.revisions == [commit_ids['change-rebased']]
875 859 expected_target_ref = 'branch:{branch}:{commit_id}'.format(
876 860 branch=backend.default_branch_name,
877 861 commit_id=commit_ids['ancestor-new'])
878 862 assert pull_request.target_ref == expected_target_ref
879 863
880 864 def test_remove_pull_request_branch(self, backend_git, csrf_token):
881 865 branch_name = 'development'
882 866 commits = [
883 867 {'message': 'initial-commit'},
884 868 {'message': 'old-feature'},
885 869 {'message': 'new-feature', 'branch': branch_name},
886 870 ]
887 871 repo = backend_git.create_repo(commits)
888 872 commit_ids = backend_git.commit_ids
889 873
890 874 pull_request = PullRequest()
891 875 pull_request.source_repo = repo
892 876 pull_request.target_repo = repo
893 877 pull_request.source_ref = 'branch:{branch}:{commit_id}'.format(
894 878 branch=branch_name, commit_id=commit_ids['new-feature'])
895 879 pull_request.target_ref = 'branch:{branch}:{commit_id}'.format(
896 branch=backend_git.default_branch_name,
897 commit_id=commit_ids['old-feature'])
880 branch=backend_git.default_branch_name, commit_id=commit_ids['old-feature'])
898 881 pull_request.revisions = [commit_ids['new-feature']]
899 882 pull_request.title = u"Test"
900 883 pull_request.description = u"Description"
901 pull_request.author = UserModel().get_by_username(
902 TEST_USER_ADMIN_LOGIN)
884 pull_request.author = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
885 pull_request.pull_request_state = PullRequest.STATE_CREATED
903 886 Session().add(pull_request)
904 887 Session().commit()
905 888
906 889 vcs = repo.scm_instance()
907 890 vcs.remove_ref('refs/heads/{}'.format(branch_name))
908 891
909 892 response = self.app.get(route_path(
910 893 'pullrequest_show',
911 894 repo_name=repo.repo_name,
912 895 pull_request_id=pull_request.pull_request_id))
913 896
914 897 assert response.status_int == 200
915 898
916 899 response.assert_response().element_contains(
917 900 '#changeset_compare_view_content .alert strong',
918 901 'Missing commits')
919 902 response.assert_response().element_contains(
920 903 '#changeset_compare_view_content .alert',
921 904 'This pull request cannot be displayed, because one or more'
922 905 ' commits no longer exist in the source repository.')
923 906
924 907 def test_strip_commits_from_pull_request(
925 908 self, backend, pr_util, csrf_token):
926 909 commits = [
927 910 {'message': 'initial-commit'},
928 911 {'message': 'old-feature'},
929 912 {'message': 'new-feature', 'parents': ['initial-commit']},
930 913 ]
931 914 pull_request = pr_util.create_pull_request(
932 915 commits, target_head='initial-commit', source_head='new-feature',
933 916 revisions=['new-feature'])
934 917
935 918 vcs = pr_util.source_repository.scm_instance()
936 919 if backend.alias == 'git':
937 920 vcs.strip(pr_util.commit_ids['new-feature'], branch_name='master')
938 921 else:
939 922 vcs.strip(pr_util.commit_ids['new-feature'])
940 923
941 924 response = self.app.get(route_path(
942 925 'pullrequest_show',
943 926 repo_name=pr_util.target_repository.repo_name,
944 927 pull_request_id=pull_request.pull_request_id))
945 928
946 929 assert response.status_int == 200
947 930
948 931 response.assert_response().element_contains(
949 932 '#changeset_compare_view_content .alert strong',
950 933 'Missing commits')
951 934 response.assert_response().element_contains(
952 935 '#changeset_compare_view_content .alert',
953 936 'This pull request cannot be displayed, because one or more'
954 937 ' commits no longer exist in the source repository.')
955 938 response.assert_response().element_contains(
956 939 '#update_commits',
957 940 'Update commits')
958 941
959 942 def test_strip_commits_and_update(
960 943 self, backend, pr_util, csrf_token):
961 944 commits = [
962 945 {'message': 'initial-commit'},
963 946 {'message': 'old-feature'},
964 947 {'message': 'new-feature', 'parents': ['old-feature']},
965 948 ]
966 949 pull_request = pr_util.create_pull_request(
967 950 commits, target_head='old-feature', source_head='new-feature',
968 951 revisions=['new-feature'], mergeable=True)
969 952
970 953 vcs = pr_util.source_repository.scm_instance()
971 954 if backend.alias == 'git':
972 955 vcs.strip(pr_util.commit_ids['new-feature'], branch_name='master')
973 956 else:
974 957 vcs.strip(pr_util.commit_ids['new-feature'])
975 958
976 959 response = self.app.post(
977 960 route_path('pullrequest_update',
978 961 repo_name=pull_request.target_repo.repo_name,
979 962 pull_request_id=pull_request.pull_request_id),
980 963 params={'update_commits': 'true',
981 964 'csrf_token': csrf_token})
982 965
983 966 assert response.status_int == 200
984 967 assert response.body == 'true'
985 968
986 969 # Make sure that after update, it won't raise 500 errors
987 970 response = self.app.get(route_path(
988 971 'pullrequest_show',
989 972 repo_name=pr_util.target_repository.repo_name,
990 973 pull_request_id=pull_request.pull_request_id))
991 974
992 975 assert response.status_int == 200
993 976 response.assert_response().element_contains(
994 977 '#changeset_compare_view_content .alert strong',
995 978 'Missing commits')
996 979
997 980 def test_branch_is_a_link(self, pr_util):
998 981 pull_request = pr_util.create_pull_request()
999 982 pull_request.source_ref = 'branch:origin:1234567890abcdef'
1000 983 pull_request.target_ref = 'branch:target:abcdef1234567890'
1001 984 Session().add(pull_request)
1002 985 Session().commit()
1003 986
1004 987 response = self.app.get(route_path(
1005 988 'pullrequest_show',
1006 989 repo_name=pull_request.target_repo.scm_instance().name,
1007 990 pull_request_id=pull_request.pull_request_id))
1008 991 assert response.status_int == 200
1009 992
1010 993 origin = response.assert_response().get_element('.pr-origininfo .tag')
1011 994 origin_children = origin.getchildren()
1012 995 assert len(origin_children) == 1
1013 996 target = response.assert_response().get_element('.pr-targetinfo .tag')
1014 997 target_children = target.getchildren()
1015 998 assert len(target_children) == 1
1016 999
1017 1000 expected_origin_link = route_path(
1018 1001 'repo_changelog',
1019 1002 repo_name=pull_request.source_repo.scm_instance().name,
1020 1003 params=dict(branch='origin'))
1021 1004 expected_target_link = route_path(
1022 1005 'repo_changelog',
1023 1006 repo_name=pull_request.target_repo.scm_instance().name,
1024 1007 params=dict(branch='target'))
1025 1008 assert origin_children[0].attrib['href'] == expected_origin_link
1026 1009 assert origin_children[0].text == 'branch: origin'
1027 1010 assert target_children[0].attrib['href'] == expected_target_link
1028 1011 assert target_children[0].text == 'branch: target'
1029 1012
1030 1013 def test_bookmark_is_not_a_link(self, pr_util):
1031 1014 pull_request = pr_util.create_pull_request()
1032 1015 pull_request.source_ref = 'bookmark:origin:1234567890abcdef'
1033 1016 pull_request.target_ref = 'bookmark:target:abcdef1234567890'
1034 1017 Session().add(pull_request)
1035 1018 Session().commit()
1036 1019
1037 1020 response = self.app.get(route_path(
1038 1021 'pullrequest_show',
1039 1022 repo_name=pull_request.target_repo.scm_instance().name,
1040 1023 pull_request_id=pull_request.pull_request_id))
1041 1024 assert response.status_int == 200
1042 1025
1043 1026 origin = response.assert_response().get_element('.pr-origininfo .tag')
1044 1027 assert origin.text.strip() == 'bookmark: origin'
1045 1028 assert origin.getchildren() == []
1046 1029
1047 1030 target = response.assert_response().get_element('.pr-targetinfo .tag')
1048 1031 assert target.text.strip() == 'bookmark: target'
1049 1032 assert target.getchildren() == []
1050 1033
1051 1034 def test_tag_is_not_a_link(self, pr_util):
1052 1035 pull_request = pr_util.create_pull_request()
1053 1036 pull_request.source_ref = 'tag:origin:1234567890abcdef'
1054 1037 pull_request.target_ref = 'tag:target:abcdef1234567890'
1055 1038 Session().add(pull_request)
1056 1039 Session().commit()
1057 1040
1058 1041 response = self.app.get(route_path(
1059 1042 'pullrequest_show',
1060 1043 repo_name=pull_request.target_repo.scm_instance().name,
1061 1044 pull_request_id=pull_request.pull_request_id))
1062 1045 assert response.status_int == 200
1063 1046
1064 1047 origin = response.assert_response().get_element('.pr-origininfo .tag')
1065 1048 assert origin.text.strip() == 'tag: origin'
1066 1049 assert origin.getchildren() == []
1067 1050
1068 1051 target = response.assert_response().get_element('.pr-targetinfo .tag')
1069 1052 assert target.text.strip() == 'tag: target'
1070 1053 assert target.getchildren() == []
1071 1054
1072 1055 @pytest.mark.parametrize('mergeable', [True, False])
1073 1056 def test_shadow_repository_link(
1074 1057 self, mergeable, pr_util, http_host_only_stub):
1075 1058 """
1076 1059 Check that the pull request summary page displays a link to the shadow
1077 1060 repository if the pull request is mergeable. If it is not mergeable
1078 1061 the link should not be displayed.
1079 1062 """
1080 1063 pull_request = pr_util.create_pull_request(
1081 1064 mergeable=mergeable, enable_notifications=False)
1082 1065 target_repo = pull_request.target_repo.scm_instance()
1083 1066 pr_id = pull_request.pull_request_id
1084 1067 shadow_url = '{host}/{repo}/pull-request/{pr_id}/repository'.format(
1085 1068 host=http_host_only_stub, repo=target_repo.name, pr_id=pr_id)
1086 1069
1087 1070 response = self.app.get(route_path(
1088 1071 'pullrequest_show',
1089 1072 repo_name=target_repo.name,
1090 1073 pull_request_id=pr_id))
1091 1074
1092 1075 if mergeable:
1093 1076 response.assert_response().element_value_contains(
1094 1077 'input.pr-mergeinfo', shadow_url)
1095 1078 response.assert_response().element_value_contains(
1096 1079 'input.pr-mergeinfo ', 'pr-merge')
1097 1080 else:
1098 1081 response.assert_response().no_element_exists('.pr-mergeinfo')
1099 1082
1100 1083
1101 1084 @pytest.mark.usefixtures('app')
1102 1085 @pytest.mark.backends("git", "hg")
1103 1086 class TestPullrequestsControllerDelete(object):
1104 1087 def test_pull_request_delete_button_permissions_admin(
1105 1088 self, autologin_user, user_admin, pr_util):
1106 1089 pull_request = pr_util.create_pull_request(
1107 1090 author=user_admin.username, enable_notifications=False)
1108 1091
1109 1092 response = self.app.get(route_path(
1110 1093 'pullrequest_show',
1111 1094 repo_name=pull_request.target_repo.scm_instance().name,
1112 1095 pull_request_id=pull_request.pull_request_id))
1113 1096
1114 1097 response.mustcontain('id="delete_pullrequest"')
1115 1098 response.mustcontain('Confirm to delete this pull request')
1116 1099
1117 1100 def test_pull_request_delete_button_permissions_owner(
1118 1101 self, autologin_regular_user, user_regular, pr_util):
1119 1102 pull_request = pr_util.create_pull_request(
1120 1103 author=user_regular.username, enable_notifications=False)
1121 1104
1122 1105 response = self.app.get(route_path(
1123 1106 'pullrequest_show',
1124 1107 repo_name=pull_request.target_repo.scm_instance().name,
1125 1108 pull_request_id=pull_request.pull_request_id))
1126 1109
1127 1110 response.mustcontain('id="delete_pullrequest"')
1128 1111 response.mustcontain('Confirm to delete this pull request')
1129 1112
1130 1113 def test_pull_request_delete_button_permissions_forbidden(
1131 1114 self, autologin_regular_user, user_regular, user_admin, pr_util):
1132 1115 pull_request = pr_util.create_pull_request(
1133 1116 author=user_admin.username, enable_notifications=False)
1134 1117
1135 1118 response = self.app.get(route_path(
1136 1119 'pullrequest_show',
1137 1120 repo_name=pull_request.target_repo.scm_instance().name,
1138 1121 pull_request_id=pull_request.pull_request_id))
1139 1122 response.mustcontain(no=['id="delete_pullrequest"'])
1140 1123 response.mustcontain(no=['Confirm to delete this pull request'])
1141 1124
1142 1125 def test_pull_request_delete_button_permissions_can_update_cannot_delete(
1143 1126 self, autologin_regular_user, user_regular, user_admin, pr_util,
1144 1127 user_util):
1145 1128
1146 1129 pull_request = pr_util.create_pull_request(
1147 1130 author=user_admin.username, enable_notifications=False)
1148 1131
1149 1132 user_util.grant_user_permission_to_repo(
1150 1133 pull_request.target_repo, user_regular,
1151 1134 'repository.write')
1152 1135
1153 1136 response = self.app.get(route_path(
1154 1137 'pullrequest_show',
1155 1138 repo_name=pull_request.target_repo.scm_instance().name,
1156 1139 pull_request_id=pull_request.pull_request_id))
1157 1140
1158 1141 response.mustcontain('id="open_edit_pullrequest"')
1159 1142 response.mustcontain('id="delete_pullrequest"')
1160 1143 response.mustcontain(no=['Confirm to delete this pull request'])
1161 1144
1162 1145 def test_delete_comment_returns_404_if_comment_does_not_exist(
1163 1146 self, autologin_user, pr_util, user_admin, csrf_token, xhr_header):
1164 1147
1165 1148 pull_request = pr_util.create_pull_request(
1166 1149 author=user_admin.username, enable_notifications=False)
1167 1150
1168 1151 self.app.post(
1169 1152 route_path(
1170 1153 'pullrequest_comment_delete',
1171 1154 repo_name=pull_request.target_repo.scm_instance().name,
1172 1155 pull_request_id=pull_request.pull_request_id,
1173 1156 comment_id=1024404),
1174 1157 extra_environ=xhr_header,
1175 1158 params={'csrf_token': csrf_token},
1176 1159 status=404
1177 1160 )
1178 1161
1179 1162 def test_delete_comment(
1180 1163 self, autologin_user, pr_util, user_admin, csrf_token, xhr_header):
1181 1164
1182 1165 pull_request = pr_util.create_pull_request(
1183 1166 author=user_admin.username, enable_notifications=False)
1184 1167 comment = pr_util.create_comment()
1185 1168 comment_id = comment.comment_id
1186 1169
1187 1170 response = self.app.post(
1188 1171 route_path(
1189 1172 'pullrequest_comment_delete',
1190 1173 repo_name=pull_request.target_repo.scm_instance().name,
1191 1174 pull_request_id=pull_request.pull_request_id,
1192 1175 comment_id=comment_id),
1193 1176 extra_environ=xhr_header,
1194 1177 params={'csrf_token': csrf_token},
1195 1178 status=200
1196 1179 )
1197 1180 assert response.body == 'true'
1198 1181
1199 1182 @pytest.mark.parametrize('url_type', [
1200 1183 'pullrequest_new',
1201 1184 'pullrequest_create',
1202 1185 'pullrequest_update',
1203 1186 'pullrequest_merge',
1204 1187 ])
1205 1188 def test_pull_request_is_forbidden_on_archived_repo(
1206 1189 self, autologin_user, backend, xhr_header, user_util, url_type):
1207 1190
1208 1191 # create a temporary repo
1209 1192 source = user_util.create_repo(repo_type=backend.alias)
1210 1193 repo_name = source.repo_name
1211 1194 repo = Repository.get_by_repo_name(repo_name)
1212 1195 repo.archived = True
1213 1196 Session().commit()
1214 1197
1215 1198 response = self.app.get(
1216 1199 route_path(url_type, repo_name=repo_name, pull_request_id=1), status=302)
1217 1200
1218 1201 msg = 'Action not supported for archived repository.'
1219 1202 assert_session_flash(response, msg)
1220 1203
1221 1204
1222 1205 def assert_pull_request_status(pull_request, expected_status):
1223 1206 status = ChangesetStatusModel().calculated_review_status(
1224 1207 pull_request=pull_request)
1225 1208 assert status == expected_status
1226 1209
1227 1210
1228 1211 @pytest.mark.parametrize('route', ['pullrequest_new', 'pullrequest_create'])
1229 1212 @pytest.mark.usefixtures("autologin_user")
1230 1213 def test_forbidde_to_repo_summary_for_svn_repositories(backend_svn, app, route):
1231 1214 response = app.get(
1232 1215 route_path(route, repo_name=backend_svn.repo_name), status=404)
1233 1216
@@ -1,1413 +1,1456 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import logging
22 22 import collections
23 23
24 24 import formencode
25 25 import formencode.htmlfill
26 26 import peppercorn
27 27 from pyramid.httpexceptions import (
28 28 HTTPFound, HTTPNotFound, HTTPForbidden, HTTPBadRequest)
29 29 from pyramid.view import view_config
30 30 from pyramid.renderers import render
31 31
32 32 from rhodecode import events
33 33 from rhodecode.apps._base import RepoAppView, DataGridAppView
34 34
35 35 from rhodecode.lib import helpers as h, diffs, codeblocks, channelstream
36 36 from rhodecode.lib.base import vcs_operation_context
37 37 from rhodecode.lib.diffs import load_cached_diff, cache_diff, diff_cache_exist
38 38 from rhodecode.lib.ext_json import json
39 39 from rhodecode.lib.auth import (
40 40 LoginRequired, HasRepoPermissionAny, HasRepoPermissionAnyDecorator,
41 41 NotAnonymous, CSRFRequired)
42 42 from rhodecode.lib.utils2 import str2bool, safe_str, safe_unicode
43 43 from rhodecode.lib.vcs.backends.base import EmptyCommit, UpdateFailureReason
44 44 from rhodecode.lib.vcs.exceptions import (CommitDoesNotExistError,
45 45 RepositoryRequirementError, EmptyRepositoryError)
46 46 from rhodecode.model.changeset_status import ChangesetStatusModel
47 47 from rhodecode.model.comment import CommentsModel
48 48 from rhodecode.model.db import (func, or_, PullRequest, PullRequestVersion,
49 49 ChangesetComment, ChangesetStatus, Repository)
50 50 from rhodecode.model.forms import PullRequestForm
51 51 from rhodecode.model.meta import Session
52 52 from rhodecode.model.pull_request import PullRequestModel, MergeCheck
53 53 from rhodecode.model.scm import ScmModel
54 54
55 55 log = logging.getLogger(__name__)
56 56
57 57
58 58 class RepoPullRequestsView(RepoAppView, DataGridAppView):
59 59
60 60 def load_default_context(self):
61 61 c = self._get_local_tmpl_context(include_app_defaults=True)
62 62 c.REVIEW_STATUS_APPROVED = ChangesetStatus.STATUS_APPROVED
63 63 c.REVIEW_STATUS_REJECTED = ChangesetStatus.STATUS_REJECTED
64 64 # backward compat., we use for OLD PRs a plain renderer
65 65 c.renderer = 'plain'
66 66 return c
67 67
68 68 def _get_pull_requests_list(
69 69 self, repo_name, source, filter_type, opened_by, statuses):
70 70
71 71 draw, start, limit = self._extract_chunk(self.request)
72 72 search_q, order_by, order_dir = self._extract_ordering(self.request)
73 73 _render = self.request.get_partial_renderer(
74 74 'rhodecode:templates/data_table/_dt_elements.mako')
75 75
76 76 # pagination
77 77
78 78 if filter_type == 'awaiting_review':
79 79 pull_requests = PullRequestModel().get_awaiting_review(
80 80 repo_name, source=source, opened_by=opened_by,
81 81 statuses=statuses, offset=start, length=limit,
82 82 order_by=order_by, order_dir=order_dir)
83 83 pull_requests_total_count = PullRequestModel().count_awaiting_review(
84 84 repo_name, source=source, statuses=statuses,
85 85 opened_by=opened_by)
86 86 elif filter_type == 'awaiting_my_review':
87 87 pull_requests = PullRequestModel().get_awaiting_my_review(
88 88 repo_name, source=source, opened_by=opened_by,
89 89 user_id=self._rhodecode_user.user_id, statuses=statuses,
90 90 offset=start, length=limit, order_by=order_by,
91 91 order_dir=order_dir)
92 92 pull_requests_total_count = PullRequestModel().count_awaiting_my_review(
93 93 repo_name, source=source, user_id=self._rhodecode_user.user_id,
94 94 statuses=statuses, opened_by=opened_by)
95 95 else:
96 96 pull_requests = PullRequestModel().get_all(
97 97 repo_name, source=source, opened_by=opened_by,
98 98 statuses=statuses, offset=start, length=limit,
99 99 order_by=order_by, order_dir=order_dir)
100 100 pull_requests_total_count = PullRequestModel().count_all(
101 101 repo_name, source=source, statuses=statuses,
102 102 opened_by=opened_by)
103 103
104 104 data = []
105 105 comments_model = CommentsModel()
106 106 for pr in pull_requests:
107 107 comments = comments_model.get_all_comments(
108 108 self.db_repo.repo_id, pull_request=pr)
109 109
110 110 data.append({
111 111 'name': _render('pullrequest_name',
112 112 pr.pull_request_id, pr.target_repo.repo_name),
113 113 'name_raw': pr.pull_request_id,
114 114 'status': _render('pullrequest_status',
115 115 pr.calculated_review_status()),
116 116 'title': _render(
117 117 'pullrequest_title', pr.title, pr.description),
118 118 'description': h.escape(pr.description),
119 119 'updated_on': _render('pullrequest_updated_on',
120 120 h.datetime_to_time(pr.updated_on)),
121 121 'updated_on_raw': h.datetime_to_time(pr.updated_on),
122 122 'created_on': _render('pullrequest_updated_on',
123 123 h.datetime_to_time(pr.created_on)),
124 124 'created_on_raw': h.datetime_to_time(pr.created_on),
125 125 'author': _render('pullrequest_author',
126 126 pr.author.full_contact, ),
127 127 'author_raw': pr.author.full_name,
128 128 'comments': _render('pullrequest_comments', len(comments)),
129 129 'comments_raw': len(comments),
130 130 'closed': pr.is_closed(),
131 131 })
132 132
133 133 data = ({
134 134 'draw': draw,
135 135 'data': data,
136 136 'recordsTotal': pull_requests_total_count,
137 137 'recordsFiltered': pull_requests_total_count,
138 138 })
139 139 return data
140 140
141 141 def get_recache_flag(self):
142 142 for flag_name in ['force_recache', 'force-recache', 'no-cache']:
143 143 flag_val = self.request.GET.get(flag_name)
144 144 if str2bool(flag_val):
145 145 return True
146 146 return False
147 147
148 148 @LoginRequired()
149 149 @HasRepoPermissionAnyDecorator(
150 150 'repository.read', 'repository.write', 'repository.admin')
151 151 @view_config(
152 152 route_name='pullrequest_show_all', request_method='GET',
153 153 renderer='rhodecode:templates/pullrequests/pullrequests.mako')
154 154 def pull_request_list(self):
155 155 c = self.load_default_context()
156 156
157 157 req_get = self.request.GET
158 158 c.source = str2bool(req_get.get('source'))
159 159 c.closed = str2bool(req_get.get('closed'))
160 160 c.my = str2bool(req_get.get('my'))
161 161 c.awaiting_review = str2bool(req_get.get('awaiting_review'))
162 162 c.awaiting_my_review = str2bool(req_get.get('awaiting_my_review'))
163 163
164 164 c.active = 'open'
165 165 if c.my:
166 166 c.active = 'my'
167 167 if c.closed:
168 168 c.active = 'closed'
169 169 if c.awaiting_review and not c.source:
170 170 c.active = 'awaiting'
171 171 if c.source and not c.awaiting_review:
172 172 c.active = 'source'
173 173 if c.awaiting_my_review:
174 174 c.active = 'awaiting_my'
175 175
176 176 return self._get_template_context(c)
177 177
178 178 @LoginRequired()
179 179 @HasRepoPermissionAnyDecorator(
180 180 'repository.read', 'repository.write', 'repository.admin')
181 181 @view_config(
182 182 route_name='pullrequest_show_all_data', request_method='GET',
183 183 renderer='json_ext', xhr=True)
184 184 def pull_request_list_data(self):
185 185 self.load_default_context()
186 186
187 187 # additional filters
188 188 req_get = self.request.GET
189 189 source = str2bool(req_get.get('source'))
190 190 closed = str2bool(req_get.get('closed'))
191 191 my = str2bool(req_get.get('my'))
192 192 awaiting_review = str2bool(req_get.get('awaiting_review'))
193 193 awaiting_my_review = str2bool(req_get.get('awaiting_my_review'))
194 194
195 195 filter_type = 'awaiting_review' if awaiting_review \
196 196 else 'awaiting_my_review' if awaiting_my_review \
197 197 else None
198 198
199 199 opened_by = None
200 200 if my:
201 201 opened_by = [self._rhodecode_user.user_id]
202 202
203 203 statuses = [PullRequest.STATUS_NEW, PullRequest.STATUS_OPEN]
204 204 if closed:
205 205 statuses = [PullRequest.STATUS_CLOSED]
206 206
207 207 data = self._get_pull_requests_list(
208 208 repo_name=self.db_repo_name, source=source,
209 209 filter_type=filter_type, opened_by=opened_by, statuses=statuses)
210 210
211 211 return data
212 212
213 213 def _is_diff_cache_enabled(self, target_repo):
214 214 caching_enabled = self._get_general_setting(
215 215 target_repo, 'rhodecode_diff_cache')
216 216 log.debug('Diff caching enabled: %s', caching_enabled)
217 217 return caching_enabled
218 218
219 219 def _get_diffset(self, source_repo_name, source_repo,
220 220 source_ref_id, target_ref_id,
221 221 target_commit, source_commit, diff_limit, file_limit,
222 222 fulldiff, hide_whitespace_changes, diff_context):
223 223
224 224 vcs_diff = PullRequestModel().get_diff(
225 225 source_repo, source_ref_id, target_ref_id,
226 226 hide_whitespace_changes, diff_context)
227 227
228 228 diff_processor = diffs.DiffProcessor(
229 229 vcs_diff, format='newdiff', diff_limit=diff_limit,
230 230 file_limit=file_limit, show_full_diff=fulldiff)
231 231
232 232 _parsed = diff_processor.prepare()
233 233
234 234 diffset = codeblocks.DiffSet(
235 235 repo_name=self.db_repo_name,
236 236 source_repo_name=source_repo_name,
237 237 source_node_getter=codeblocks.diffset_node_getter(target_commit),
238 238 target_node_getter=codeblocks.diffset_node_getter(source_commit),
239 239 )
240 240 diffset = self.path_filter.render_patchset_filtered(
241 241 diffset, _parsed, target_commit.raw_id, source_commit.raw_id)
242 242
243 243 return diffset
244 244
245 245 def _get_range_diffset(self, source_scm, source_repo,
246 246 commit1, commit2, diff_limit, file_limit,
247 247 fulldiff, hide_whitespace_changes, diff_context):
248 248 vcs_diff = source_scm.get_diff(
249 249 commit1, commit2,
250 250 ignore_whitespace=hide_whitespace_changes,
251 251 context=diff_context)
252 252
253 253 diff_processor = diffs.DiffProcessor(
254 254 vcs_diff, format='newdiff', diff_limit=diff_limit,
255 255 file_limit=file_limit, show_full_diff=fulldiff)
256 256
257 257 _parsed = diff_processor.prepare()
258 258
259 259 diffset = codeblocks.DiffSet(
260 260 repo_name=source_repo.repo_name,
261 261 source_node_getter=codeblocks.diffset_node_getter(commit1),
262 262 target_node_getter=codeblocks.diffset_node_getter(commit2))
263 263
264 264 diffset = self.path_filter.render_patchset_filtered(
265 265 diffset, _parsed, commit1.raw_id, commit2.raw_id)
266 266
267 267 return diffset
268 268
269 269 @LoginRequired()
270 270 @HasRepoPermissionAnyDecorator(
271 271 'repository.read', 'repository.write', 'repository.admin')
272 272 @view_config(
273 273 route_name='pullrequest_show', request_method='GET',
274 274 renderer='rhodecode:templates/pullrequests/pullrequest_show.mako')
275 275 def pull_request_show(self):
276 pull_request_id = self.request.matchdict['pull_request_id']
276 _ = self.request.translate
277 c = self.load_default_context()
278
279 pull_request = PullRequest.get_or_404(
280 self.request.matchdict['pull_request_id'])
281 pull_request_id = pull_request.pull_request_id
277 282
278 c = self.load_default_context()
283 if pull_request.pull_request_state != PullRequest.STATE_CREATED:
284 log.debug('show: forbidden because pull request is in state %s',
285 pull_request.pull_request_state)
286 msg = _(u'Cannot show pull requests in state other than `{}`. '
287 u'Current state is: `{}`').format(PullRequest.STATE_CREATED,
288 pull_request.pull_request_state)
289 h.flash(msg, category='error')
290 raise HTTPFound(h.route_path('pullrequest_show_all',
291 repo_name=self.db_repo_name))
279 292
280 293 version = self.request.GET.get('version')
281 294 from_version = self.request.GET.get('from_version') or version
282 295 merge_checks = self.request.GET.get('merge_checks')
283 296 c.fulldiff = str2bool(self.request.GET.get('fulldiff'))
284 297
285 298 # fetch global flags of ignore ws or context lines
286 299 diff_context = diffs.get_diff_context(self.request)
287 300 hide_whitespace_changes = diffs.get_diff_whitespace_flag(self.request)
288 301
289 302 force_refresh = str2bool(self.request.GET.get('force_refresh'))
290 303
291 304 (pull_request_latest,
292 305 pull_request_at_ver,
293 306 pull_request_display_obj,
294 307 at_version) = PullRequestModel().get_pr_version(
295 308 pull_request_id, version=version)
296 309 pr_closed = pull_request_latest.is_closed()
297 310
298 311 if pr_closed and (version or from_version):
299 312 # not allow to browse versions
300 313 raise HTTPFound(h.route_path(
301 314 'pullrequest_show', repo_name=self.db_repo_name,
302 315 pull_request_id=pull_request_id))
303 316
304 317 versions = pull_request_display_obj.versions()
305 318 # used to store per-commit range diffs
306 319 c.changes = collections.OrderedDict()
307 320 c.range_diff_on = self.request.GET.get('range-diff') == "1"
308 321
309 322 c.at_version = at_version
310 323 c.at_version_num = (at_version
311 324 if at_version and at_version != 'latest'
312 325 else None)
313 326 c.at_version_pos = ChangesetComment.get_index_from_version(
314 327 c.at_version_num, versions)
315 328
316 329 (prev_pull_request_latest,
317 330 prev_pull_request_at_ver,
318 331 prev_pull_request_display_obj,
319 332 prev_at_version) = PullRequestModel().get_pr_version(
320 333 pull_request_id, version=from_version)
321 334
322 335 c.from_version = prev_at_version
323 336 c.from_version_num = (prev_at_version
324 337 if prev_at_version and prev_at_version != 'latest'
325 338 else None)
326 339 c.from_version_pos = ChangesetComment.get_index_from_version(
327 340 c.from_version_num, versions)
328 341
329 342 # define if we're in COMPARE mode or VIEW at version mode
330 343 compare = at_version != prev_at_version
331 344
332 345 # pull_requests repo_name we opened it against
333 346 # ie. target_repo must match
334 347 if self.db_repo_name != pull_request_at_ver.target_repo.repo_name:
335 348 raise HTTPNotFound()
336 349
337 350 c.shadow_clone_url = PullRequestModel().get_shadow_clone_url(
338 351 pull_request_at_ver)
339 352
340 353 c.pull_request = pull_request_display_obj
341 354 c.renderer = pull_request_at_ver.description_renderer or c.renderer
342 355 c.pull_request_latest = pull_request_latest
343 356
344 357 if compare or (at_version and not at_version == 'latest'):
345 358 c.allowed_to_change_status = False
346 359 c.allowed_to_update = False
347 360 c.allowed_to_merge = False
348 361 c.allowed_to_delete = False
349 362 c.allowed_to_comment = False
350 363 c.allowed_to_close = False
351 364 else:
352 365 can_change_status = PullRequestModel().check_user_change_status(
353 366 pull_request_at_ver, self._rhodecode_user)
354 367 c.allowed_to_change_status = can_change_status and not pr_closed
355 368
356 369 c.allowed_to_update = PullRequestModel().check_user_update(
357 370 pull_request_latest, self._rhodecode_user) and not pr_closed
358 371 c.allowed_to_merge = PullRequestModel().check_user_merge(
359 372 pull_request_latest, self._rhodecode_user) and not pr_closed
360 373 c.allowed_to_delete = PullRequestModel().check_user_delete(
361 374 pull_request_latest, self._rhodecode_user) and not pr_closed
362 375 c.allowed_to_comment = not pr_closed
363 376 c.allowed_to_close = c.allowed_to_merge and not pr_closed
364 377
365 378 c.forbid_adding_reviewers = False
366 379 c.forbid_author_to_review = False
367 380 c.forbid_commit_author_to_review = False
368 381
369 382 if pull_request_latest.reviewer_data and \
370 383 'rules' in pull_request_latest.reviewer_data:
371 384 rules = pull_request_latest.reviewer_data['rules'] or {}
372 385 try:
373 386 c.forbid_adding_reviewers = rules.get(
374 387 'forbid_adding_reviewers')
375 388 c.forbid_author_to_review = rules.get(
376 389 'forbid_author_to_review')
377 390 c.forbid_commit_author_to_review = rules.get(
378 391 'forbid_commit_author_to_review')
379 392 except Exception:
380 393 pass
381 394
382 395 # check merge capabilities
383 396 _merge_check = MergeCheck.validate(
384 397 pull_request_latest, auth_user=self._rhodecode_user,
385 398 translator=self.request.translate,
386 399 force_shadow_repo_refresh=force_refresh)
387 400 c.pr_merge_errors = _merge_check.error_details
388 401 c.pr_merge_possible = not _merge_check.failed
389 402 c.pr_merge_message = _merge_check.merge_msg
390 403
391 404 c.pr_merge_info = MergeCheck.get_merge_conditions(
392 405 pull_request_latest, translator=self.request.translate)
393 406
394 407 c.pull_request_review_status = _merge_check.review_status
395 408 if merge_checks:
396 409 self.request.override_renderer = \
397 410 'rhodecode:templates/pullrequests/pullrequest_merge_checks.mako'
398 411 return self._get_template_context(c)
399 412
400 413 comments_model = CommentsModel()
401 414
402 415 # reviewers and statuses
403 416 c.pull_request_reviewers = pull_request_at_ver.reviewers_statuses()
404 417 allowed_reviewers = [x[0].user_id for x in c.pull_request_reviewers]
405 418
406 419 # GENERAL COMMENTS with versions #
407 420 q = comments_model._all_general_comments_of_pull_request(pull_request_latest)
408 421 q = q.order_by(ChangesetComment.comment_id.asc())
409 422 general_comments = q
410 423
411 424 # pick comments we want to render at current version
412 425 c.comment_versions = comments_model.aggregate_comments(
413 426 general_comments, versions, c.at_version_num)
414 427 c.comments = c.comment_versions[c.at_version_num]['until']
415 428
416 429 # INLINE COMMENTS with versions #
417 430 q = comments_model._all_inline_comments_of_pull_request(pull_request_latest)
418 431 q = q.order_by(ChangesetComment.comment_id.asc())
419 432 inline_comments = q
420 433
421 434 c.inline_versions = comments_model.aggregate_comments(
422 435 inline_comments, versions, c.at_version_num, inline=True)
423 436
424 437 # inject latest version
425 438 latest_ver = PullRequest.get_pr_display_object(
426 439 pull_request_latest, pull_request_latest)
427 440
428 441 c.versions = versions + [latest_ver]
429 442
430 443 # if we use version, then do not show later comments
431 444 # than current version
432 445 display_inline_comments = collections.defaultdict(
433 446 lambda: collections.defaultdict(list))
434 447 for co in inline_comments:
435 448 if c.at_version_num:
436 449 # pick comments that are at least UPTO given version, so we
437 450 # don't render comments for higher version
438 451 should_render = co.pull_request_version_id and \
439 452 co.pull_request_version_id <= c.at_version_num
440 453 else:
441 454 # showing all, for 'latest'
442 455 should_render = True
443 456
444 457 if should_render:
445 458 display_inline_comments[co.f_path][co.line_no].append(co)
446 459
447 460 # load diff data into template context, if we use compare mode then
448 461 # diff is calculated based on changes between versions of PR
449 462
450 463 source_repo = pull_request_at_ver.source_repo
451 464 source_ref_id = pull_request_at_ver.source_ref_parts.commit_id
452 465
453 466 target_repo = pull_request_at_ver.target_repo
454 467 target_ref_id = pull_request_at_ver.target_ref_parts.commit_id
455 468
456 469 if compare:
457 470 # in compare switch the diff base to latest commit from prev version
458 471 target_ref_id = prev_pull_request_display_obj.revisions[0]
459 472
460 473 # despite opening commits for bookmarks/branches/tags, we always
461 474 # convert this to rev to prevent changes after bookmark or branch change
462 475 c.source_ref_type = 'rev'
463 476 c.source_ref = source_ref_id
464 477
465 478 c.target_ref_type = 'rev'
466 479 c.target_ref = target_ref_id
467 480
468 481 c.source_repo = source_repo
469 482 c.target_repo = target_repo
470 483
471 484 c.commit_ranges = []
472 485 source_commit = EmptyCommit()
473 486 target_commit = EmptyCommit()
474 487 c.missing_requirements = False
475 488
476 489 source_scm = source_repo.scm_instance()
477 490 target_scm = target_repo.scm_instance()
478 491
479 492 shadow_scm = None
480 493 try:
481 494 shadow_scm = pull_request_latest.get_shadow_repo()
482 495 except Exception:
483 496 log.debug('Failed to get shadow repo', exc_info=True)
484 497 # try first the existing source_repo, and then shadow
485 498 # repo if we can obtain one
486 499 commits_source_repo = source_scm or shadow_scm
487 500
488 501 c.commits_source_repo = commits_source_repo
489 502 c.ancestor = None # set it to None, to hide it from PR view
490 503
491 504 # empty version means latest, so we keep this to prevent
492 505 # double caching
493 506 version_normalized = version or 'latest'
494 507 from_version_normalized = from_version or 'latest'
495 508
496 509 cache_path = self.rhodecode_vcs_repo.get_create_shadow_cache_pr_path(target_repo)
497 510 cache_file_path = diff_cache_exist(
498 511 cache_path, 'pull_request', pull_request_id, version_normalized,
499 512 from_version_normalized, source_ref_id, target_ref_id,
500 513 hide_whitespace_changes, diff_context, c.fulldiff)
501 514
502 515 caching_enabled = self._is_diff_cache_enabled(c.target_repo)
503 516 force_recache = self.get_recache_flag()
504 517
505 518 cached_diff = None
506 519 if caching_enabled:
507 520 cached_diff = load_cached_diff(cache_file_path)
508 521
509 522 has_proper_commit_cache = (
510 523 cached_diff and cached_diff.get('commits')
511 524 and len(cached_diff.get('commits', [])) == 5
512 525 and cached_diff.get('commits')[0]
513 526 and cached_diff.get('commits')[3])
514 527
515 528 if not force_recache and not c.range_diff_on and has_proper_commit_cache:
516 529 diff_commit_cache = \
517 530 (ancestor_commit, commit_cache, missing_requirements,
518 531 source_commit, target_commit) = cached_diff['commits']
519 532 else:
520 533 diff_commit_cache = \
521 534 (ancestor_commit, commit_cache, missing_requirements,
522 535 source_commit, target_commit) = self.get_commits(
523 536 commits_source_repo,
524 537 pull_request_at_ver,
525 538 source_commit,
526 539 source_ref_id,
527 540 source_scm,
528 541 target_commit,
529 542 target_ref_id,
530 543 target_scm)
531 544
532 545 # register our commit range
533 546 for comm in commit_cache.values():
534 547 c.commit_ranges.append(comm)
535 548
536 549 c.missing_requirements = missing_requirements
537 550 c.ancestor_commit = ancestor_commit
538 551 c.statuses = source_repo.statuses(
539 552 [x.raw_id for x in c.commit_ranges])
540 553
541 554 # auto collapse if we have more than limit
542 555 collapse_limit = diffs.DiffProcessor._collapse_commits_over
543 556 c.collapse_all_commits = len(c.commit_ranges) > collapse_limit
544 557 c.compare_mode = compare
545 558
546 559 # diff_limit is the old behavior, will cut off the whole diff
547 560 # if the limit is applied otherwise will just hide the
548 561 # big files from the front-end
549 562 diff_limit = c.visual.cut_off_limit_diff
550 563 file_limit = c.visual.cut_off_limit_file
551 564
552 565 c.missing_commits = False
553 566 if (c.missing_requirements
554 567 or isinstance(source_commit, EmptyCommit)
555 568 or source_commit == target_commit):
556 569
557 570 c.missing_commits = True
558 571 else:
559 572 c.inline_comments = display_inline_comments
560 573
561 574 has_proper_diff_cache = cached_diff and cached_diff.get('commits')
562 575 if not force_recache and has_proper_diff_cache:
563 576 c.diffset = cached_diff['diff']
564 577 (ancestor_commit, commit_cache, missing_requirements,
565 578 source_commit, target_commit) = cached_diff['commits']
566 579 else:
567 580 c.diffset = self._get_diffset(
568 581 c.source_repo.repo_name, commits_source_repo,
569 582 source_ref_id, target_ref_id,
570 583 target_commit, source_commit,
571 584 diff_limit, file_limit, c.fulldiff,
572 585 hide_whitespace_changes, diff_context)
573 586
574 587 # save cached diff
575 588 if caching_enabled:
576 589 cache_diff(cache_file_path, c.diffset, diff_commit_cache)
577 590
578 591 c.limited_diff = c.diffset.limited_diff
579 592
580 593 # calculate removed files that are bound to comments
581 594 comment_deleted_files = [
582 595 fname for fname in display_inline_comments
583 596 if fname not in c.diffset.file_stats]
584 597
585 598 c.deleted_files_comments = collections.defaultdict(dict)
586 599 for fname, per_line_comments in display_inline_comments.items():
587 600 if fname in comment_deleted_files:
588 601 c.deleted_files_comments[fname]['stats'] = 0
589 602 c.deleted_files_comments[fname]['comments'] = list()
590 603 for lno, comments in per_line_comments.items():
591 604 c.deleted_files_comments[fname]['comments'].extend(comments)
592 605
593 606 # maybe calculate the range diff
594 607 if c.range_diff_on:
595 608 # TODO(marcink): set whitespace/context
596 609 context_lcl = 3
597 610 ign_whitespace_lcl = False
598 611
599 612 for commit in c.commit_ranges:
600 613 commit2 = commit
601 614 commit1 = commit.first_parent
602 615
603 616 range_diff_cache_file_path = diff_cache_exist(
604 617 cache_path, 'diff', commit.raw_id,
605 618 ign_whitespace_lcl, context_lcl, c.fulldiff)
606 619
607 620 cached_diff = None
608 621 if caching_enabled:
609 622 cached_diff = load_cached_diff(range_diff_cache_file_path)
610 623
611 624 has_proper_diff_cache = cached_diff and cached_diff.get('diff')
612 625 if not force_recache and has_proper_diff_cache:
613 626 diffset = cached_diff['diff']
614 627 else:
615 628 diffset = self._get_range_diffset(
616 629 source_scm, source_repo,
617 630 commit1, commit2, diff_limit, file_limit,
618 631 c.fulldiff, ign_whitespace_lcl, context_lcl
619 632 )
620 633
621 634 # save cached diff
622 635 if caching_enabled:
623 636 cache_diff(range_diff_cache_file_path, diffset, None)
624 637
625 638 c.changes[commit.raw_id] = diffset
626 639
627 640 # this is a hack to properly display links, when creating PR, the
628 641 # compare view and others uses different notation, and
629 642 # compare_commits.mako renders links based on the target_repo.
630 643 # We need to swap that here to generate it properly on the html side
631 644 c.target_repo = c.source_repo
632 645
633 646 c.commit_statuses = ChangesetStatus.STATUSES
634 647
635 648 c.show_version_changes = not pr_closed
636 649 if c.show_version_changes:
637 650 cur_obj = pull_request_at_ver
638 651 prev_obj = prev_pull_request_at_ver
639 652
640 653 old_commit_ids = prev_obj.revisions
641 654 new_commit_ids = cur_obj.revisions
642 655 commit_changes = PullRequestModel()._calculate_commit_id_changes(
643 656 old_commit_ids, new_commit_ids)
644 657 c.commit_changes_summary = commit_changes
645 658
646 659 # calculate the diff for commits between versions
647 660 c.commit_changes = []
648 661 mark = lambda cs, fw: list(
649 662 h.itertools.izip_longest([], cs, fillvalue=fw))
650 663 for c_type, raw_id in mark(commit_changes.added, 'a') \
651 664 + mark(commit_changes.removed, 'r') \
652 665 + mark(commit_changes.common, 'c'):
653 666
654 667 if raw_id in commit_cache:
655 668 commit = commit_cache[raw_id]
656 669 else:
657 670 try:
658 671 commit = commits_source_repo.get_commit(raw_id)
659 672 except CommitDoesNotExistError:
660 673 # in case we fail extracting still use "dummy" commit
661 674 # for display in commit diff
662 675 commit = h.AttributeDict(
663 676 {'raw_id': raw_id,
664 677 'message': 'EMPTY or MISSING COMMIT'})
665 678 c.commit_changes.append([c_type, commit])
666 679
667 680 # current user review statuses for each version
668 681 c.review_versions = {}
669 682 if self._rhodecode_user.user_id in allowed_reviewers:
670 683 for co in general_comments:
671 684 if co.author.user_id == self._rhodecode_user.user_id:
672 685 status = co.status_change
673 686 if status:
674 687 _ver_pr = status[0].comment.pull_request_version_id
675 688 c.review_versions[_ver_pr] = status[0]
676 689
677 690 return self._get_template_context(c)
678 691
679 692 def get_commits(
680 693 self, commits_source_repo, pull_request_at_ver, source_commit,
681 694 source_ref_id, source_scm, target_commit, target_ref_id, target_scm):
682 695 commit_cache = collections.OrderedDict()
683 696 missing_requirements = False
684 697 try:
685 698 pre_load = ["author", "branch", "date", "message", "parents"]
686 699 show_revs = pull_request_at_ver.revisions
687 700 for rev in show_revs:
688 701 comm = commits_source_repo.get_commit(
689 702 commit_id=rev, pre_load=pre_load)
690 703 commit_cache[comm.raw_id] = comm
691 704
692 705 # Order here matters, we first need to get target, and then
693 706 # the source
694 707 target_commit = commits_source_repo.get_commit(
695 708 commit_id=safe_str(target_ref_id))
696 709
697 710 source_commit = commits_source_repo.get_commit(
698 711 commit_id=safe_str(source_ref_id))
699 712 except CommitDoesNotExistError:
700 713 log.warning(
701 714 'Failed to get commit from `{}` repo'.format(
702 715 commits_source_repo), exc_info=True)
703 716 except RepositoryRequirementError:
704 717 log.warning(
705 718 'Failed to get all required data from repo', exc_info=True)
706 719 missing_requirements = True
707 720 ancestor_commit = None
708 721 try:
709 722 ancestor_id = source_scm.get_common_ancestor(
710 723 source_commit.raw_id, target_commit.raw_id, target_scm)
711 724 ancestor_commit = source_scm.get_commit(ancestor_id)
712 725 except Exception:
713 726 ancestor_commit = None
714 727 return ancestor_commit, commit_cache, missing_requirements, source_commit, target_commit
715 728
716 729 def assure_not_empty_repo(self):
717 730 _ = self.request.translate
718 731
719 732 try:
720 733 self.db_repo.scm_instance().get_commit()
721 734 except EmptyRepositoryError:
722 735 h.flash(h.literal(_('There are no commits yet')),
723 736 category='warning')
724 737 raise HTTPFound(
725 738 h.route_path('repo_summary', repo_name=self.db_repo.repo_name))
726 739
727 740 @LoginRequired()
728 741 @NotAnonymous()
729 742 @HasRepoPermissionAnyDecorator(
730 743 'repository.read', 'repository.write', 'repository.admin')
731 744 @view_config(
732 745 route_name='pullrequest_new', request_method='GET',
733 746 renderer='rhodecode:templates/pullrequests/pullrequest.mako')
734 747 def pull_request_new(self):
735 748 _ = self.request.translate
736 749 c = self.load_default_context()
737 750
738 751 self.assure_not_empty_repo()
739 752 source_repo = self.db_repo
740 753
741 754 commit_id = self.request.GET.get('commit')
742 755 branch_ref = self.request.GET.get('branch')
743 756 bookmark_ref = self.request.GET.get('bookmark')
744 757
745 758 try:
746 759 source_repo_data = PullRequestModel().generate_repo_data(
747 760 source_repo, commit_id=commit_id,
748 761 branch=branch_ref, bookmark=bookmark_ref,
749 762 translator=self.request.translate)
750 763 except CommitDoesNotExistError as e:
751 764 log.exception(e)
752 765 h.flash(_('Commit does not exist'), 'error')
753 766 raise HTTPFound(
754 767 h.route_path('pullrequest_new', repo_name=source_repo.repo_name))
755 768
756 769 default_target_repo = source_repo
757 770
758 771 if source_repo.parent and c.has_origin_repo_read_perm:
759 772 parent_vcs_obj = source_repo.parent.scm_instance()
760 773 if parent_vcs_obj and not parent_vcs_obj.is_empty():
761 774 # change default if we have a parent repo
762 775 default_target_repo = source_repo.parent
763 776
764 777 target_repo_data = PullRequestModel().generate_repo_data(
765 778 default_target_repo, translator=self.request.translate)
766 779
767 780 selected_source_ref = source_repo_data['refs']['selected_ref']
768 781 title_source_ref = ''
769 782 if selected_source_ref:
770 783 title_source_ref = selected_source_ref.split(':', 2)[1]
771 784 c.default_title = PullRequestModel().generate_pullrequest_title(
772 785 source=source_repo.repo_name,
773 786 source_ref=title_source_ref,
774 787 target=default_target_repo.repo_name
775 788 )
776 789
777 790 c.default_repo_data = {
778 791 'source_repo_name': source_repo.repo_name,
779 792 'source_refs_json': json.dumps(source_repo_data),
780 793 'target_repo_name': default_target_repo.repo_name,
781 794 'target_refs_json': json.dumps(target_repo_data),
782 795 }
783 796 c.default_source_ref = selected_source_ref
784 797
785 798 return self._get_template_context(c)
786 799
787 800 @LoginRequired()
788 801 @NotAnonymous()
789 802 @HasRepoPermissionAnyDecorator(
790 803 'repository.read', 'repository.write', 'repository.admin')
791 804 @view_config(
792 805 route_name='pullrequest_repo_refs', request_method='GET',
793 806 renderer='json_ext', xhr=True)
794 807 def pull_request_repo_refs(self):
795 808 self.load_default_context()
796 809 target_repo_name = self.request.matchdict['target_repo_name']
797 810 repo = Repository.get_by_repo_name(target_repo_name)
798 811 if not repo:
799 812 raise HTTPNotFound()
800 813
801 814 target_perm = HasRepoPermissionAny(
802 815 'repository.read', 'repository.write', 'repository.admin')(
803 816 target_repo_name)
804 817 if not target_perm:
805 818 raise HTTPNotFound()
806 819
807 820 return PullRequestModel().generate_repo_data(
808 821 repo, translator=self.request.translate)
809 822
810 823 @LoginRequired()
811 824 @NotAnonymous()
812 825 @HasRepoPermissionAnyDecorator(
813 826 'repository.read', 'repository.write', 'repository.admin')
814 827 @view_config(
815 828 route_name='pullrequest_repo_targets', request_method='GET',
816 829 renderer='json_ext', xhr=True)
817 830 def pullrequest_repo_targets(self):
818 831 _ = self.request.translate
819 832 filter_query = self.request.GET.get('query')
820 833
821 834 # get the parents
822 835 parent_target_repos = []
823 836 if self.db_repo.parent:
824 837 parents_query = Repository.query() \
825 838 .order_by(func.length(Repository.repo_name)) \
826 839 .filter(Repository.fork_id == self.db_repo.parent.repo_id)
827 840
828 841 if filter_query:
829 842 ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
830 843 parents_query = parents_query.filter(
831 844 Repository.repo_name.ilike(ilike_expression))
832 845 parents = parents_query.limit(20).all()
833 846
834 847 for parent in parents:
835 848 parent_vcs_obj = parent.scm_instance()
836 849 if parent_vcs_obj and not parent_vcs_obj.is_empty():
837 850 parent_target_repos.append(parent)
838 851
839 852 # get other forks, and repo itself
840 853 query = Repository.query() \
841 854 .order_by(func.length(Repository.repo_name)) \
842 855 .filter(
843 856 or_(Repository.repo_id == self.db_repo.repo_id, # repo itself
844 857 Repository.fork_id == self.db_repo.repo_id) # forks of this repo
845 858 ) \
846 859 .filter(~Repository.repo_id.in_([x.repo_id for x in parent_target_repos]))
847 860
848 861 if filter_query:
849 862 ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
850 863 query = query.filter(Repository.repo_name.ilike(ilike_expression))
851 864
852 865 limit = max(20 - len(parent_target_repos), 5) # not less then 5
853 866 target_repos = query.limit(limit).all()
854 867
855 868 all_target_repos = target_repos + parent_target_repos
856 869
857 870 repos = []
858 871 # This checks permissions to the repositories
859 872 for obj in ScmModel().get_repos(all_target_repos):
860 873 repos.append({
861 874 'id': obj['name'],
862 875 'text': obj['name'],
863 876 'type': 'repo',
864 877 'repo_id': obj['dbrepo']['repo_id'],
865 878 'repo_type': obj['dbrepo']['repo_type'],
866 879 'private': obj['dbrepo']['private'],
867 880
868 881 })
869 882
870 883 data = {
871 884 'more': False,
872 885 'results': [{
873 886 'text': _('Repositories'),
874 887 'children': repos
875 888 }] if repos else []
876 889 }
877 890 return data
878 891
879 892 @LoginRequired()
880 893 @NotAnonymous()
881 894 @HasRepoPermissionAnyDecorator(
882 895 'repository.read', 'repository.write', 'repository.admin')
883 896 @CSRFRequired()
884 897 @view_config(
885 898 route_name='pullrequest_create', request_method='POST',
886 899 renderer=None)
887 900 def pull_request_create(self):
888 901 _ = self.request.translate
889 902 self.assure_not_empty_repo()
890 903 self.load_default_context()
891 904
892 905 controls = peppercorn.parse(self.request.POST.items())
893 906
894 907 try:
895 908 form = PullRequestForm(
896 909 self.request.translate, self.db_repo.repo_id)()
897 910 _form = form.to_python(controls)
898 911 except formencode.Invalid as errors:
899 912 if errors.error_dict.get('revisions'):
900 913 msg = 'Revisions: %s' % errors.error_dict['revisions']
901 914 elif errors.error_dict.get('pullrequest_title'):
902 915 msg = errors.error_dict.get('pullrequest_title')
903 916 else:
904 917 msg = _('Error creating pull request: {}').format(errors)
905 918 log.exception(msg)
906 919 h.flash(msg, 'error')
907 920
908 921 # would rather just go back to form ...
909 922 raise HTTPFound(
910 923 h.route_path('pullrequest_new', repo_name=self.db_repo_name))
911 924
912 925 source_repo = _form['source_repo']
913 926 source_ref = _form['source_ref']
914 927 target_repo = _form['target_repo']
915 928 target_ref = _form['target_ref']
916 929 commit_ids = _form['revisions'][::-1]
917 930
918 931 # find the ancestor for this pr
919 932 source_db_repo = Repository.get_by_repo_name(_form['source_repo'])
920 933 target_db_repo = Repository.get_by_repo_name(_form['target_repo'])
921 934
935 if not (source_db_repo or target_db_repo):
936 h.flash(_('source_repo or target repo not found'), category='error')
937 raise HTTPFound(
938 h.route_path('pullrequest_new', repo_name=self.db_repo_name))
939
922 940 # re-check permissions again here
923 941 # source_repo we must have read permissions
924 942
925 943 source_perm = HasRepoPermissionAny(
926 'repository.read',
927 'repository.write', 'repository.admin')(source_db_repo.repo_name)
944 'repository.read', 'repository.write', 'repository.admin')(
945 source_db_repo.repo_name)
928 946 if not source_perm:
929 947 msg = _('Not Enough permissions to source repo `{}`.'.format(
930 948 source_db_repo.repo_name))
931 949 h.flash(msg, category='error')
932 950 # copy the args back to redirect
933 951 org_query = self.request.GET.mixed()
934 952 raise HTTPFound(
935 953 h.route_path('pullrequest_new', repo_name=self.db_repo_name,
936 954 _query=org_query))
937 955
938 956 # target repo we must have read permissions, and also later on
939 957 # we want to check branch permissions here
940 958 target_perm = HasRepoPermissionAny(
941 'repository.read',
942 'repository.write', 'repository.admin')(target_db_repo.repo_name)
959 'repository.read', 'repository.write', 'repository.admin')(
960 target_db_repo.repo_name)
943 961 if not target_perm:
944 962 msg = _('Not Enough permissions to target repo `{}`.'.format(
945 963 target_db_repo.repo_name))
946 964 h.flash(msg, category='error')
947 965 # copy the args back to redirect
948 966 org_query = self.request.GET.mixed()
949 967 raise HTTPFound(
950 968 h.route_path('pullrequest_new', repo_name=self.db_repo_name,
951 969 _query=org_query))
952 970
953 971 source_scm = source_db_repo.scm_instance()
954 972 target_scm = target_db_repo.scm_instance()
955 973
956 974 source_commit = source_scm.get_commit(source_ref.split(':')[-1])
957 975 target_commit = target_scm.get_commit(target_ref.split(':')[-1])
958 976
959 977 ancestor = source_scm.get_common_ancestor(
960 978 source_commit.raw_id, target_commit.raw_id, target_scm)
961 979
962 980 # recalculate target ref based on ancestor
963 981 target_ref_type, target_ref_name, __ = _form['target_ref'].split(':')
964 982 target_ref = ':'.join((target_ref_type, target_ref_name, ancestor))
965 983
966 984 get_default_reviewers_data, validate_default_reviewers = \
967 985 PullRequestModel().get_reviewer_functions()
968 986
969 987 # recalculate reviewers logic, to make sure we can validate this
970 988 reviewer_rules = get_default_reviewers_data(
971 989 self._rhodecode_db_user, source_db_repo,
972 990 source_commit, target_db_repo, target_commit)
973 991
974 992 given_reviewers = _form['review_members']
975 993 reviewers = validate_default_reviewers(
976 994 given_reviewers, reviewer_rules)
977 995
978 996 pullrequest_title = _form['pullrequest_title']
979 997 title_source_ref = source_ref.split(':', 2)[1]
980 998 if not pullrequest_title:
981 999 pullrequest_title = PullRequestModel().generate_pullrequest_title(
982 1000 source=source_repo,
983 1001 source_ref=title_source_ref,
984 1002 target=target_repo
985 1003 )
986 1004
987 1005 description = _form['pullrequest_desc']
988 1006 description_renderer = _form['description_renderer']
989 1007
990 1008 try:
991 1009 pull_request = PullRequestModel().create(
992 1010 created_by=self._rhodecode_user.user_id,
993 1011 source_repo=source_repo,
994 1012 source_ref=source_ref,
995 1013 target_repo=target_repo,
996 1014 target_ref=target_ref,
997 1015 revisions=commit_ids,
998 1016 reviewers=reviewers,
999 1017 title=pullrequest_title,
1000 1018 description=description,
1001 1019 description_renderer=description_renderer,
1002 1020 reviewer_data=reviewer_rules,
1003 1021 auth_user=self._rhodecode_user
1004 1022 )
1005 1023 Session().commit()
1006 1024
1007 1025 h.flash(_('Successfully opened new pull request'),
1008 1026 category='success')
1009 1027 except Exception:
1010 1028 msg = _('Error occurred during creation of this pull request.')
1011 1029 log.exception(msg)
1012 1030 h.flash(msg, category='error')
1013 1031
1014 1032 # copy the args back to redirect
1015 1033 org_query = self.request.GET.mixed()
1016 1034 raise HTTPFound(
1017 1035 h.route_path('pullrequest_new', repo_name=self.db_repo_name,
1018 1036 _query=org_query))
1019 1037
1020 1038 raise HTTPFound(
1021 1039 h.route_path('pullrequest_show', repo_name=target_repo,
1022 1040 pull_request_id=pull_request.pull_request_id))
1023 1041
1024 1042 @LoginRequired()
1025 1043 @NotAnonymous()
1026 1044 @HasRepoPermissionAnyDecorator(
1027 1045 'repository.read', 'repository.write', 'repository.admin')
1028 1046 @CSRFRequired()
1029 1047 @view_config(
1030 1048 route_name='pullrequest_update', request_method='POST',
1031 1049 renderer='json_ext')
1032 1050 def pull_request_update(self):
1033 1051 pull_request = PullRequest.get_or_404(
1034 1052 self.request.matchdict['pull_request_id'])
1035 1053 _ = self.request.translate
1036 1054
1037 1055 self.load_default_context()
1038 1056
1039 1057 if pull_request.is_closed():
1040 1058 log.debug('update: forbidden because pull request is closed')
1041 1059 msg = _(u'Cannot update closed pull requests.')
1042 1060 h.flash(msg, category='error')
1043 1061 return True
1044 1062
1063 if pull_request.pull_request_state != PullRequest.STATE_CREATED:
1064 log.debug('update: forbidden because pull request is in state %s',
1065 pull_request.pull_request_state)
1066 msg = _(u'Cannot update pull requests in state other than `{}`. '
1067 u'Current state is: `{}`').format(PullRequest.STATE_CREATED,
1068 pull_request.pull_request_state)
1069 h.flash(msg, category='error')
1070 return True
1071
1045 1072 # only owner or admin can update it
1046 1073 allowed_to_update = PullRequestModel().check_user_update(
1047 1074 pull_request, self._rhodecode_user)
1048 1075 if allowed_to_update:
1049 1076 controls = peppercorn.parse(self.request.POST.items())
1050 1077
1051 1078 if 'review_members' in controls:
1052 1079 self._update_reviewers(
1053 1080 pull_request, controls['review_members'],
1054 1081 pull_request.reviewer_data)
1055 1082 elif str2bool(self.request.POST.get('update_commits', 'false')):
1056 1083 self._update_commits(pull_request)
1057 1084 elif str2bool(self.request.POST.get('edit_pull_request', 'false')):
1058 1085 self._edit_pull_request(pull_request)
1059 1086 else:
1060 1087 raise HTTPBadRequest()
1061 1088 return True
1062 1089 raise HTTPForbidden()
1063 1090
1064 1091 def _edit_pull_request(self, pull_request):
1065 1092 _ = self.request.translate
1066 1093
1067 1094 try:
1068 1095 PullRequestModel().edit(
1069 1096 pull_request,
1070 1097 self.request.POST.get('title'),
1071 1098 self.request.POST.get('description'),
1072 1099 self.request.POST.get('description_renderer'),
1073 1100 self._rhodecode_user)
1074 1101 except ValueError:
1075 1102 msg = _(u'Cannot update closed pull requests.')
1076 1103 h.flash(msg, category='error')
1077 1104 return
1078 1105 else:
1079 1106 Session().commit()
1080 1107
1081 1108 msg = _(u'Pull request title & description updated.')
1082 1109 h.flash(msg, category='success')
1083 1110 return
1084 1111
1085 1112 def _update_commits(self, pull_request):
1086 1113 _ = self.request.translate
1087 resp = PullRequestModel().update_commits(pull_request)
1114
1115 with pull_request.set_state(PullRequest.STATE_UPDATING):
1116 resp = PullRequestModel().update_commits(pull_request)
1088 1117
1089 1118 if resp.executed:
1090 1119
1091 1120 if resp.target_changed and resp.source_changed:
1092 1121 changed = 'target and source repositories'
1093 1122 elif resp.target_changed and not resp.source_changed:
1094 1123 changed = 'target repository'
1095 1124 elif not resp.target_changed and resp.source_changed:
1096 1125 changed = 'source repository'
1097 1126 else:
1098 1127 changed = 'nothing'
1099 1128
1100 msg = _(
1101 u'Pull request updated to "{source_commit_id}" with '
1102 u'{count_added} added, {count_removed} removed commits. '
1103 u'Source of changes: {change_source}')
1129 msg = _(u'Pull request updated to "{source_commit_id}" with '
1130 u'{count_added} added, {count_removed} removed commits. '
1131 u'Source of changes: {change_source}')
1104 1132 msg = msg.format(
1105 1133 source_commit_id=pull_request.source_ref_parts.commit_id,
1106 1134 count_added=len(resp.changes.added),
1107 1135 count_removed=len(resp.changes.removed),
1108 1136 change_source=changed)
1109 1137 h.flash(msg, category='success')
1110 1138
1111 1139 channel = '/repo${}$/pr/{}'.format(
1112 pull_request.target_repo.repo_name,
1113 pull_request.pull_request_id)
1140 pull_request.target_repo.repo_name, pull_request.pull_request_id)
1114 1141 message = msg + (
1115 1142 ' - <a onclick="window.location.reload()">'
1116 1143 '<strong>{}</strong></a>'.format(_('Reload page')))
1117 1144 channelstream.post_message(
1118 1145 channel, message, self._rhodecode_user.username,
1119 1146 registry=self.request.registry)
1120 1147 else:
1121 1148 msg = PullRequestModel.UPDATE_STATUS_MESSAGES[resp.reason]
1122 1149 warning_reasons = [
1123 1150 UpdateFailureReason.NO_CHANGE,
1124 1151 UpdateFailureReason.WRONG_REF_TYPE,
1125 1152 ]
1126 1153 category = 'warning' if resp.reason in warning_reasons else 'error'
1127 1154 h.flash(msg, category=category)
1128 1155
1129 1156 @LoginRequired()
1130 1157 @NotAnonymous()
1131 1158 @HasRepoPermissionAnyDecorator(
1132 1159 'repository.read', 'repository.write', 'repository.admin')
1133 1160 @CSRFRequired()
1134 1161 @view_config(
1135 1162 route_name='pullrequest_merge', request_method='POST',
1136 1163 renderer='json_ext')
1137 1164 def pull_request_merge(self):
1138 1165 """
1139 1166 Merge will perform a server-side merge of the specified
1140 1167 pull request, if the pull request is approved and mergeable.
1141 1168 After successful merging, the pull request is automatically
1142 1169 closed, with a relevant comment.
1143 1170 """
1144 1171 pull_request = PullRequest.get_or_404(
1145 1172 self.request.matchdict['pull_request_id'])
1173 _ = self.request.translate
1174
1175 if pull_request.pull_request_state != PullRequest.STATE_CREATED:
1176 log.debug('show: forbidden because pull request is in state %s',
1177 pull_request.pull_request_state)
1178 msg = _(u'Cannot merge pull requests in state other than `{}`. '
1179 u'Current state is: `{}`').format(PullRequest.STATE_CREATED,
1180 pull_request.pull_request_state)
1181 h.flash(msg, category='error')
1182 raise HTTPFound(
1183 h.route_path('pullrequest_show',
1184 repo_name=pull_request.target_repo.repo_name,
1185 pull_request_id=pull_request.pull_request_id))
1146 1186
1147 1187 self.load_default_context()
1148 check = MergeCheck.validate(
1149 pull_request, auth_user=self._rhodecode_user,
1150 translator=self.request.translate)
1188
1189 with pull_request.set_state(PullRequest.STATE_UPDATING):
1190 check = MergeCheck.validate(
1191 pull_request, auth_user=self._rhodecode_user,
1192 translator=self.request.translate)
1151 1193 merge_possible = not check.failed
1152 1194
1153 1195 for err_type, error_msg in check.errors:
1154 1196 h.flash(error_msg, category=err_type)
1155 1197
1156 1198 if merge_possible:
1157 1199 log.debug("Pre-conditions checked, trying to merge.")
1158 1200 extras = vcs_operation_context(
1159 1201 self.request.environ, repo_name=pull_request.target_repo.repo_name,
1160 1202 username=self._rhodecode_db_user.username, action='push',
1161 1203 scm=pull_request.target_repo.repo_type)
1162 self._merge_pull_request(
1163 pull_request, self._rhodecode_db_user, extras)
1204 with pull_request.set_state(PullRequest.STATE_UPDATING):
1205 self._merge_pull_request(
1206 pull_request, self._rhodecode_db_user, extras)
1164 1207 else:
1165 1208 log.debug("Pre-conditions failed, NOT merging.")
1166 1209
1167 1210 raise HTTPFound(
1168 1211 h.route_path('pullrequest_show',
1169 1212 repo_name=pull_request.target_repo.repo_name,
1170 1213 pull_request_id=pull_request.pull_request_id))
1171 1214
1172 1215 def _merge_pull_request(self, pull_request, user, extras):
1173 1216 _ = self.request.translate
1174 1217 merge_resp = PullRequestModel().merge_repo(pull_request, user, extras=extras)
1175 1218
1176 1219 if merge_resp.executed:
1177 1220 log.debug("The merge was successful, closing the pull request.")
1178 1221 PullRequestModel().close_pull_request(
1179 1222 pull_request.pull_request_id, user)
1180 1223 Session().commit()
1181 1224 msg = _('Pull request was successfully merged and closed.')
1182 1225 h.flash(msg, category='success')
1183 1226 else:
1184 1227 log.debug(
1185 1228 "The merge was not successful. Merge response: %s", merge_resp)
1186 1229 msg = merge_resp.merge_status_message
1187 1230 h.flash(msg, category='error')
1188 1231
1189 1232 def _update_reviewers(self, pull_request, review_members, reviewer_rules):
1190 1233 _ = self.request.translate
1191 1234 get_default_reviewers_data, validate_default_reviewers = \
1192 1235 PullRequestModel().get_reviewer_functions()
1193 1236
1194 1237 try:
1195 1238 reviewers = validate_default_reviewers(review_members, reviewer_rules)
1196 1239 except ValueError as e:
1197 1240 log.error('Reviewers Validation: {}'.format(e))
1198 1241 h.flash(e, category='error')
1199 1242 return
1200 1243
1201 1244 PullRequestModel().update_reviewers(
1202 1245 pull_request, reviewers, self._rhodecode_user)
1203 1246 h.flash(_('Pull request reviewers updated.'), category='success')
1204 1247 Session().commit()
1205 1248
1206 1249 @LoginRequired()
1207 1250 @NotAnonymous()
1208 1251 @HasRepoPermissionAnyDecorator(
1209 1252 'repository.read', 'repository.write', 'repository.admin')
1210 1253 @CSRFRequired()
1211 1254 @view_config(
1212 1255 route_name='pullrequest_delete', request_method='POST',
1213 1256 renderer='json_ext')
1214 1257 def pull_request_delete(self):
1215 1258 _ = self.request.translate
1216 1259
1217 1260 pull_request = PullRequest.get_or_404(
1218 1261 self.request.matchdict['pull_request_id'])
1219 1262 self.load_default_context()
1220 1263
1221 1264 pr_closed = pull_request.is_closed()
1222 1265 allowed_to_delete = PullRequestModel().check_user_delete(
1223 1266 pull_request, self._rhodecode_user) and not pr_closed
1224 1267
1225 1268 # only owner can delete it !
1226 1269 if allowed_to_delete:
1227 1270 PullRequestModel().delete(pull_request, self._rhodecode_user)
1228 1271 Session().commit()
1229 1272 h.flash(_('Successfully deleted pull request'),
1230 1273 category='success')
1231 1274 raise HTTPFound(h.route_path('pullrequest_show_all',
1232 1275 repo_name=self.db_repo_name))
1233 1276
1234 1277 log.warning('user %s tried to delete pull request without access',
1235 1278 self._rhodecode_user)
1236 1279 raise HTTPNotFound()
1237 1280
1238 1281 @LoginRequired()
1239 1282 @NotAnonymous()
1240 1283 @HasRepoPermissionAnyDecorator(
1241 1284 'repository.read', 'repository.write', 'repository.admin')
1242 1285 @CSRFRequired()
1243 1286 @view_config(
1244 1287 route_name='pullrequest_comment_create', request_method='POST',
1245 1288 renderer='json_ext')
1246 1289 def pull_request_comment_create(self):
1247 1290 _ = self.request.translate
1248 1291
1249 1292 pull_request = PullRequest.get_or_404(
1250 1293 self.request.matchdict['pull_request_id'])
1251 1294 pull_request_id = pull_request.pull_request_id
1252 1295
1253 1296 if pull_request.is_closed():
1254 1297 log.debug('comment: forbidden because pull request is closed')
1255 1298 raise HTTPForbidden()
1256 1299
1257 1300 allowed_to_comment = PullRequestModel().check_user_comment(
1258 1301 pull_request, self._rhodecode_user)
1259 1302 if not allowed_to_comment:
1260 1303 log.debug(
1261 1304 'comment: forbidden because pull request is from forbidden repo')
1262 1305 raise HTTPForbidden()
1263 1306
1264 1307 c = self.load_default_context()
1265 1308
1266 1309 status = self.request.POST.get('changeset_status', None)
1267 1310 text = self.request.POST.get('text')
1268 1311 comment_type = self.request.POST.get('comment_type')
1269 1312 resolves_comment_id = self.request.POST.get('resolves_comment_id', None)
1270 1313 close_pull_request = self.request.POST.get('close_pull_request')
1271 1314
1272 1315 # the logic here should work like following, if we submit close
1273 1316 # pr comment, use `close_pull_request_with_comment` function
1274 1317 # else handle regular comment logic
1275 1318
1276 1319 if close_pull_request:
1277 1320 # only owner or admin or person with write permissions
1278 1321 allowed_to_close = PullRequestModel().check_user_update(
1279 1322 pull_request, self._rhodecode_user)
1280 1323 if not allowed_to_close:
1281 1324 log.debug('comment: forbidden because not allowed to close '
1282 1325 'pull request %s', pull_request_id)
1283 1326 raise HTTPForbidden()
1284 1327 comment, status = PullRequestModel().close_pull_request_with_comment(
1285 1328 pull_request, self._rhodecode_user, self.db_repo, message=text,
1286 1329 auth_user=self._rhodecode_user)
1287 1330 Session().flush()
1288 1331 events.trigger(
1289 1332 events.PullRequestCommentEvent(pull_request, comment))
1290 1333
1291 1334 else:
1292 1335 # regular comment case, could be inline, or one with status.
1293 1336 # for that one we check also permissions
1294 1337
1295 1338 allowed_to_change_status = PullRequestModel().check_user_change_status(
1296 1339 pull_request, self._rhodecode_user)
1297 1340
1298 1341 if status and allowed_to_change_status:
1299 1342 message = (_('Status change %(transition_icon)s %(status)s')
1300 1343 % {'transition_icon': '>',
1301 1344 'status': ChangesetStatus.get_status_lbl(status)})
1302 1345 text = text or message
1303 1346
1304 1347 comment = CommentsModel().create(
1305 1348 text=text,
1306 1349 repo=self.db_repo.repo_id,
1307 1350 user=self._rhodecode_user.user_id,
1308 1351 pull_request=pull_request,
1309 1352 f_path=self.request.POST.get('f_path'),
1310 1353 line_no=self.request.POST.get('line'),
1311 1354 status_change=(ChangesetStatus.get_status_lbl(status)
1312 1355 if status and allowed_to_change_status else None),
1313 1356 status_change_type=(status
1314 1357 if status and allowed_to_change_status else None),
1315 1358 comment_type=comment_type,
1316 1359 resolves_comment_id=resolves_comment_id,
1317 1360 auth_user=self._rhodecode_user
1318 1361 )
1319 1362
1320 1363 if allowed_to_change_status:
1321 1364 # calculate old status before we change it
1322 1365 old_calculated_status = pull_request.calculated_review_status()
1323 1366
1324 1367 # get status if set !
1325 1368 if status:
1326 1369 ChangesetStatusModel().set_status(
1327 1370 self.db_repo.repo_id,
1328 1371 status,
1329 1372 self._rhodecode_user.user_id,
1330 1373 comment,
1331 1374 pull_request=pull_request
1332 1375 )
1333 1376
1334 1377 Session().flush()
1335 1378 # this is somehow required to get access to some relationship
1336 1379 # loaded on comment
1337 1380 Session().refresh(comment)
1338 1381
1339 1382 events.trigger(
1340 1383 events.PullRequestCommentEvent(pull_request, comment))
1341 1384
1342 1385 # we now calculate the status of pull request, and based on that
1343 1386 # calculation we set the commits status
1344 1387 calculated_status = pull_request.calculated_review_status()
1345 1388 if old_calculated_status != calculated_status:
1346 1389 PullRequestModel()._trigger_pull_request_hook(
1347 1390 pull_request, self._rhodecode_user, 'review_status_change')
1348 1391
1349 1392 Session().commit()
1350 1393
1351 1394 data = {
1352 1395 'target_id': h.safeid(h.safe_unicode(
1353 1396 self.request.POST.get('f_path'))),
1354 1397 }
1355 1398 if comment:
1356 1399 c.co = comment
1357 1400 rendered_comment = render(
1358 1401 'rhodecode:templates/changeset/changeset_comment_block.mako',
1359 1402 self._get_template_context(c), self.request)
1360 1403
1361 1404 data.update(comment.get_dict())
1362 1405 data.update({'rendered_text': rendered_comment})
1363 1406
1364 1407 return data
1365 1408
1366 1409 @LoginRequired()
1367 1410 @NotAnonymous()
1368 1411 @HasRepoPermissionAnyDecorator(
1369 1412 'repository.read', 'repository.write', 'repository.admin')
1370 1413 @CSRFRequired()
1371 1414 @view_config(
1372 1415 route_name='pullrequest_comment_delete', request_method='POST',
1373 1416 renderer='json_ext')
1374 1417 def pull_request_comment_delete(self):
1375 1418 pull_request = PullRequest.get_or_404(
1376 1419 self.request.matchdict['pull_request_id'])
1377 1420
1378 1421 comment = ChangesetComment.get_or_404(
1379 1422 self.request.matchdict['comment_id'])
1380 1423 comment_id = comment.comment_id
1381 1424
1382 1425 if pull_request.is_closed():
1383 1426 log.debug('comment: forbidden because pull request is closed')
1384 1427 raise HTTPForbidden()
1385 1428
1386 1429 if not comment:
1387 1430 log.debug('Comment with id:%s not found, skipping', comment_id)
1388 1431 # comment already deleted in another call probably
1389 1432 return True
1390 1433
1391 1434 if comment.pull_request.is_closed():
1392 1435 # don't allow deleting comments on closed pull request
1393 1436 raise HTTPForbidden()
1394 1437
1395 1438 is_repo_admin = h.HasRepoPermissionAny('repository.admin')(self.db_repo_name)
1396 1439 super_admin = h.HasPermissionAny('hg.admin')()
1397 1440 comment_owner = comment.author.user_id == self._rhodecode_user.user_id
1398 1441 is_repo_comment = comment.repo.repo_name == self.db_repo_name
1399 1442 comment_repo_admin = is_repo_admin and is_repo_comment
1400 1443
1401 1444 if super_admin or comment_owner or comment_repo_admin:
1402 1445 old_calculated_status = comment.pull_request.calculated_review_status()
1403 1446 CommentsModel().delete(comment=comment, auth_user=self._rhodecode_user)
1404 1447 Session().commit()
1405 1448 calculated_status = comment.pull_request.calculated_review_status()
1406 1449 if old_calculated_status != calculated_status:
1407 1450 PullRequestModel()._trigger_pull_request_hook(
1408 1451 comment.pull_request, self._rhodecode_user, 'review_status_change')
1409 1452 return True
1410 1453 else:
1411 1454 log.warning('No permissions for user %s to delete comment_id: %s',
1412 1455 self._rhodecode_db_user, comment_id)
1413 1456 raise HTTPNotFound()
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now