##// END OF EJS Templates
pull-requests: make merge state default as False. This causes a lot of performance problems and should default to faster way
marcink -
r3818:e0a16bba stable
parent child Browse files
Show More
@@ -1,997 +1,1002 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, validate_set_owner_permissions)
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 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 def get_pull_request(request, apiuser, pullrequestid, repoid=Optional(None)):
46 def get_pull_request(request, apiuser, pullrequestid, repoid=Optional(None),
47 merge_state=Optional(False)):
47 48 """
48 49 Get a pull request based on the given ID.
49 50
50 51 :param apiuser: This is filled automatically from the |authtoken|.
51 52 :type apiuser: AuthUser
52 53 :param repoid: Optional, repository name or repository ID from where
53 54 the pull request was opened.
54 55 :type repoid: str or int
55 56 :param pullrequestid: ID of the requested pull request.
56 57 :type pullrequestid: int
58 :param merge_state: Optional calculate merge state for each repository.
59 This could result in longer time to fetch the data
60 :type merge_state: bool
57 61
58 62 Example output:
59 63
60 64 .. code-block:: bash
61 65
62 66 "id": <id_given_in_input>,
63 67 "result":
64 68 {
65 69 "pull_request_id": "<pull_request_id>",
66 70 "url": "<url>",
67 71 "title": "<title>",
68 72 "description": "<description>",
69 73 "status" : "<status>",
70 74 "created_on": "<date_time_created>",
71 75 "updated_on": "<date_time_updated>",
72 76 "commit_ids": [
73 77 ...
74 78 "<commit_id>",
75 79 "<commit_id>",
76 80 ...
77 81 ],
78 82 "review_status": "<review_status>",
79 83 "mergeable": {
80 84 "status": "<bool>",
81 85 "message": "<message>",
82 86 },
83 87 "source": {
84 88 "clone_url": "<clone_url>",
85 89 "repository": "<repository_name>",
86 90 "reference":
87 91 {
88 92 "name": "<name>",
89 93 "type": "<type>",
90 94 "commit_id": "<commit_id>",
91 95 }
92 96 },
93 97 "target": {
94 98 "clone_url": "<clone_url>",
95 99 "repository": "<repository_name>",
96 100 "reference":
97 101 {
98 102 "name": "<name>",
99 103 "type": "<type>",
100 104 "commit_id": "<commit_id>",
101 105 }
102 106 },
103 107 "merge": {
104 108 "clone_url": "<clone_url>",
105 109 "reference":
106 110 {
107 111 "name": "<name>",
108 112 "type": "<type>",
109 113 "commit_id": "<commit_id>",
110 114 }
111 115 },
112 116 "author": <user_obj>,
113 117 "reviewers": [
114 118 ...
115 119 {
116 120 "user": "<user_obj>",
117 121 "review_status": "<review_status>",
118 122 }
119 123 ...
120 124 ]
121 125 },
122 126 "error": null
123 127 """
124 128
125 129 pull_request = get_pull_request_or_error(pullrequestid)
126 130 if Optional.extract(repoid):
127 131 repo = get_repo_or_error(repoid)
128 132 else:
129 133 repo = pull_request.target_repo
130 134
131 135 if not PullRequestModel().check_user_read(pull_request, apiuser, api=True):
132 136 raise JSONRPCError('repository `%s` or pull request `%s` '
133 137 'does not exist' % (repoid, pullrequestid))
134 138
135 139 # NOTE(marcink): only calculate and return merge state if the pr state is 'created'
136 140 # otherwise we can lock the repo on calculation of merge state while update/merge
137 141 # is happening.
138 merge_state = pull_request.pull_request_state == pull_request.STATE_CREATED
142 pr_created = pull_request.pull_request_state == pull_request.STATE_CREATED
143 merge_state = Optional.extract(merge_state, binary=True) and pr_created
139 144 data = pull_request.get_api_data(with_merge_state=merge_state)
140 145 return data
141 146
142 147
143 148 @jsonrpc_method()
144 149 def get_pull_requests(request, apiuser, repoid, status=Optional('new'),
145 merge_state=Optional(True)):
150 merge_state=Optional(False)):
146 151 """
147 152 Get all pull requests from the repository specified in `repoid`.
148 153
149 154 :param apiuser: This is filled automatically from the |authtoken|.
150 155 :type apiuser: AuthUser
151 156 :param repoid: Optional repository name or repository ID.
152 157 :type repoid: str or int
153 158 :param status: Only return pull requests with the specified status.
154 159 Valid options are.
155 160 * ``new`` (default)
156 161 * ``open``
157 162 * ``closed``
158 163 :type status: str
159 164 :param merge_state: Optional calculate merge state for each repository.
160 165 This could result in longer time to fetch the data
161 166 :type merge_state: bool
162 167
163 168 Example output:
164 169
165 170 .. code-block:: bash
166 171
167 172 "id": <id_given_in_input>,
168 173 "result":
169 174 [
170 175 ...
171 176 {
172 177 "pull_request_id": "<pull_request_id>",
173 178 "url": "<url>",
174 179 "title" : "<title>",
175 180 "description": "<description>",
176 181 "status": "<status>",
177 182 "created_on": "<date_time_created>",
178 183 "updated_on": "<date_time_updated>",
179 184 "commit_ids": [
180 185 ...
181 186 "<commit_id>",
182 187 "<commit_id>",
183 188 ...
184 189 ],
185 190 "review_status": "<review_status>",
186 191 "mergeable": {
187 192 "status": "<bool>",
188 193 "message: "<message>",
189 194 },
190 195 "source": {
191 196 "clone_url": "<clone_url>",
192 197 "reference":
193 198 {
194 199 "name": "<name>",
195 200 "type": "<type>",
196 201 "commit_id": "<commit_id>",
197 202 }
198 203 },
199 204 "target": {
200 205 "clone_url": "<clone_url>",
201 206 "reference":
202 207 {
203 208 "name": "<name>",
204 209 "type": "<type>",
205 210 "commit_id": "<commit_id>",
206 211 }
207 212 },
208 213 "merge": {
209 214 "clone_url": "<clone_url>",
210 215 "reference":
211 216 {
212 217 "name": "<name>",
213 218 "type": "<type>",
214 219 "commit_id": "<commit_id>",
215 220 }
216 221 },
217 222 "author": <user_obj>,
218 223 "reviewers": [
219 224 ...
220 225 {
221 226 "user": "<user_obj>",
222 227 "review_status": "<review_status>",
223 228 }
224 229 ...
225 230 ]
226 231 }
227 232 ...
228 233 ],
229 234 "error": null
230 235
231 236 """
232 237 repo = get_repo_or_error(repoid)
233 238 if not has_superadmin_permission(apiuser):
234 239 _perms = (
235 240 'repository.admin', 'repository.write', 'repository.read',)
236 241 validate_repo_permissions(apiuser, repoid, repo, _perms)
237 242
238 243 status = Optional.extract(status)
239 244 merge_state = Optional.extract(merge_state, binary=True)
240 245 pull_requests = PullRequestModel().get_all(repo, statuses=[status],
241 246 order_by='id', order_dir='desc')
242 247 data = [pr.get_api_data(with_merge_state=merge_state) for pr in pull_requests]
243 248 return data
244 249
245 250
246 251 @jsonrpc_method()
247 252 def merge_pull_request(
248 253 request, apiuser, pullrequestid, repoid=Optional(None),
249 254 userid=Optional(OAttr('apiuser'))):
250 255 """
251 256 Merge the pull request specified by `pullrequestid` into its target
252 257 repository.
253 258
254 259 :param apiuser: This is filled automatically from the |authtoken|.
255 260 :type apiuser: AuthUser
256 261 :param repoid: Optional, repository name or repository ID of the
257 262 target repository to which the |pr| is to be merged.
258 263 :type repoid: str or int
259 264 :param pullrequestid: ID of the pull request which shall be merged.
260 265 :type pullrequestid: int
261 266 :param userid: Merge the pull request as this user.
262 267 :type userid: Optional(str or int)
263 268
264 269 Example output:
265 270
266 271 .. code-block:: bash
267 272
268 273 "id": <id_given_in_input>,
269 274 "result": {
270 275 "executed": "<bool>",
271 276 "failure_reason": "<int>",
272 277 "merge_status_message": "<str>",
273 278 "merge_commit_id": "<merge_commit_id>",
274 279 "possible": "<bool>",
275 280 "merge_ref": {
276 281 "commit_id": "<commit_id>",
277 282 "type": "<type>",
278 283 "name": "<name>"
279 284 }
280 285 },
281 286 "error": null
282 287 """
283 288 pull_request = get_pull_request_or_error(pullrequestid)
284 289 if Optional.extract(repoid):
285 290 repo = get_repo_or_error(repoid)
286 291 else:
287 292 repo = pull_request.target_repo
288 293 auth_user = apiuser
289 294 if not isinstance(userid, Optional):
290 295 if (has_superadmin_permission(apiuser) or
291 296 HasRepoPermissionAnyApi('repository.admin')(
292 297 user=apiuser, repo_name=repo.repo_name)):
293 298 apiuser = get_user_or_error(userid)
294 299 auth_user = apiuser.AuthUser()
295 300 else:
296 301 raise JSONRPCError('userid is not the same as your user')
297 302
298 303 if pull_request.pull_request_state != PullRequest.STATE_CREATED:
299 304 raise JSONRPCError(
300 305 'Operation forbidden because pull request is in state {}, '
301 306 'only state {} is allowed.'.format(
302 307 pull_request.pull_request_state, PullRequest.STATE_CREATED))
303 308
304 309 with pull_request.set_state(PullRequest.STATE_UPDATING):
305 310 check = MergeCheck.validate(pull_request, auth_user=auth_user,
306 311 translator=request.translate)
307 312 merge_possible = not check.failed
308 313
309 314 if not merge_possible:
310 315 error_messages = []
311 316 for err_type, error_msg in check.errors:
312 317 error_msg = request.translate(error_msg)
313 318 error_messages.append(error_msg)
314 319
315 320 reasons = ','.join(error_messages)
316 321 raise JSONRPCError(
317 322 'merge not possible for following reasons: {}'.format(reasons))
318 323
319 324 target_repo = pull_request.target_repo
320 325 extras = vcs_operation_context(
321 326 request.environ, repo_name=target_repo.repo_name,
322 327 username=auth_user.username, action='push',
323 328 scm=target_repo.repo_type)
324 329 with pull_request.set_state(PullRequest.STATE_UPDATING):
325 330 merge_response = PullRequestModel().merge_repo(
326 331 pull_request, apiuser, extras=extras)
327 332 if merge_response.executed:
328 333 PullRequestModel().close_pull_request(pull_request.pull_request_id, auth_user)
329 334
330 335 Session().commit()
331 336
332 337 # In previous versions the merge response directly contained the merge
333 338 # commit id. It is now contained in the merge reference object. To be
334 339 # backwards compatible we have to extract it again.
335 340 merge_response = merge_response.asdict()
336 341 merge_response['merge_commit_id'] = merge_response['merge_ref'].commit_id
337 342
338 343 return merge_response
339 344
340 345
341 346 @jsonrpc_method()
342 347 def get_pull_request_comments(
343 348 request, apiuser, pullrequestid, repoid=Optional(None)):
344 349 """
345 350 Get all comments of pull request specified with the `pullrequestid`
346 351
347 352 :param apiuser: This is filled automatically from the |authtoken|.
348 353 :type apiuser: AuthUser
349 354 :param repoid: Optional repository name or repository ID.
350 355 :type repoid: str or int
351 356 :param pullrequestid: The pull request ID.
352 357 :type pullrequestid: int
353 358
354 359 Example output:
355 360
356 361 .. code-block:: bash
357 362
358 363 id : <id_given_in_input>
359 364 result : [
360 365 {
361 366 "comment_author": {
362 367 "active": true,
363 368 "full_name_or_username": "Tom Gore",
364 369 "username": "admin"
365 370 },
366 371 "comment_created_on": "2017-01-02T18:43:45.533",
367 372 "comment_f_path": null,
368 373 "comment_id": 25,
369 374 "comment_lineno": null,
370 375 "comment_status": {
371 376 "status": "under_review",
372 377 "status_lbl": "Under Review"
373 378 },
374 379 "comment_text": "Example text",
375 380 "comment_type": null,
376 381 "pull_request_version": null
377 382 }
378 383 ],
379 384 error : null
380 385 """
381 386
382 387 pull_request = get_pull_request_or_error(pullrequestid)
383 388 if Optional.extract(repoid):
384 389 repo = get_repo_or_error(repoid)
385 390 else:
386 391 repo = pull_request.target_repo
387 392
388 393 if not PullRequestModel().check_user_read(
389 394 pull_request, apiuser, api=True):
390 395 raise JSONRPCError('repository `%s` or pull request `%s` '
391 396 'does not exist' % (repoid, pullrequestid))
392 397
393 398 (pull_request_latest,
394 399 pull_request_at_ver,
395 400 pull_request_display_obj,
396 401 at_version) = PullRequestModel().get_pr_version(
397 402 pull_request.pull_request_id, version=None)
398 403
399 404 versions = pull_request_display_obj.versions()
400 405 ver_map = {
401 406 ver.pull_request_version_id: cnt
402 407 for cnt, ver in enumerate(versions, 1)
403 408 }
404 409
405 410 # GENERAL COMMENTS with versions #
406 411 q = CommentsModel()._all_general_comments_of_pull_request(pull_request)
407 412 q = q.order_by(ChangesetComment.comment_id.asc())
408 413 general_comments = q.all()
409 414
410 415 # INLINE COMMENTS with versions #
411 416 q = CommentsModel()._all_inline_comments_of_pull_request(pull_request)
412 417 q = q.order_by(ChangesetComment.comment_id.asc())
413 418 inline_comments = q.all()
414 419
415 420 data = []
416 421 for comment in inline_comments + general_comments:
417 422 full_data = comment.get_api_data()
418 423 pr_version_id = None
419 424 if comment.pull_request_version_id:
420 425 pr_version_id = 'v{}'.format(
421 426 ver_map[comment.pull_request_version_id])
422 427
423 428 # sanitize some entries
424 429
425 430 full_data['pull_request_version'] = pr_version_id
426 431 full_data['comment_author'] = {
427 432 'username': full_data['comment_author'].username,
428 433 'full_name_or_username': full_data['comment_author'].full_name_or_username,
429 434 'active': full_data['comment_author'].active,
430 435 }
431 436
432 437 if full_data['comment_status']:
433 438 full_data['comment_status'] = {
434 439 'status': full_data['comment_status'][0].status,
435 440 'status_lbl': full_data['comment_status'][0].status_lbl,
436 441 }
437 442 else:
438 443 full_data['comment_status'] = {}
439 444
440 445 data.append(full_data)
441 446 return data
442 447
443 448
444 449 @jsonrpc_method()
445 450 def comment_pull_request(
446 451 request, apiuser, pullrequestid, repoid=Optional(None),
447 452 message=Optional(None), commit_id=Optional(None), status=Optional(None),
448 453 comment_type=Optional(ChangesetComment.COMMENT_TYPE_NOTE),
449 454 resolves_comment_id=Optional(None),
450 455 userid=Optional(OAttr('apiuser'))):
451 456 """
452 457 Comment on the pull request specified with the `pullrequestid`,
453 458 in the |repo| specified by the `repoid`, and optionally change the
454 459 review status.
455 460
456 461 :param apiuser: This is filled automatically from the |authtoken|.
457 462 :type apiuser: AuthUser
458 463 :param repoid: Optional repository name or repository ID.
459 464 :type repoid: str or int
460 465 :param pullrequestid: The pull request ID.
461 466 :type pullrequestid: int
462 467 :param commit_id: Specify the commit_id for which to set a comment. If
463 468 given commit_id is different than latest in the PR status
464 469 change won't be performed.
465 470 :type commit_id: str
466 471 :param message: The text content of the comment.
467 472 :type message: str
468 473 :param status: (**Optional**) Set the approval status of the pull
469 474 request. One of: 'not_reviewed', 'approved', 'rejected',
470 475 'under_review'
471 476 :type status: str
472 477 :param comment_type: Comment type, one of: 'note', 'todo'
473 478 :type comment_type: Optional(str), default: 'note'
474 479 :param userid: Comment on the pull request as this user
475 480 :type userid: Optional(str or int)
476 481
477 482 Example output:
478 483
479 484 .. code-block:: bash
480 485
481 486 id : <id_given_in_input>
482 487 result : {
483 488 "pull_request_id": "<Integer>",
484 489 "comment_id": "<Integer>",
485 490 "status": {"given": <given_status>,
486 491 "was_changed": <bool status_was_actually_changed> },
487 492 },
488 493 error : null
489 494 """
490 495 pull_request = get_pull_request_or_error(pullrequestid)
491 496 if Optional.extract(repoid):
492 497 repo = get_repo_or_error(repoid)
493 498 else:
494 499 repo = pull_request.target_repo
495 500
496 501 auth_user = apiuser
497 502 if not isinstance(userid, Optional):
498 503 if (has_superadmin_permission(apiuser) or
499 504 HasRepoPermissionAnyApi('repository.admin')(
500 505 user=apiuser, repo_name=repo.repo_name)):
501 506 apiuser = get_user_or_error(userid)
502 507 auth_user = apiuser.AuthUser()
503 508 else:
504 509 raise JSONRPCError('userid is not the same as your user')
505 510
506 511 if pull_request.is_closed():
507 512 raise JSONRPCError(
508 513 'pull request `%s` comment failed, pull request is closed' % (
509 514 pullrequestid,))
510 515
511 516 if not PullRequestModel().check_user_read(
512 517 pull_request, apiuser, api=True):
513 518 raise JSONRPCError('repository `%s` does not exist' % (repoid,))
514 519 message = Optional.extract(message)
515 520 status = Optional.extract(status)
516 521 commit_id = Optional.extract(commit_id)
517 522 comment_type = Optional.extract(comment_type)
518 523 resolves_comment_id = Optional.extract(resolves_comment_id)
519 524
520 525 if not message and not status:
521 526 raise JSONRPCError(
522 527 'Both message and status parameters are missing. '
523 528 'At least one is required.')
524 529
525 530 if (status not in (st[0] for st in ChangesetStatus.STATUSES) and
526 531 status is not None):
527 532 raise JSONRPCError('Unknown comment status: `%s`' % status)
528 533
529 534 if commit_id and commit_id not in pull_request.revisions:
530 535 raise JSONRPCError(
531 536 'Invalid commit_id `%s` for this pull request.' % commit_id)
532 537
533 538 allowed_to_change_status = PullRequestModel().check_user_change_status(
534 539 pull_request, apiuser)
535 540
536 541 # if commit_id is passed re-validated if user is allowed to change status
537 542 # based on latest commit_id from the PR
538 543 if commit_id:
539 544 commit_idx = pull_request.revisions.index(commit_id)
540 545 if commit_idx != 0:
541 546 allowed_to_change_status = False
542 547
543 548 if resolves_comment_id:
544 549 comment = ChangesetComment.get(resolves_comment_id)
545 550 if not comment:
546 551 raise JSONRPCError(
547 552 'Invalid resolves_comment_id `%s` for this pull request.'
548 553 % resolves_comment_id)
549 554 if comment.comment_type != ChangesetComment.COMMENT_TYPE_TODO:
550 555 raise JSONRPCError(
551 556 'Comment `%s` is wrong type for setting status to resolved.'
552 557 % resolves_comment_id)
553 558
554 559 text = message
555 560 status_label = ChangesetStatus.get_status_lbl(status)
556 561 if status and allowed_to_change_status:
557 562 st_message = ('Status change %(transition_icon)s %(status)s'
558 563 % {'transition_icon': '>', 'status': status_label})
559 564 text = message or st_message
560 565
561 566 rc_config = SettingsModel().get_all_settings()
562 567 renderer = rc_config.get('rhodecode_markup_renderer', 'rst')
563 568
564 569 status_change = status and allowed_to_change_status
565 570 comment = CommentsModel().create(
566 571 text=text,
567 572 repo=pull_request.target_repo.repo_id,
568 573 user=apiuser.user_id,
569 574 pull_request=pull_request.pull_request_id,
570 575 f_path=None,
571 576 line_no=None,
572 577 status_change=(status_label if status_change else None),
573 578 status_change_type=(status if status_change else None),
574 579 closing_pr=False,
575 580 renderer=renderer,
576 581 comment_type=comment_type,
577 582 resolves_comment_id=resolves_comment_id,
578 583 auth_user=auth_user
579 584 )
580 585
581 586 if allowed_to_change_status and status:
582 587 old_calculated_status = pull_request.calculated_review_status()
583 588 ChangesetStatusModel().set_status(
584 589 pull_request.target_repo.repo_id,
585 590 status,
586 591 apiuser.user_id,
587 592 comment,
588 593 pull_request=pull_request.pull_request_id
589 594 )
590 595 Session().flush()
591 596
592 597 Session().commit()
593 598
594 599 PullRequestModel().trigger_pull_request_hook(
595 600 pull_request, apiuser, 'comment',
596 601 data={'comment': comment})
597 602
598 603 if allowed_to_change_status and status:
599 604 # we now calculate the status of pull request, and based on that
600 605 # calculation we set the commits status
601 606 calculated_status = pull_request.calculated_review_status()
602 607 if old_calculated_status != calculated_status:
603 608 PullRequestModel().trigger_pull_request_hook(
604 609 pull_request, apiuser, 'review_status_change',
605 610 data={'status': calculated_status})
606 611
607 612 data = {
608 613 'pull_request_id': pull_request.pull_request_id,
609 614 'comment_id': comment.comment_id if comment else None,
610 615 'status': {'given': status, 'was_changed': status_change},
611 616 }
612 617 return data
613 618
614 619
615 620 @jsonrpc_method()
616 621 def create_pull_request(
617 622 request, apiuser, source_repo, target_repo, source_ref, target_ref,
618 623 owner=Optional(OAttr('apiuser')), title=Optional(''), description=Optional(''),
619 624 description_renderer=Optional(''), reviewers=Optional(None)):
620 625 """
621 626 Creates a new pull request.
622 627
623 628 Accepts refs in the following formats:
624 629
625 630 * branch:<branch_name>:<sha>
626 631 * branch:<branch_name>
627 632 * bookmark:<bookmark_name>:<sha> (Mercurial only)
628 633 * bookmark:<bookmark_name> (Mercurial only)
629 634
630 635 :param apiuser: This is filled automatically from the |authtoken|.
631 636 :type apiuser: AuthUser
632 637 :param source_repo: Set the source repository name.
633 638 :type source_repo: str
634 639 :param target_repo: Set the target repository name.
635 640 :type target_repo: str
636 641 :param source_ref: Set the source ref name.
637 642 :type source_ref: str
638 643 :param target_ref: Set the target ref name.
639 644 :type target_ref: str
640 645 :param owner: user_id or username
641 646 :type owner: Optional(str)
642 647 :param title: Optionally Set the pull request title, it's generated otherwise
643 648 :type title: str
644 649 :param description: Set the pull request description.
645 650 :type description: Optional(str)
646 651 :type description_renderer: Optional(str)
647 652 :param description_renderer: Set pull request renderer for the description.
648 653 It should be 'rst', 'markdown' or 'plain'. If not give default
649 654 system renderer will be used
650 655 :param reviewers: Set the new pull request reviewers list.
651 656 Reviewer defined by review rules will be added automatically to the
652 657 defined list.
653 658 :type reviewers: Optional(list)
654 659 Accepts username strings or objects of the format:
655 660
656 661 [{'username': 'nick', 'reasons': ['original author'], 'mandatory': <bool>}]
657 662 """
658 663
659 664 source_db_repo = get_repo_or_error(source_repo)
660 665 target_db_repo = get_repo_or_error(target_repo)
661 666 if not has_superadmin_permission(apiuser):
662 667 _perms = ('repository.admin', 'repository.write', 'repository.read',)
663 668 validate_repo_permissions(apiuser, source_repo, source_db_repo, _perms)
664 669
665 670 owner = validate_set_owner_permissions(apiuser, owner)
666 671
667 672 full_source_ref = resolve_ref_or_error(source_ref, source_db_repo)
668 673 full_target_ref = resolve_ref_or_error(target_ref, target_db_repo)
669 674
670 675 source_scm = source_db_repo.scm_instance()
671 676 target_scm = target_db_repo.scm_instance()
672 677
673 678 source_commit = get_commit_or_error(full_source_ref, source_db_repo)
674 679 target_commit = get_commit_or_error(full_target_ref, target_db_repo)
675 680
676 681 ancestor = source_scm.get_common_ancestor(
677 682 source_commit.raw_id, target_commit.raw_id, target_scm)
678 683 if not ancestor:
679 684 raise JSONRPCError('no common ancestor found')
680 685
681 686 # recalculate target ref based on ancestor
682 687 target_ref_type, target_ref_name, __ = full_target_ref.split(':')
683 688 full_target_ref = ':'.join((target_ref_type, target_ref_name, ancestor))
684 689
685 690 commit_ranges = target_scm.compare(
686 691 target_commit.raw_id, source_commit.raw_id, source_scm,
687 692 merge=True, pre_load=[])
688 693
689 694 if not commit_ranges:
690 695 raise JSONRPCError('no commits found')
691 696
692 697 reviewer_objects = Optional.extract(reviewers) or []
693 698
694 699 # serialize and validate passed in given reviewers
695 700 if reviewer_objects:
696 701 schema = ReviewerListSchema()
697 702 try:
698 703 reviewer_objects = schema.deserialize(reviewer_objects)
699 704 except Invalid as err:
700 705 raise JSONRPCValidationError(colander_exc=err)
701 706
702 707 # validate users
703 708 for reviewer_object in reviewer_objects:
704 709 user = get_user_or_error(reviewer_object['username'])
705 710 reviewer_object['user_id'] = user.user_id
706 711
707 712 get_default_reviewers_data, validate_default_reviewers = \
708 713 PullRequestModel().get_reviewer_functions()
709 714
710 715 # recalculate reviewers logic, to make sure we can validate this
711 716 reviewer_rules = get_default_reviewers_data(
712 717 owner, source_db_repo,
713 718 source_commit, target_db_repo, target_commit)
714 719
715 720 # now MERGE our given with the calculated
716 721 reviewer_objects = reviewer_rules['reviewers'] + reviewer_objects
717 722
718 723 try:
719 724 reviewers = validate_default_reviewers(
720 725 reviewer_objects, reviewer_rules)
721 726 except ValueError as e:
722 727 raise JSONRPCError('Reviewers Validation: {}'.format(e))
723 728
724 729 title = Optional.extract(title)
725 730 if not title:
726 731 title_source_ref = source_ref.split(':', 2)[1]
727 732 title = PullRequestModel().generate_pullrequest_title(
728 733 source=source_repo,
729 734 source_ref=title_source_ref,
730 735 target=target_repo
731 736 )
732 737 # fetch renderer, if set fallback to plain in case of PR
733 738 rc_config = SettingsModel().get_all_settings()
734 739 default_system_renderer = rc_config.get('rhodecode_markup_renderer', 'plain')
735 740 description = Optional.extract(description)
736 741 description_renderer = Optional.extract(description_renderer) or default_system_renderer
737 742
738 743 pull_request = PullRequestModel().create(
739 744 created_by=owner.user_id,
740 745 source_repo=source_repo,
741 746 source_ref=full_source_ref,
742 747 target_repo=target_repo,
743 748 target_ref=full_target_ref,
744 749 revisions=[commit.raw_id for commit in reversed(commit_ranges)],
745 750 reviewers=reviewers,
746 751 title=title,
747 752 description=description,
748 753 description_renderer=description_renderer,
749 754 reviewer_data=reviewer_rules,
750 755 auth_user=apiuser
751 756 )
752 757
753 758 Session().commit()
754 759 data = {
755 760 'msg': 'Created new pull request `{}`'.format(title),
756 761 'pull_request_id': pull_request.pull_request_id,
757 762 }
758 763 return data
759 764
760 765
761 766 @jsonrpc_method()
762 767 def update_pull_request(
763 768 request, apiuser, pullrequestid, repoid=Optional(None),
764 769 title=Optional(''), description=Optional(''), description_renderer=Optional(''),
765 770 reviewers=Optional(None), update_commits=Optional(None)):
766 771 """
767 772 Updates a pull request.
768 773
769 774 :param apiuser: This is filled automatically from the |authtoken|.
770 775 :type apiuser: AuthUser
771 776 :param repoid: Optional repository name or repository ID.
772 777 :type repoid: str or int
773 778 :param pullrequestid: The pull request ID.
774 779 :type pullrequestid: int
775 780 :param title: Set the pull request title.
776 781 :type title: str
777 782 :param description: Update pull request description.
778 783 :type description: Optional(str)
779 784 :type description_renderer: Optional(str)
780 785 :param description_renderer: Update pull request renderer for the description.
781 786 It should be 'rst', 'markdown' or 'plain'
782 787 :param reviewers: Update pull request reviewers list with new value.
783 788 :type reviewers: Optional(list)
784 789 Accepts username strings or objects of the format:
785 790
786 791 [{'username': 'nick', 'reasons': ['original author'], 'mandatory': <bool>}]
787 792
788 793 :param update_commits: Trigger update of commits for this pull request
789 794 :type: update_commits: Optional(bool)
790 795
791 796 Example output:
792 797
793 798 .. code-block:: bash
794 799
795 800 id : <id_given_in_input>
796 801 result : {
797 802 "msg": "Updated pull request `63`",
798 803 "pull_request": <pull_request_object>,
799 804 "updated_reviewers": {
800 805 "added": [
801 806 "username"
802 807 ],
803 808 "removed": []
804 809 },
805 810 "updated_commits": {
806 811 "added": [
807 812 "<sha1_hash>"
808 813 ],
809 814 "common": [
810 815 "<sha1_hash>",
811 816 "<sha1_hash>",
812 817 ],
813 818 "removed": []
814 819 }
815 820 }
816 821 error : null
817 822 """
818 823
819 824 pull_request = get_pull_request_or_error(pullrequestid)
820 825 if Optional.extract(repoid):
821 826 repo = get_repo_or_error(repoid)
822 827 else:
823 828 repo = pull_request.target_repo
824 829
825 830 if not PullRequestModel().check_user_update(
826 831 pull_request, apiuser, api=True):
827 832 raise JSONRPCError(
828 833 'pull request `%s` update failed, no permission to update.' % (
829 834 pullrequestid,))
830 835 if pull_request.is_closed():
831 836 raise JSONRPCError(
832 837 'pull request `%s` update failed, pull request is closed' % (
833 838 pullrequestid,))
834 839
835 840 reviewer_objects = Optional.extract(reviewers) or []
836 841
837 842 if reviewer_objects:
838 843 schema = ReviewerListSchema()
839 844 try:
840 845 reviewer_objects = schema.deserialize(reviewer_objects)
841 846 except Invalid as err:
842 847 raise JSONRPCValidationError(colander_exc=err)
843 848
844 849 # validate users
845 850 for reviewer_object in reviewer_objects:
846 851 user = get_user_or_error(reviewer_object['username'])
847 852 reviewer_object['user_id'] = user.user_id
848 853
849 854 get_default_reviewers_data, get_validated_reviewers = \
850 855 PullRequestModel().get_reviewer_functions()
851 856
852 857 # re-use stored rules
853 858 reviewer_rules = pull_request.reviewer_data
854 859 try:
855 860 reviewers = get_validated_reviewers(
856 861 reviewer_objects, reviewer_rules)
857 862 except ValueError as e:
858 863 raise JSONRPCError('Reviewers Validation: {}'.format(e))
859 864 else:
860 865 reviewers = []
861 866
862 867 title = Optional.extract(title)
863 868 description = Optional.extract(description)
864 869 description_renderer = Optional.extract(description_renderer)
865 870
866 871 if title or description:
867 872 PullRequestModel().edit(
868 873 pull_request,
869 874 title or pull_request.title,
870 875 description or pull_request.description,
871 876 description_renderer or pull_request.description_renderer,
872 877 apiuser)
873 878 Session().commit()
874 879
875 880 commit_changes = {"added": [], "common": [], "removed": []}
876 881 if str2bool(Optional.extract(update_commits)):
877 882
878 883 if pull_request.pull_request_state != PullRequest.STATE_CREATED:
879 884 raise JSONRPCError(
880 885 'Operation forbidden because pull request is in state {}, '
881 886 'only state {} is allowed.'.format(
882 887 pull_request.pull_request_state, PullRequest.STATE_CREATED))
883 888
884 889 with pull_request.set_state(PullRequest.STATE_UPDATING):
885 890 if PullRequestModel().has_valid_update_type(pull_request):
886 891 update_response = PullRequestModel().update_commits(pull_request)
887 892 commit_changes = update_response.changes or commit_changes
888 893 Session().commit()
889 894
890 895 reviewers_changes = {"added": [], "removed": []}
891 896 if reviewers:
892 897 old_calculated_status = pull_request.calculated_review_status()
893 898 added_reviewers, removed_reviewers = \
894 899 PullRequestModel().update_reviewers(pull_request, reviewers, apiuser)
895 900
896 901 reviewers_changes['added'] = sorted(
897 902 [get_user_or_error(n).username for n in added_reviewers])
898 903 reviewers_changes['removed'] = sorted(
899 904 [get_user_or_error(n).username for n in removed_reviewers])
900 905 Session().commit()
901 906
902 907 # trigger status changed if change in reviewers changes the status
903 908 calculated_status = pull_request.calculated_review_status()
904 909 if old_calculated_status != calculated_status:
905 910 PullRequestModel().trigger_pull_request_hook(
906 911 pull_request, apiuser, 'review_status_change',
907 912 data={'status': calculated_status})
908 913
909 914 data = {
910 915 'msg': 'Updated pull request `{}`'.format(
911 916 pull_request.pull_request_id),
912 917 'pull_request': pull_request.get_api_data(),
913 918 'updated_commits': commit_changes,
914 919 'updated_reviewers': reviewers_changes
915 920 }
916 921
917 922 return data
918 923
919 924
920 925 @jsonrpc_method()
921 926 def close_pull_request(
922 927 request, apiuser, pullrequestid, repoid=Optional(None),
923 928 userid=Optional(OAttr('apiuser')), message=Optional('')):
924 929 """
925 930 Close the pull request specified by `pullrequestid`.
926 931
927 932 :param apiuser: This is filled automatically from the |authtoken|.
928 933 :type apiuser: AuthUser
929 934 :param repoid: Repository name or repository ID to which the pull
930 935 request belongs.
931 936 :type repoid: str or int
932 937 :param pullrequestid: ID of the pull request to be closed.
933 938 :type pullrequestid: int
934 939 :param userid: Close the pull request as this user.
935 940 :type userid: Optional(str or int)
936 941 :param message: Optional message to close the Pull Request with. If not
937 942 specified it will be generated automatically.
938 943 :type message: Optional(str)
939 944
940 945 Example output:
941 946
942 947 .. code-block:: bash
943 948
944 949 "id": <id_given_in_input>,
945 950 "result": {
946 951 "pull_request_id": "<int>",
947 952 "close_status": "<str:status_lbl>,
948 953 "closed": "<bool>"
949 954 },
950 955 "error": null
951 956
952 957 """
953 958 _ = request.translate
954 959
955 960 pull_request = get_pull_request_or_error(pullrequestid)
956 961 if Optional.extract(repoid):
957 962 repo = get_repo_or_error(repoid)
958 963 else:
959 964 repo = pull_request.target_repo
960 965
961 966 if not isinstance(userid, Optional):
962 967 if (has_superadmin_permission(apiuser) or
963 968 HasRepoPermissionAnyApi('repository.admin')(
964 969 user=apiuser, repo_name=repo.repo_name)):
965 970 apiuser = get_user_or_error(userid)
966 971 else:
967 972 raise JSONRPCError('userid is not the same as your user')
968 973
969 974 if pull_request.is_closed():
970 975 raise JSONRPCError(
971 976 'pull request `%s` is already closed' % (pullrequestid,))
972 977
973 978 # only owner or admin or person with write permissions
974 979 allowed_to_close = PullRequestModel().check_user_update(
975 980 pull_request, apiuser, api=True)
976 981
977 982 if not allowed_to_close:
978 983 raise JSONRPCError(
979 984 'pull request `%s` close failed, no permission to close.' % (
980 985 pullrequestid,))
981 986
982 987 # message we're using to close the PR, else it's automatically generated
983 988 message = Optional.extract(message)
984 989
985 990 # finally close the PR, with proper message comment
986 991 comment, status = PullRequestModel().close_pull_request_with_comment(
987 992 pull_request, apiuser, repo, message=message, auth_user=apiuser)
988 993 status_lbl = ChangesetStatus.get_status_lbl(status)
989 994
990 995 Session().commit()
991 996
992 997 data = {
993 998 'pull_request_id': pull_request.pull_request_id,
994 999 'close_status': status_lbl,
995 1000 'closed': True,
996 1001 }
997 1002 return data
General Comments 0
You need to be logged in to leave comments. Login now