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