##// END OF EJS Templates
api: comment_pull_request, added commit_id parameter to validate status changed on particular commit....
marcink -
r1269:26e59d48 default
parent child Browse files
Show More
@@ -1,146 +1,209 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2016 RhodeCode GmbH
3 # Copyright (C) 2010-2016 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import pytest
21 import pytest
22
22
23 from rhodecode.model.comment import ChangesetCommentsModel
23 from rhodecode.model.comment import ChangesetCommentsModel
24 from rhodecode.model.db import UserLog
24 from rhodecode.model.db import UserLog
25 from rhodecode.model.pull_request import PullRequestModel
25 from rhodecode.model.pull_request import PullRequestModel
26 from rhodecode.tests import TEST_USER_ADMIN_LOGIN
26 from rhodecode.tests import TEST_USER_ADMIN_LOGIN
27 from rhodecode.api.tests.utils import (
27 from rhodecode.api.tests.utils import (
28 build_data, api_call, assert_error, assert_ok)
28 build_data, api_call, assert_error, assert_ok)
29
29
30
30
31 @pytest.mark.usefixtures("testuser_api", "app")
31 @pytest.mark.usefixtures("testuser_api", "app")
32 class TestCommentPullRequest(object):
32 class TestCommentPullRequest(object):
33 finalizers = []
33 finalizers = []
34
34
35 def teardown_method(self, method):
35 def teardown_method(self, method):
36 if self.finalizers:
36 if self.finalizers:
37 for finalizer in self.finalizers:
37 for finalizer in self.finalizers:
38 finalizer()
38 finalizer()
39 self.finalizers = []
39 self.finalizers = []
40
40
41 @pytest.mark.backends("git", "hg")
41 @pytest.mark.backends("git", "hg")
42 def test_api_comment_pull_request(self, pr_util, no_notifications):
42 def test_api_comment_pull_request(self, pr_util, no_notifications):
43 pull_request = pr_util.create_pull_request()
43 pull_request = pr_util.create_pull_request()
44 pull_request_id = pull_request.pull_request_id
44 pull_request_id = pull_request.pull_request_id
45 author = pull_request.user_id
45 author = pull_request.user_id
46 repo = pull_request.target_repo.repo_id
46 repo = pull_request.target_repo.repo_id
47 id_, params = build_data(
47 id_, params = build_data(
48 self.apikey, 'comment_pull_request',
48 self.apikey, 'comment_pull_request',
49 repoid=pull_request.target_repo.repo_name,
49 repoid=pull_request.target_repo.repo_name,
50 pullrequestid=pull_request.pull_request_id,
50 pullrequestid=pull_request.pull_request_id,
51 message='test message')
51 message='test message')
52 response = api_call(self.app, params)
52 response = api_call(self.app, params)
53 pull_request = PullRequestModel().get(pull_request.pull_request_id)
53 pull_request = PullRequestModel().get(pull_request.pull_request_id)
54
54
55 comments = ChangesetCommentsModel().get_comments(
55 comments = ChangesetCommentsModel().get_comments(
56 pull_request.target_repo.repo_id, pull_request=pull_request)
56 pull_request.target_repo.repo_id, pull_request=pull_request)
57
57
58 expected = {
58 expected = {
59 'pull_request_id': pull_request.pull_request_id,
59 'pull_request_id': pull_request.pull_request_id,
60 'comment_id': comments[-1].comment_id,
60 'comment_id': comments[-1].comment_id,
61 'status': None
61 'status': {'given': None, 'was_changed': None}
62 }
62 }
63 assert_ok(id_, expected, response.body)
63 assert_ok(id_, expected, response.body)
64
64
65 action = 'user_commented_pull_request:%d' % pull_request_id
65 action = 'user_commented_pull_request:%d' % pull_request_id
66 journal = UserLog.query()\
66 journal = UserLog.query()\
67 .filter(UserLog.user_id == author)\
67 .filter(UserLog.user_id == author)\
68 .filter(UserLog.repository_id == repo)\
68 .filter(UserLog.repository_id == repo)\
69 .filter(UserLog.action == action)\
69 .filter(UserLog.action == action)\
70 .all()
70 .all()
71 assert len(journal) == 2
71 assert len(journal) == 2
72
72
73 @pytest.mark.backends("git", "hg")
73 @pytest.mark.backends("git", "hg")
74 def test_api_comment_pull_request_change_status(
74 def test_api_comment_pull_request_change_status(
75 self, pr_util, no_notifications):
75 self, pr_util, no_notifications):
76 pull_request = pr_util.create_pull_request()
76 pull_request = pr_util.create_pull_request()
77 pull_request_id = pull_request.pull_request_id
77 pull_request_id = pull_request.pull_request_id
78 id_, params = build_data(
78 id_, params = build_data(
79 self.apikey, 'comment_pull_request',
79 self.apikey, 'comment_pull_request',
80 repoid=pull_request.target_repo.repo_name,
80 repoid=pull_request.target_repo.repo_name,
81 pullrequestid=pull_request.pull_request_id,
81 pullrequestid=pull_request.pull_request_id,
82 status='rejected')
82 status='rejected')
83 response = api_call(self.app, params)
83 response = api_call(self.app, params)
84 pull_request = PullRequestModel().get(pull_request_id)
84 pull_request = PullRequestModel().get(pull_request_id)
85
85
86 comments = ChangesetCommentsModel().get_comments(
86 comments = ChangesetCommentsModel().get_comments(
87 pull_request.target_repo.repo_id, pull_request=pull_request)
87 pull_request.target_repo.repo_id, pull_request=pull_request)
88 expected = {
88 expected = {
89 'pull_request_id': pull_request.pull_request_id,
89 'pull_request_id': pull_request.pull_request_id,
90 'comment_id': comments[-1].comment_id,
90 'comment_id': comments[-1].comment_id,
91 'status': 'rejected'
91 'status': {'given': 'rejected', 'was_changed': True}
92 }
93 assert_ok(id_, expected, response.body)
94
95 @pytest.mark.backends("git", "hg")
96 def test_api_comment_pull_request_change_status_with_specific_commit_id(
97 self, pr_util, no_notifications):
98 pull_request = pr_util.create_pull_request()
99 pull_request_id = pull_request.pull_request_id
100 latest_commit_id = 'test_commit'
101 # inject additional revision, to fail test the status change on
102 # non-latest commit
103 pull_request.revisions = pull_request.revisions + ['test_commit']
104
105 id_, params = build_data(
106 self.apikey, 'comment_pull_request',
107 repoid=pull_request.target_repo.repo_name,
108 pullrequestid=pull_request.pull_request_id,
109 status='approved', commit_id=latest_commit_id)
110 response = api_call(self.app, params)
111 pull_request = PullRequestModel().get(pull_request_id)
112
113 expected = {
114 'pull_request_id': pull_request.pull_request_id,
115 'comment_id': None,
116 'status': {'given': 'approved', 'was_changed': False}
117 }
118 assert_ok(id_, expected, response.body)
119
120 @pytest.mark.backends("git", "hg")
121 def test_api_comment_pull_request_change_status_with_specific_commit_id(
122 self, pr_util, no_notifications):
123 pull_request = pr_util.create_pull_request()
124 pull_request_id = pull_request.pull_request_id
125 latest_commit_id = pull_request.revisions[0]
126
127 id_, params = build_data(
128 self.apikey, 'comment_pull_request',
129 repoid=pull_request.target_repo.repo_name,
130 pullrequestid=pull_request.pull_request_id,
131 status='approved', commit_id=latest_commit_id)
132 response = api_call(self.app, params)
133 pull_request = PullRequestModel().get(pull_request_id)
134
135 comments = ChangesetCommentsModel().get_comments(
136 pull_request.target_repo.repo_id, pull_request=pull_request)
137 expected = {
138 'pull_request_id': pull_request.pull_request_id,
139 'comment_id': comments[-1].comment_id,
140 'status': {'given': 'approved', 'was_changed': True}
92 }
141 }
93 assert_ok(id_, expected, response.body)
142 assert_ok(id_, expected, response.body)
94
143
95 @pytest.mark.backends("git", "hg")
144 @pytest.mark.backends("git", "hg")
96 def test_api_comment_pull_request_missing_params_error(self, pr_util):
145 def test_api_comment_pull_request_missing_params_error(self, pr_util):
97 pull_request = pr_util.create_pull_request()
146 pull_request = pr_util.create_pull_request()
98 pull_request_id = pull_request.pull_request_id
147 pull_request_id = pull_request.pull_request_id
99 pull_request_repo = pull_request.target_repo.repo_name
148 pull_request_repo = pull_request.target_repo.repo_name
100 id_, params = build_data(
149 id_, params = build_data(
101 self.apikey, 'comment_pull_request',
150 self.apikey, 'comment_pull_request',
102 repoid=pull_request_repo,
151 repoid=pull_request_repo,
103 pullrequestid=pull_request_id)
152 pullrequestid=pull_request_id)
104 response = api_call(self.app, params)
153 response = api_call(self.app, params)
105
154
106 expected = 'message and status parameter missing'
155 expected = 'Both message and status parameters are missing. At least one is required.'
107 assert_error(id_, expected, given=response.body)
156 assert_error(id_, expected, given=response.body)
108
157
109 @pytest.mark.backends("git", "hg")
158 @pytest.mark.backends("git", "hg")
110 def test_api_comment_pull_request_unknown_status_error(self, pr_util):
159 def test_api_comment_pull_request_unknown_status_error(self, pr_util):
111 pull_request = pr_util.create_pull_request()
160 pull_request = pr_util.create_pull_request()
112 pull_request_id = pull_request.pull_request_id
161 pull_request_id = pull_request.pull_request_id
113 pull_request_repo = pull_request.target_repo.repo_name
162 pull_request_repo = pull_request.target_repo.repo_name
114 id_, params = build_data(
163 id_, params = build_data(
115 self.apikey, 'comment_pull_request',
164 self.apikey, 'comment_pull_request',
116 repoid=pull_request_repo,
165 repoid=pull_request_repo,
117 pullrequestid=pull_request_id,
166 pullrequestid=pull_request_id,
118 status='42')
167 status='42')
119 response = api_call(self.app, params)
168 response = api_call(self.app, params)
120
169
121 expected = 'unknown comment status`42`'
170 expected = 'Unknown comment status: `42`'
122 assert_error(id_, expected, given=response.body)
171 assert_error(id_, expected, given=response.body)
123
172
124 @pytest.mark.backends("git", "hg")
173 @pytest.mark.backends("git", "hg")
125 def test_api_comment_pull_request_repo_error(self):
174 def test_api_comment_pull_request_repo_error(self):
126 id_, params = build_data(
175 id_, params = build_data(
127 self.apikey, 'comment_pull_request',
176 self.apikey, 'comment_pull_request',
128 repoid=666, pullrequestid=1)
177 repoid=666, pullrequestid=1)
129 response = api_call(self.app, params)
178 response = api_call(self.app, params)
130
179
131 expected = 'repository `666` does not exist'
180 expected = 'repository `666` does not exist'
132 assert_error(id_, expected, given=response.body)
181 assert_error(id_, expected, given=response.body)
133
182
134 @pytest.mark.backends("git", "hg")
183 @pytest.mark.backends("git", "hg")
135 def test_api_comment_pull_request_non_admin_with_userid_error(
184 def test_api_comment_pull_request_non_admin_with_userid_error(
136 self, pr_util):
185 self, pr_util):
137 pull_request = pr_util.create_pull_request()
186 pull_request = pr_util.create_pull_request()
138 id_, params = build_data(
187 id_, params = build_data(
139 self.apikey_regular, 'comment_pull_request',
188 self.apikey_regular, 'comment_pull_request',
140 repoid=pull_request.target_repo.repo_name,
189 repoid=pull_request.target_repo.repo_name,
141 pullrequestid=pull_request.pull_request_id,
190 pullrequestid=pull_request.pull_request_id,
142 userid=TEST_USER_ADMIN_LOGIN)
191 userid=TEST_USER_ADMIN_LOGIN)
143 response = api_call(self.app, params)
192 response = api_call(self.app, params)
144
193
145 expected = 'userid is not the same as your user'
194 expected = 'userid is not the same as your user'
146 assert_error(id_, expected, given=response.body)
195 assert_error(id_, expected, given=response.body)
196
197 @pytest.mark.backends("git", "hg")
198 def test_api_comment_pull_request_wrong_commit_id_error(self, pr_util):
199 pull_request = pr_util.create_pull_request()
200 id_, params = build_data(
201 self.apikey_regular, 'comment_pull_request',
202 repoid=pull_request.target_repo.repo_name,
203 status='approved',
204 pullrequestid=pull_request.pull_request_id,
205 commit_id='XXX')
206 response = api_call(self.app, params)
207
208 expected = 'Invalid commit_id `XXX` for this pull request.'
209 assert_error(id_, expected, given=response.body)
@@ -1,691 +1,714 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2016 RhodeCode GmbH
3 # Copyright (C) 2011-2016 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21
21
22 import logging
22 import logging
23
23
24 from rhodecode.api import jsonrpc_method, JSONRPCError
24 from rhodecode.api import jsonrpc_method, JSONRPCError
25 from rhodecode.api.utils import (
25 from rhodecode.api.utils import (
26 has_superadmin_permission, Optional, OAttr, get_repo_or_error,
26 has_superadmin_permission, Optional, OAttr, get_repo_or_error,
27 get_pull_request_or_error, get_commit_or_error, get_user_or_error,
27 get_pull_request_or_error, get_commit_or_error, get_user_or_error,
28 validate_repo_permissions, resolve_ref_or_error)
28 validate_repo_permissions, resolve_ref_or_error)
29 from rhodecode.lib.auth import (HasRepoPermissionAnyApi)
29 from rhodecode.lib.auth import (HasRepoPermissionAnyApi)
30 from rhodecode.lib.base import vcs_operation_context
30 from rhodecode.lib.base import vcs_operation_context
31 from rhodecode.lib.utils2 import str2bool
31 from rhodecode.lib.utils2 import str2bool
32 from rhodecode.model.changeset_status import ChangesetStatusModel
32 from rhodecode.model.changeset_status import ChangesetStatusModel
33 from rhodecode.model.comment import ChangesetCommentsModel
33 from rhodecode.model.comment import ChangesetCommentsModel
34 from rhodecode.model.db import Session, ChangesetStatus
34 from rhodecode.model.db import Session, ChangesetStatus
35 from rhodecode.model.pull_request import PullRequestModel
35 from rhodecode.model.pull_request import PullRequestModel
36 from rhodecode.model.settings import SettingsModel
36 from rhodecode.model.settings import SettingsModel
37
37
38 log = logging.getLogger(__name__)
38 log = logging.getLogger(__name__)
39
39
40
40
41 @jsonrpc_method()
41 @jsonrpc_method()
42 def get_pull_request(request, apiuser, repoid, pullrequestid):
42 def get_pull_request(request, apiuser, repoid, pullrequestid):
43 """
43 """
44 Get a pull request based on the given ID.
44 Get a pull request based on the given ID.
45
45
46 :param apiuser: This is filled automatically from the |authtoken|.
46 :param apiuser: This is filled automatically from the |authtoken|.
47 :type apiuser: AuthUser
47 :type apiuser: AuthUser
48 :param repoid: Repository name or repository ID from where the pull
48 :param repoid: Repository name or repository ID from where the pull
49 request was opened.
49 request was opened.
50 :type repoid: str or int
50 :type repoid: str or int
51 :param pullrequestid: ID of the requested pull request.
51 :param pullrequestid: ID of the requested pull request.
52 :type pullrequestid: int
52 :type pullrequestid: int
53
53
54 Example output:
54 Example output:
55
55
56 .. code-block:: bash
56 .. code-block:: bash
57
57
58 "id": <id_given_in_input>,
58 "id": <id_given_in_input>,
59 "result":
59 "result":
60 {
60 {
61 "pull_request_id": "<pull_request_id>",
61 "pull_request_id": "<pull_request_id>",
62 "url": "<url>",
62 "url": "<url>",
63 "title": "<title>",
63 "title": "<title>",
64 "description": "<description>",
64 "description": "<description>",
65 "status" : "<status>",
65 "status" : "<status>",
66 "created_on": "<date_time_created>",
66 "created_on": "<date_time_created>",
67 "updated_on": "<date_time_updated>",
67 "updated_on": "<date_time_updated>",
68 "commit_ids": [
68 "commit_ids": [
69 ...
69 ...
70 "<commit_id>",
70 "<commit_id>",
71 "<commit_id>",
71 "<commit_id>",
72 ...
72 ...
73 ],
73 ],
74 "review_status": "<review_status>",
74 "review_status": "<review_status>",
75 "mergeable": {
75 "mergeable": {
76 "status": "<bool>",
76 "status": "<bool>",
77 "message": "<message>",
77 "message": "<message>",
78 },
78 },
79 "source": {
79 "source": {
80 "clone_url": "<clone_url>",
80 "clone_url": "<clone_url>",
81 "repository": "<repository_name>",
81 "repository": "<repository_name>",
82 "reference":
82 "reference":
83 {
83 {
84 "name": "<name>",
84 "name": "<name>",
85 "type": "<type>",
85 "type": "<type>",
86 "commit_id": "<commit_id>",
86 "commit_id": "<commit_id>",
87 }
87 }
88 },
88 },
89 "target": {
89 "target": {
90 "clone_url": "<clone_url>",
90 "clone_url": "<clone_url>",
91 "repository": "<repository_name>",
91 "repository": "<repository_name>",
92 "reference":
92 "reference":
93 {
93 {
94 "name": "<name>",
94 "name": "<name>",
95 "type": "<type>",
95 "type": "<type>",
96 "commit_id": "<commit_id>",
96 "commit_id": "<commit_id>",
97 }
97 }
98 },
98 },
99 "merge": {
99 "merge": {
100 "clone_url": "<clone_url>",
100 "clone_url": "<clone_url>",
101 "reference":
101 "reference":
102 {
102 {
103 "name": "<name>",
103 "name": "<name>",
104 "type": "<type>",
104 "type": "<type>",
105 "commit_id": "<commit_id>",
105 "commit_id": "<commit_id>",
106 }
106 }
107 },
107 },
108 "author": <user_obj>,
108 "author": <user_obj>,
109 "reviewers": [
109 "reviewers": [
110 ...
110 ...
111 {
111 {
112 "user": "<user_obj>",
112 "user": "<user_obj>",
113 "review_status": "<review_status>",
113 "review_status": "<review_status>",
114 }
114 }
115 ...
115 ...
116 ]
116 ]
117 },
117 },
118 "error": null
118 "error": null
119 """
119 """
120 get_repo_or_error(repoid)
120 get_repo_or_error(repoid)
121 pull_request = get_pull_request_or_error(pullrequestid)
121 pull_request = get_pull_request_or_error(pullrequestid)
122 if not PullRequestModel().check_user_read(
122 if not PullRequestModel().check_user_read(
123 pull_request, apiuser, api=True):
123 pull_request, apiuser, api=True):
124 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
124 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
125 data = pull_request.get_api_data()
125 data = pull_request.get_api_data()
126 return data
126 return data
127
127
128
128
129 @jsonrpc_method()
129 @jsonrpc_method()
130 def get_pull_requests(request, apiuser, repoid, status=Optional('new')):
130 def get_pull_requests(request, apiuser, repoid, status=Optional('new')):
131 """
131 """
132 Get all pull requests from the repository specified in `repoid`.
132 Get all pull requests from the repository specified in `repoid`.
133
133
134 :param apiuser: This is filled automatically from the |authtoken|.
134 :param apiuser: This is filled automatically from the |authtoken|.
135 :type apiuser: AuthUser
135 :type apiuser: AuthUser
136 :param repoid: Repository name or repository ID.
136 :param repoid: Repository name or repository ID.
137 :type repoid: str or int
137 :type repoid: str or int
138 :param status: Only return pull requests with the specified status.
138 :param status: Only return pull requests with the specified status.
139 Valid options are.
139 Valid options are.
140 * ``new`` (default)
140 * ``new`` (default)
141 * ``open``
141 * ``open``
142 * ``closed``
142 * ``closed``
143 :type status: str
143 :type status: str
144
144
145 Example output:
145 Example output:
146
146
147 .. code-block:: bash
147 .. code-block:: bash
148
148
149 "id": <id_given_in_input>,
149 "id": <id_given_in_input>,
150 "result":
150 "result":
151 [
151 [
152 ...
152 ...
153 {
153 {
154 "pull_request_id": "<pull_request_id>",
154 "pull_request_id": "<pull_request_id>",
155 "url": "<url>",
155 "url": "<url>",
156 "title" : "<title>",
156 "title" : "<title>",
157 "description": "<description>",
157 "description": "<description>",
158 "status": "<status>",
158 "status": "<status>",
159 "created_on": "<date_time_created>",
159 "created_on": "<date_time_created>",
160 "updated_on": "<date_time_updated>",
160 "updated_on": "<date_time_updated>",
161 "commit_ids": [
161 "commit_ids": [
162 ...
162 ...
163 "<commit_id>",
163 "<commit_id>",
164 "<commit_id>",
164 "<commit_id>",
165 ...
165 ...
166 ],
166 ],
167 "review_status": "<review_status>",
167 "review_status": "<review_status>",
168 "mergeable": {
168 "mergeable": {
169 "status": "<bool>",
169 "status": "<bool>",
170 "message: "<message>",
170 "message: "<message>",
171 },
171 },
172 "source": {
172 "source": {
173 "clone_url": "<clone_url>",
173 "clone_url": "<clone_url>",
174 "reference":
174 "reference":
175 {
175 {
176 "name": "<name>",
176 "name": "<name>",
177 "type": "<type>",
177 "type": "<type>",
178 "commit_id": "<commit_id>",
178 "commit_id": "<commit_id>",
179 }
179 }
180 },
180 },
181 "target": {
181 "target": {
182 "clone_url": "<clone_url>",
182 "clone_url": "<clone_url>",
183 "reference":
183 "reference":
184 {
184 {
185 "name": "<name>",
185 "name": "<name>",
186 "type": "<type>",
186 "type": "<type>",
187 "commit_id": "<commit_id>",
187 "commit_id": "<commit_id>",
188 }
188 }
189 },
189 },
190 "merge": {
190 "merge": {
191 "clone_url": "<clone_url>",
191 "clone_url": "<clone_url>",
192 "reference":
192 "reference":
193 {
193 {
194 "name": "<name>",
194 "name": "<name>",
195 "type": "<type>",
195 "type": "<type>",
196 "commit_id": "<commit_id>",
196 "commit_id": "<commit_id>",
197 }
197 }
198 },
198 },
199 "author": <user_obj>,
199 "author": <user_obj>,
200 "reviewers": [
200 "reviewers": [
201 ...
201 ...
202 {
202 {
203 "user": "<user_obj>",
203 "user": "<user_obj>",
204 "review_status": "<review_status>",
204 "review_status": "<review_status>",
205 }
205 }
206 ...
206 ...
207 ]
207 ]
208 }
208 }
209 ...
209 ...
210 ],
210 ],
211 "error": null
211 "error": null
212
212
213 """
213 """
214 repo = get_repo_or_error(repoid)
214 repo = get_repo_or_error(repoid)
215 if not has_superadmin_permission(apiuser):
215 if not has_superadmin_permission(apiuser):
216 _perms = (
216 _perms = (
217 'repository.admin', 'repository.write', 'repository.read',)
217 'repository.admin', 'repository.write', 'repository.read',)
218 validate_repo_permissions(apiuser, repoid, repo, _perms)
218 validate_repo_permissions(apiuser, repoid, repo, _perms)
219
219
220 status = Optional.extract(status)
220 status = Optional.extract(status)
221 pull_requests = PullRequestModel().get_all(repo, statuses=[status])
221 pull_requests = PullRequestModel().get_all(repo, statuses=[status])
222 data = [pr.get_api_data() for pr in pull_requests]
222 data = [pr.get_api_data() for pr in pull_requests]
223 return data
223 return data
224
224
225
225
226 @jsonrpc_method()
226 @jsonrpc_method()
227 def merge_pull_request(request, apiuser, repoid, pullrequestid,
227 def merge_pull_request(request, apiuser, repoid, pullrequestid,
228 userid=Optional(OAttr('apiuser'))):
228 userid=Optional(OAttr('apiuser'))):
229 """
229 """
230 Merge the pull request specified by `pullrequestid` into its target
230 Merge the pull request specified by `pullrequestid` into its target
231 repository.
231 repository.
232
232
233 :param apiuser: This is filled automatically from the |authtoken|.
233 :param apiuser: This is filled automatically from the |authtoken|.
234 :type apiuser: AuthUser
234 :type apiuser: AuthUser
235 :param repoid: The Repository name or repository ID of the
235 :param repoid: The Repository name or repository ID of the
236 target repository to which the |pr| is to be merged.
236 target repository to which the |pr| is to be merged.
237 :type repoid: str or int
237 :type repoid: str or int
238 :param pullrequestid: ID of the pull request which shall be merged.
238 :param pullrequestid: ID of the pull request which shall be merged.
239 :type pullrequestid: int
239 :type pullrequestid: int
240 :param userid: Merge the pull request as this user.
240 :param userid: Merge the pull request as this user.
241 :type userid: Optional(str or int)
241 :type userid: Optional(str or int)
242
242
243 Example output:
243 Example output:
244
244
245 .. code-block:: bash
245 .. code-block:: bash
246
246
247 "id": <id_given_in_input>,
247 "id": <id_given_in_input>,
248 "result":
248 "result":
249 {
249 {
250 "executed": "<bool>",
250 "executed": "<bool>",
251 "failure_reason": "<int>",
251 "failure_reason": "<int>",
252 "merge_commit_id": "<merge_commit_id>",
252 "merge_commit_id": "<merge_commit_id>",
253 "possible": "<bool>",
253 "possible": "<bool>",
254 "merge_ref": {
254 "merge_ref": {
255 "commit_id": "<commit_id>",
255 "commit_id": "<commit_id>",
256 "type": "<type>",
256 "type": "<type>",
257 "name": "<name>"
257 "name": "<name>"
258 }
258 }
259 },
259 },
260 "error": null
260 "error": null
261
261
262 """
262 """
263 repo = get_repo_or_error(repoid)
263 repo = get_repo_or_error(repoid)
264 if not isinstance(userid, Optional):
264 if not isinstance(userid, Optional):
265 if (has_superadmin_permission(apiuser) or
265 if (has_superadmin_permission(apiuser) or
266 HasRepoPermissionAnyApi('repository.admin')(
266 HasRepoPermissionAnyApi('repository.admin')(
267 user=apiuser, repo_name=repo.repo_name)):
267 user=apiuser, repo_name=repo.repo_name)):
268 apiuser = get_user_or_error(userid)
268 apiuser = get_user_or_error(userid)
269 else:
269 else:
270 raise JSONRPCError('userid is not the same as your user')
270 raise JSONRPCError('userid is not the same as your user')
271
271
272 pull_request = get_pull_request_or_error(pullrequestid)
272 pull_request = get_pull_request_or_error(pullrequestid)
273 if not PullRequestModel().check_user_merge(
273 if not PullRequestModel().check_user_merge(
274 pull_request, apiuser, api=True):
274 pull_request, apiuser, api=True):
275 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
275 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
276 if pull_request.is_closed():
276 if pull_request.is_closed():
277 raise JSONRPCError(
277 raise JSONRPCError(
278 'pull request `%s` merge failed, pull request is closed' % (
278 'pull request `%s` merge failed, pull request is closed' % (
279 pullrequestid,))
279 pullrequestid,))
280
280
281 target_repo = pull_request.target_repo
281 target_repo = pull_request.target_repo
282 extras = vcs_operation_context(
282 extras = vcs_operation_context(
283 request.environ, repo_name=target_repo.repo_name,
283 request.environ, repo_name=target_repo.repo_name,
284 username=apiuser.username, action='push',
284 username=apiuser.username, action='push',
285 scm=target_repo.repo_type)
285 scm=target_repo.repo_type)
286 merge_response = PullRequestModel().merge(
286 merge_response = PullRequestModel().merge(
287 pull_request, apiuser, extras=extras)
287 pull_request, apiuser, extras=extras)
288 if merge_response.executed:
288 if merge_response.executed:
289 PullRequestModel().close_pull_request(
289 PullRequestModel().close_pull_request(
290 pull_request.pull_request_id, apiuser)
290 pull_request.pull_request_id, apiuser)
291
291
292 Session().commit()
292 Session().commit()
293
293
294 # In previous versions the merge response directly contained the merge
294 # In previous versions the merge response directly contained the merge
295 # commit id. It is now contained in the merge reference object. To be
295 # commit id. It is now contained in the merge reference object. To be
296 # backwards compatible we have to extract it again.
296 # backwards compatible we have to extract it again.
297 merge_response = merge_response._asdict()
297 merge_response = merge_response._asdict()
298 merge_response['merge_commit_id'] = merge_response['merge_ref'].commit_id
298 merge_response['merge_commit_id'] = merge_response['merge_ref'].commit_id
299
299
300 return merge_response
300 return merge_response
301
301
302
302
303 @jsonrpc_method()
303 @jsonrpc_method()
304 def close_pull_request(request, apiuser, repoid, pullrequestid,
304 def close_pull_request(request, apiuser, repoid, pullrequestid,
305 userid=Optional(OAttr('apiuser'))):
305 userid=Optional(OAttr('apiuser'))):
306 """
306 """
307 Close the pull request specified by `pullrequestid`.
307 Close the pull request specified by `pullrequestid`.
308
308
309 :param apiuser: This is filled automatically from the |authtoken|.
309 :param apiuser: This is filled automatically from the |authtoken|.
310 :type apiuser: AuthUser
310 :type apiuser: AuthUser
311 :param repoid: Repository name or repository ID to which the pull
311 :param repoid: Repository name or repository ID to which the pull
312 request belongs.
312 request belongs.
313 :type repoid: str or int
313 :type repoid: str or int
314 :param pullrequestid: ID of the pull request to be closed.
314 :param pullrequestid: ID of the pull request to be closed.
315 :type pullrequestid: int
315 :type pullrequestid: int
316 :param userid: Close the pull request as this user.
316 :param userid: Close the pull request as this user.
317 :type userid: Optional(str or int)
317 :type userid: Optional(str or int)
318
318
319 Example output:
319 Example output:
320
320
321 .. code-block:: bash
321 .. code-block:: bash
322
322
323 "id": <id_given_in_input>,
323 "id": <id_given_in_input>,
324 "result":
324 "result":
325 {
325 {
326 "pull_request_id": "<int>",
326 "pull_request_id": "<int>",
327 "closed": "<bool>"
327 "closed": "<bool>"
328 },
328 },
329 "error": null
329 "error": null
330
330
331 """
331 """
332 repo = get_repo_or_error(repoid)
332 repo = get_repo_or_error(repoid)
333 if not isinstance(userid, Optional):
333 if not isinstance(userid, Optional):
334 if (has_superadmin_permission(apiuser) or
334 if (has_superadmin_permission(apiuser) or
335 HasRepoPermissionAnyApi('repository.admin')(
335 HasRepoPermissionAnyApi('repository.admin')(
336 user=apiuser, repo_name=repo.repo_name)):
336 user=apiuser, repo_name=repo.repo_name)):
337 apiuser = get_user_or_error(userid)
337 apiuser = get_user_or_error(userid)
338 else:
338 else:
339 raise JSONRPCError('userid is not the same as your user')
339 raise JSONRPCError('userid is not the same as your user')
340
340
341 pull_request = get_pull_request_or_error(pullrequestid)
341 pull_request = get_pull_request_or_error(pullrequestid)
342 if not PullRequestModel().check_user_update(
342 if not PullRequestModel().check_user_update(
343 pull_request, apiuser, api=True):
343 pull_request, apiuser, api=True):
344 raise JSONRPCError(
344 raise JSONRPCError(
345 'pull request `%s` close failed, no permission to close.' % (
345 'pull request `%s` close failed, no permission to close.' % (
346 pullrequestid,))
346 pullrequestid,))
347 if pull_request.is_closed():
347 if pull_request.is_closed():
348 raise JSONRPCError(
348 raise JSONRPCError(
349 'pull request `%s` is already closed' % (pullrequestid,))
349 'pull request `%s` is already closed' % (pullrequestid,))
350
350
351 PullRequestModel().close_pull_request(
351 PullRequestModel().close_pull_request(
352 pull_request.pull_request_id, apiuser)
352 pull_request.pull_request_id, apiuser)
353 Session().commit()
353 Session().commit()
354 data = {
354 data = {
355 'pull_request_id': pull_request.pull_request_id,
355 'pull_request_id': pull_request.pull_request_id,
356 'closed': True,
356 'closed': True,
357 }
357 }
358 return data
358 return data
359
359
360
360
361 @jsonrpc_method()
361 @jsonrpc_method()
362 def comment_pull_request(request, apiuser, repoid, pullrequestid,
362 def comment_pull_request(request, apiuser, repoid, pullrequestid,
363 message=Optional(None), status=Optional(None),
363 message=Optional(None), status=Optional(None),
364 commit_id=Optional(None),
364 userid=Optional(OAttr('apiuser'))):
365 userid=Optional(OAttr('apiuser'))):
365 """
366 """
366 Comment on the pull request specified with the `pullrequestid`,
367 Comment on the pull request specified with the `pullrequestid`,
367 in the |repo| specified by the `repoid`, and optionally change the
368 in the |repo| specified by the `repoid`, and optionally change the
368 review status.
369 review status.
369
370
370 :param apiuser: This is filled automatically from the |authtoken|.
371 :param apiuser: This is filled automatically from the |authtoken|.
371 :type apiuser: AuthUser
372 :type apiuser: AuthUser
372 :param repoid: The repository name or repository ID.
373 :param repoid: The repository name or repository ID.
373 :type repoid: str or int
374 :type repoid: str or int
374 :param pullrequestid: The pull request ID.
375 :param pullrequestid: The pull request ID.
375 :type pullrequestid: int
376 :type pullrequestid: int
376 :param message: The text content of the comment.
377 :param message: The text content of the comment.
377 :type message: str
378 :type message: str
378 :param status: (**Optional**) Set the approval status of the pull
379 :param status: (**Optional**) Set the approval status of the pull
379 request. Valid options are:
380 request. Valid options are:
380 * not_reviewed
381 * not_reviewed
381 * approved
382 * approved
382 * rejected
383 * rejected
383 * under_review
384 * under_review
384 :type status: str
385 :type status: str
386 :param commit_id: Specify the commit_id for which to set a comment. If
387 given commit_id is different than latest in the PR status
388 change won't be performed.
389 :type commit_id: str
385 :param userid: Comment on the pull request as this user
390 :param userid: Comment on the pull request as this user
386 :type userid: Optional(str or int)
391 :type userid: Optional(str or int)
387
392
388 Example output:
393 Example output:
389
394
390 .. code-block:: bash
395 .. code-block:: bash
391
396
392 id : <id_given_in_input>
397 id : <id_given_in_input>
393 result :
398 result :
394 {
399 {
395 "pull_request_id": "<Integer>",
400 "pull_request_id": "<Integer>",
396 "comment_id": "<Integer>"
401 "comment_id": "<Integer>",
402 "status": {"given": <given_status>,
403 "was_changed": <bool status_was_actually_changed> },
397 }
404 }
398 error : null
405 error : null
399 """
406 """
400 repo = get_repo_or_error(repoid)
407 repo = get_repo_or_error(repoid)
401 if not isinstance(userid, Optional):
408 if not isinstance(userid, Optional):
402 if (has_superadmin_permission(apiuser) or
409 if (has_superadmin_permission(apiuser) or
403 HasRepoPermissionAnyApi('repository.admin')(
410 HasRepoPermissionAnyApi('repository.admin')(
404 user=apiuser, repo_name=repo.repo_name)):
411 user=apiuser, repo_name=repo.repo_name)):
405 apiuser = get_user_or_error(userid)
412 apiuser = get_user_or_error(userid)
406 else:
413 else:
407 raise JSONRPCError('userid is not the same as your user')
414 raise JSONRPCError('userid is not the same as your user')
408
415
409 pull_request = get_pull_request_or_error(pullrequestid)
416 pull_request = get_pull_request_or_error(pullrequestid)
410 if not PullRequestModel().check_user_read(
417 if not PullRequestModel().check_user_read(
411 pull_request, apiuser, api=True):
418 pull_request, apiuser, api=True):
412 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
419 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
413 message = Optional.extract(message)
420 message = Optional.extract(message)
414 status = Optional.extract(status)
421 status = Optional.extract(status)
422 commit_id = Optional.extract(commit_id)
423
415 if not message and not status:
424 if not message and not status:
416 raise JSONRPCError('message and status parameter missing')
425 raise JSONRPCError(
426 'Both message and status parameters are missing. '
427 'At least one is required.')
417
428
418 if (status not in (st[0] for st in ChangesetStatus.STATUSES) and
429 if (status not in (st[0] for st in ChangesetStatus.STATUSES) and
419 status is not None):
430 status is not None):
420 raise JSONRPCError('unknown comment status`%s`' % status)
431 raise JSONRPCError('Unknown comment status: `%s`' % status)
432
433 if commit_id and commit_id not in pull_request.revisions:
434 raise JSONRPCError(
435 'Invalid commit_id `%s` for this pull request.' % commit_id)
421
436
422 allowed_to_change_status = PullRequestModel().check_user_change_status(
437 allowed_to_change_status = PullRequestModel().check_user_change_status(
423 pull_request, apiuser)
438 pull_request, apiuser)
439
440 # if commit_id is passed re-validated if user is allowed to change status
441 # based on latest commit_id from the PR
442 if commit_id:
443 commit_idx = pull_request.revisions.index(commit_id)
444 if commit_idx != 0:
445 allowed_to_change_status = False
446
424 text = message
447 text = message
448 status_label = ChangesetStatus.get_status_lbl(status)
425 if status and allowed_to_change_status:
449 if status and allowed_to_change_status:
426 st_message = (('Status change %(transition_icon)s %(status)s')
450 st_message = ('Status change %(transition_icon)s %(status)s'
427 % {'transition_icon': '>',
451 % {'transition_icon': '>', 'status': status_label})
428 'status': ChangesetStatus.get_status_lbl(status)})
429 text = message or st_message
452 text = message or st_message
430
453
431 rc_config = SettingsModel().get_all_settings()
454 rc_config = SettingsModel().get_all_settings()
432 renderer = rc_config.get('rhodecode_markup_renderer', 'rst')
455 renderer = rc_config.get('rhodecode_markup_renderer', 'rst')
456
457 status_change = status and allowed_to_change_status
433 comment = ChangesetCommentsModel().create(
458 comment = ChangesetCommentsModel().create(
434 text=text,
459 text=text,
435 repo=pull_request.target_repo.repo_id,
460 repo=pull_request.target_repo.repo_id,
436 user=apiuser.user_id,
461 user=apiuser.user_id,
437 pull_request=pull_request.pull_request_id,
462 pull_request=pull_request.pull_request_id,
438 f_path=None,
463 f_path=None,
439 line_no=None,
464 line_no=None,
440 status_change=(ChangesetStatus.get_status_lbl(status)
465 status_change=(status_label if status_change else None),
441 if status and allowed_to_change_status else None),
466 status_change_type=(status if status_change else None),
442 status_change_type=(status
443 if status and allowed_to_change_status else None),
444 closing_pr=False,
467 closing_pr=False,
445 renderer=renderer
468 renderer=renderer
446 )
469 )
447
470
448 if allowed_to_change_status and status:
471 if allowed_to_change_status and status:
449 ChangesetStatusModel().set_status(
472 ChangesetStatusModel().set_status(
450 pull_request.target_repo.repo_id,
473 pull_request.target_repo.repo_id,
451 status,
474 status,
452 apiuser.user_id,
475 apiuser.user_id,
453 comment,
476 comment,
454 pull_request=pull_request.pull_request_id
477 pull_request=pull_request.pull_request_id
455 )
478 )
456 Session().flush()
479 Session().flush()
457
480
458 Session().commit()
481 Session().commit()
459 data = {
482 data = {
460 'pull_request_id': pull_request.pull_request_id,
483 'pull_request_id': pull_request.pull_request_id,
461 'comment_id': comment.comment_id,
484 'comment_id': comment.comment_id if comment else None,
462 'status': status
485 'status': {'given': status, 'was_changed': status_change},
463 }
486 }
464 return data
487 return data
465
488
466
489
467 @jsonrpc_method()
490 @jsonrpc_method()
468 def create_pull_request(
491 def create_pull_request(
469 request, apiuser, source_repo, target_repo, source_ref, target_ref,
492 request, apiuser, source_repo, target_repo, source_ref, target_ref,
470 title, description=Optional(''), reviewers=Optional(None)):
493 title, description=Optional(''), reviewers=Optional(None)):
471 """
494 """
472 Creates a new pull request.
495 Creates a new pull request.
473
496
474 Accepts refs in the following formats:
497 Accepts refs in the following formats:
475
498
476 * branch:<branch_name>:<sha>
499 * branch:<branch_name>:<sha>
477 * branch:<branch_name>
500 * branch:<branch_name>
478 * bookmark:<bookmark_name>:<sha> (Mercurial only)
501 * bookmark:<bookmark_name>:<sha> (Mercurial only)
479 * bookmark:<bookmark_name> (Mercurial only)
502 * bookmark:<bookmark_name> (Mercurial only)
480
503
481 :param apiuser: This is filled automatically from the |authtoken|.
504 :param apiuser: This is filled automatically from the |authtoken|.
482 :type apiuser: AuthUser
505 :type apiuser: AuthUser
483 :param source_repo: Set the source repository name.
506 :param source_repo: Set the source repository name.
484 :type source_repo: str
507 :type source_repo: str
485 :param target_repo: Set the target repository name.
508 :param target_repo: Set the target repository name.
486 :type target_repo: str
509 :type target_repo: str
487 :param source_ref: Set the source ref name.
510 :param source_ref: Set the source ref name.
488 :type source_ref: str
511 :type source_ref: str
489 :param target_ref: Set the target ref name.
512 :param target_ref: Set the target ref name.
490 :type target_ref: str
513 :type target_ref: str
491 :param title: Set the pull request title.
514 :param title: Set the pull request title.
492 :type title: str
515 :type title: str
493 :param description: Set the pull request description.
516 :param description: Set the pull request description.
494 :type description: Optional(str)
517 :type description: Optional(str)
495 :param reviewers: Set the new pull request reviewers list.
518 :param reviewers: Set the new pull request reviewers list.
496 :type reviewers: Optional(list)
519 :type reviewers: Optional(list)
497 Accepts username strings or objects of the format:
520 Accepts username strings or objects of the format:
498 {
521 {
499 'username': 'nick', 'reasons': ['original author']
522 'username': 'nick', 'reasons': ['original author']
500 }
523 }
501 """
524 """
502
525
503 source = get_repo_or_error(source_repo)
526 source = get_repo_or_error(source_repo)
504 target = get_repo_or_error(target_repo)
527 target = get_repo_or_error(target_repo)
505 if not has_superadmin_permission(apiuser):
528 if not has_superadmin_permission(apiuser):
506 _perms = ('repository.admin', 'repository.write', 'repository.read',)
529 _perms = ('repository.admin', 'repository.write', 'repository.read',)
507 validate_repo_permissions(apiuser, source_repo, source, _perms)
530 validate_repo_permissions(apiuser, source_repo, source, _perms)
508
531
509 full_source_ref = resolve_ref_or_error(source_ref, source)
532 full_source_ref = resolve_ref_or_error(source_ref, source)
510 full_target_ref = resolve_ref_or_error(target_ref, target)
533 full_target_ref = resolve_ref_or_error(target_ref, target)
511 source_commit = get_commit_or_error(full_source_ref, source)
534 source_commit = get_commit_or_error(full_source_ref, source)
512 target_commit = get_commit_or_error(full_target_ref, target)
535 target_commit = get_commit_or_error(full_target_ref, target)
513 source_scm = source.scm_instance()
536 source_scm = source.scm_instance()
514 target_scm = target.scm_instance()
537 target_scm = target.scm_instance()
515
538
516 commit_ranges = target_scm.compare(
539 commit_ranges = target_scm.compare(
517 target_commit.raw_id, source_commit.raw_id, source_scm,
540 target_commit.raw_id, source_commit.raw_id, source_scm,
518 merge=True, pre_load=[])
541 merge=True, pre_load=[])
519
542
520 ancestor = target_scm.get_common_ancestor(
543 ancestor = target_scm.get_common_ancestor(
521 target_commit.raw_id, source_commit.raw_id, source_scm)
544 target_commit.raw_id, source_commit.raw_id, source_scm)
522
545
523 if not commit_ranges:
546 if not commit_ranges:
524 raise JSONRPCError('no commits found')
547 raise JSONRPCError('no commits found')
525
548
526 if not ancestor:
549 if not ancestor:
527 raise JSONRPCError('no common ancestor found')
550 raise JSONRPCError('no common ancestor found')
528
551
529 reviewer_objects = Optional.extract(reviewers) or []
552 reviewer_objects = Optional.extract(reviewers) or []
530 if not isinstance(reviewer_objects, list):
553 if not isinstance(reviewer_objects, list):
531 raise JSONRPCError('reviewers should be specified as a list')
554 raise JSONRPCError('reviewers should be specified as a list')
532
555
533 reviewers_reasons = []
556 reviewers_reasons = []
534 for reviewer_object in reviewer_objects:
557 for reviewer_object in reviewer_objects:
535 reviewer_reasons = []
558 reviewer_reasons = []
536 if isinstance(reviewer_object, (basestring, int)):
559 if isinstance(reviewer_object, (basestring, int)):
537 reviewer_username = reviewer_object
560 reviewer_username = reviewer_object
538 else:
561 else:
539 reviewer_username = reviewer_object['username']
562 reviewer_username = reviewer_object['username']
540 reviewer_reasons = reviewer_object.get('reasons', [])
563 reviewer_reasons = reviewer_object.get('reasons', [])
541
564
542 user = get_user_or_error(reviewer_username)
565 user = get_user_or_error(reviewer_username)
543 reviewers_reasons.append((user.user_id, reviewer_reasons))
566 reviewers_reasons.append((user.user_id, reviewer_reasons))
544
567
545 pull_request_model = PullRequestModel()
568 pull_request_model = PullRequestModel()
546 pull_request = pull_request_model.create(
569 pull_request = pull_request_model.create(
547 created_by=apiuser.user_id,
570 created_by=apiuser.user_id,
548 source_repo=source_repo,
571 source_repo=source_repo,
549 source_ref=full_source_ref,
572 source_ref=full_source_ref,
550 target_repo=target_repo,
573 target_repo=target_repo,
551 target_ref=full_target_ref,
574 target_ref=full_target_ref,
552 revisions=reversed(
575 revisions=reversed(
553 [commit.raw_id for commit in reversed(commit_ranges)]),
576 [commit.raw_id for commit in reversed(commit_ranges)]),
554 reviewers=reviewers_reasons,
577 reviewers=reviewers_reasons,
555 title=title,
578 title=title,
556 description=Optional.extract(description)
579 description=Optional.extract(description)
557 )
580 )
558
581
559 Session().commit()
582 Session().commit()
560 data = {
583 data = {
561 'msg': 'Created new pull request `{}`'.format(title),
584 'msg': 'Created new pull request `{}`'.format(title),
562 'pull_request_id': pull_request.pull_request_id,
585 'pull_request_id': pull_request.pull_request_id,
563 }
586 }
564 return data
587 return data
565
588
566
589
567 @jsonrpc_method()
590 @jsonrpc_method()
568 def update_pull_request(
591 def update_pull_request(
569 request, apiuser, repoid, pullrequestid, title=Optional(''),
592 request, apiuser, repoid, pullrequestid, title=Optional(''),
570 description=Optional(''), reviewers=Optional(None),
593 description=Optional(''), reviewers=Optional(None),
571 update_commits=Optional(None), close_pull_request=Optional(None)):
594 update_commits=Optional(None), close_pull_request=Optional(None)):
572 """
595 """
573 Updates a pull request.
596 Updates a pull request.
574
597
575 :param apiuser: This is filled automatically from the |authtoken|.
598 :param apiuser: This is filled automatically from the |authtoken|.
576 :type apiuser: AuthUser
599 :type apiuser: AuthUser
577 :param repoid: The repository name or repository ID.
600 :param repoid: The repository name or repository ID.
578 :type repoid: str or int
601 :type repoid: str or int
579 :param pullrequestid: The pull request ID.
602 :param pullrequestid: The pull request ID.
580 :type pullrequestid: int
603 :type pullrequestid: int
581 :param title: Set the pull request title.
604 :param title: Set the pull request title.
582 :type title: str
605 :type title: str
583 :param description: Update pull request description.
606 :param description: Update pull request description.
584 :type description: Optional(str)
607 :type description: Optional(str)
585 :param reviewers: Update pull request reviewers list with new value.
608 :param reviewers: Update pull request reviewers list with new value.
586 :type reviewers: Optional(list)
609 :type reviewers: Optional(list)
587 :param update_commits: Trigger update of commits for this pull request
610 :param update_commits: Trigger update of commits for this pull request
588 :type: update_commits: Optional(bool)
611 :type: update_commits: Optional(bool)
589 :param close_pull_request: Close this pull request with rejected state
612 :param close_pull_request: Close this pull request with rejected state
590 :type: close_pull_request: Optional(bool)
613 :type: close_pull_request: Optional(bool)
591
614
592 Example output:
615 Example output:
593
616
594 .. code-block:: bash
617 .. code-block:: bash
595
618
596 id : <id_given_in_input>
619 id : <id_given_in_input>
597 result :
620 result :
598 {
621 {
599 "msg": "Updated pull request `63`",
622 "msg": "Updated pull request `63`",
600 "pull_request": <pull_request_object>,
623 "pull_request": <pull_request_object>,
601 "updated_reviewers": {
624 "updated_reviewers": {
602 "added": [
625 "added": [
603 "username"
626 "username"
604 ],
627 ],
605 "removed": []
628 "removed": []
606 },
629 },
607 "updated_commits": {
630 "updated_commits": {
608 "added": [
631 "added": [
609 "<sha1_hash>"
632 "<sha1_hash>"
610 ],
633 ],
611 "common": [
634 "common": [
612 "<sha1_hash>",
635 "<sha1_hash>",
613 "<sha1_hash>",
636 "<sha1_hash>",
614 ],
637 ],
615 "removed": []
638 "removed": []
616 }
639 }
617 }
640 }
618 error : null
641 error : null
619 """
642 """
620
643
621 repo = get_repo_or_error(repoid)
644 repo = get_repo_or_error(repoid)
622 pull_request = get_pull_request_or_error(pullrequestid)
645 pull_request = get_pull_request_or_error(pullrequestid)
623 if not PullRequestModel().check_user_update(
646 if not PullRequestModel().check_user_update(
624 pull_request, apiuser, api=True):
647 pull_request, apiuser, api=True):
625 raise JSONRPCError(
648 raise JSONRPCError(
626 'pull request `%s` update failed, no permission to update.' % (
649 'pull request `%s` update failed, no permission to update.' % (
627 pullrequestid,))
650 pullrequestid,))
628 if pull_request.is_closed():
651 if pull_request.is_closed():
629 raise JSONRPCError(
652 raise JSONRPCError(
630 'pull request `%s` update failed, pull request is closed' % (
653 'pull request `%s` update failed, pull request is closed' % (
631 pullrequestid,))
654 pullrequestid,))
632
655
633 reviewer_objects = Optional.extract(reviewers) or []
656 reviewer_objects = Optional.extract(reviewers) or []
634 if not isinstance(reviewer_objects, list):
657 if not isinstance(reviewer_objects, list):
635 raise JSONRPCError('reviewers should be specified as a list')
658 raise JSONRPCError('reviewers should be specified as a list')
636
659
637 reviewers_reasons = []
660 reviewers_reasons = []
638 reviewer_ids = set()
661 reviewer_ids = set()
639 for reviewer_object in reviewer_objects:
662 for reviewer_object in reviewer_objects:
640 reviewer_reasons = []
663 reviewer_reasons = []
641 if isinstance(reviewer_object, (int, basestring)):
664 if isinstance(reviewer_object, (int, basestring)):
642 reviewer_username = reviewer_object
665 reviewer_username = reviewer_object
643 else:
666 else:
644 reviewer_username = reviewer_object['username']
667 reviewer_username = reviewer_object['username']
645 reviewer_reasons = reviewer_object.get('reasons', [])
668 reviewer_reasons = reviewer_object.get('reasons', [])
646
669
647 user = get_user_or_error(reviewer_username)
670 user = get_user_or_error(reviewer_username)
648 reviewer_ids.add(user.user_id)
671 reviewer_ids.add(user.user_id)
649 reviewers_reasons.append((user.user_id, reviewer_reasons))
672 reviewers_reasons.append((user.user_id, reviewer_reasons))
650
673
651 title = Optional.extract(title)
674 title = Optional.extract(title)
652 description = Optional.extract(description)
675 description = Optional.extract(description)
653 if title or description:
676 if title or description:
654 PullRequestModel().edit(
677 PullRequestModel().edit(
655 pull_request, title or pull_request.title,
678 pull_request, title or pull_request.title,
656 description or pull_request.description)
679 description or pull_request.description)
657 Session().commit()
680 Session().commit()
658
681
659 commit_changes = {"added": [], "common": [], "removed": []}
682 commit_changes = {"added": [], "common": [], "removed": []}
660 if str2bool(Optional.extract(update_commits)):
683 if str2bool(Optional.extract(update_commits)):
661 if PullRequestModel().has_valid_update_type(pull_request):
684 if PullRequestModel().has_valid_update_type(pull_request):
662 update_response = PullRequestModel().update_commits(
685 update_response = PullRequestModel().update_commits(
663 pull_request)
686 pull_request)
664 commit_changes = update_response.changes or commit_changes
687 commit_changes = update_response.changes or commit_changes
665 Session().commit()
688 Session().commit()
666
689
667 reviewers_changes = {"added": [], "removed": []}
690 reviewers_changes = {"added": [], "removed": []}
668 if reviewer_ids:
691 if reviewer_ids:
669 added_reviewers, removed_reviewers = \
692 added_reviewers, removed_reviewers = \
670 PullRequestModel().update_reviewers(pull_request, reviewers_reasons)
693 PullRequestModel().update_reviewers(pull_request, reviewers_reasons)
671
694
672 reviewers_changes['added'] = sorted(
695 reviewers_changes['added'] = sorted(
673 [get_user_or_error(n).username for n in added_reviewers])
696 [get_user_or_error(n).username for n in added_reviewers])
674 reviewers_changes['removed'] = sorted(
697 reviewers_changes['removed'] = sorted(
675 [get_user_or_error(n).username for n in removed_reviewers])
698 [get_user_or_error(n).username for n in removed_reviewers])
676 Session().commit()
699 Session().commit()
677
700
678 if str2bool(Optional.extract(close_pull_request)):
701 if str2bool(Optional.extract(close_pull_request)):
679 PullRequestModel().close_pull_request_with_comment(
702 PullRequestModel().close_pull_request_with_comment(
680 pull_request, apiuser, repo)
703 pull_request, apiuser, repo)
681 Session().commit()
704 Session().commit()
682
705
683 data = {
706 data = {
684 'msg': 'Updated pull request `{}`'.format(
707 'msg': 'Updated pull request `{}`'.format(
685 pull_request.pull_request_id),
708 pull_request.pull_request_id),
686 'pull_request': pull_request.get_api_data(),
709 'pull_request': pull_request.get_api_data(),
687 'updated_commits': commit_changes,
710 'updated_commits': commit_changes,
688 'updated_reviewers': reviewers_changes
711 'updated_reviewers': reviewers_changes
689 }
712 }
690
713
691 return data
714 return data
General Comments 0
You need to be logged in to leave comments. Login now