##// END OF EJS Templates
pull-requests: expose force refresh of merge workspace and expose all metadata for merge message formatting.
marcink -
r3558:d2ddd715 default
parent child Browse files
Show More
@@ -1,1717 +1,1720 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2012-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 """
23 23 pull request model for RhodeCode
24 24 """
25 25
26 26
27 27 import json
28 28 import logging
29 29 import datetime
30 30 import urllib
31 31 import collections
32 32
33 33 from pyramid import compat
34 34 from pyramid.threadlocal import get_current_request
35 35
36 36 from rhodecode import events
37 37 from rhodecode.translation import lazy_ugettext
38 38 from rhodecode.lib import helpers as h, hooks_utils, diffs
39 39 from rhodecode.lib import audit_logger
40 40 from rhodecode.lib.compat import OrderedDict
41 41 from rhodecode.lib.hooks_daemon import prepare_callback_daemon
42 42 from rhodecode.lib.markup_renderer import (
43 43 DEFAULT_COMMENTS_RENDERER, RstTemplateRenderer)
44 44 from rhodecode.lib.utils2 import safe_unicode, safe_str, md5_safe
45 45 from rhodecode.lib.vcs.backends.base import (
46 46 Reference, MergeResponse, MergeFailureReason, UpdateFailureReason)
47 47 from rhodecode.lib.vcs.conf import settings as vcs_settings
48 48 from rhodecode.lib.vcs.exceptions import (
49 49 CommitDoesNotExistError, EmptyRepositoryError)
50 50 from rhodecode.model import BaseModel
51 51 from rhodecode.model.changeset_status import ChangesetStatusModel
52 52 from rhodecode.model.comment import CommentsModel
53 53 from rhodecode.model.db import (
54 54 or_, PullRequest, PullRequestReviewers, ChangesetStatus,
55 55 PullRequestVersion, ChangesetComment, Repository, RepoReviewRule)
56 56 from rhodecode.model.meta import Session
57 57 from rhodecode.model.notification import NotificationModel, \
58 58 EmailNotificationModel
59 59 from rhodecode.model.scm import ScmModel
60 60 from rhodecode.model.settings import VcsSettingsModel
61 61
62 62
63 63 log = logging.getLogger(__name__)
64 64
65 65
66 66 # Data structure to hold the response data when updating commits during a pull
67 67 # request update.
68 68 UpdateResponse = collections.namedtuple('UpdateResponse', [
69 69 'executed', 'reason', 'new', 'old', 'changes',
70 70 'source_changed', 'target_changed'])
71 71
72 72
73 73 class PullRequestModel(BaseModel):
74 74
75 75 cls = PullRequest
76 76
77 77 DIFF_CONTEXT = diffs.DEFAULT_CONTEXT
78 78
79 79 UPDATE_STATUS_MESSAGES = {
80 80 UpdateFailureReason.NONE: lazy_ugettext(
81 81 'Pull request update successful.'),
82 82 UpdateFailureReason.UNKNOWN: lazy_ugettext(
83 83 'Pull request update failed because of an unknown error.'),
84 84 UpdateFailureReason.NO_CHANGE: lazy_ugettext(
85 85 'No update needed because the source and target have not changed.'),
86 86 UpdateFailureReason.WRONG_REF_TYPE: lazy_ugettext(
87 87 'Pull request cannot be updated because the reference type is '
88 88 'not supported for an update. Only Branch, Tag or Bookmark is allowed.'),
89 89 UpdateFailureReason.MISSING_TARGET_REF: lazy_ugettext(
90 90 'This pull request cannot be updated because the target '
91 91 'reference is missing.'),
92 92 UpdateFailureReason.MISSING_SOURCE_REF: lazy_ugettext(
93 93 'This pull request cannot be updated because the source '
94 94 'reference is missing.'),
95 95 }
96 96 REF_TYPES = ['bookmark', 'book', 'tag', 'branch']
97 97 UPDATABLE_REF_TYPES = ['bookmark', 'book', 'branch']
98 98
99 99 def __get_pull_request(self, pull_request):
100 100 return self._get_instance((
101 101 PullRequest, PullRequestVersion), pull_request)
102 102
103 103 def _check_perms(self, perms, pull_request, user, api=False):
104 104 if not api:
105 105 return h.HasRepoPermissionAny(*perms)(
106 106 user=user, repo_name=pull_request.target_repo.repo_name)
107 107 else:
108 108 return h.HasRepoPermissionAnyApi(*perms)(
109 109 user=user, repo_name=pull_request.target_repo.repo_name)
110 110
111 111 def check_user_read(self, pull_request, user, api=False):
112 112 _perms = ('repository.admin', 'repository.write', 'repository.read',)
113 113 return self._check_perms(_perms, pull_request, user, api)
114 114
115 115 def check_user_merge(self, pull_request, user, api=False):
116 116 _perms = ('repository.admin', 'repository.write', 'hg.admin',)
117 117 return self._check_perms(_perms, pull_request, user, api)
118 118
119 119 def check_user_update(self, pull_request, user, api=False):
120 120 owner = user.user_id == pull_request.user_id
121 121 return self.check_user_merge(pull_request, user, api) or owner
122 122
123 123 def check_user_delete(self, pull_request, user):
124 124 owner = user.user_id == pull_request.user_id
125 125 _perms = ('repository.admin',)
126 126 return self._check_perms(_perms, pull_request, user) or owner
127 127
128 128 def check_user_change_status(self, pull_request, user, api=False):
129 129 reviewer = user.user_id in [x.user_id for x in
130 130 pull_request.reviewers]
131 131 return self.check_user_update(pull_request, user, api) or reviewer
132 132
133 133 def check_user_comment(self, pull_request, user):
134 134 owner = user.user_id == pull_request.user_id
135 135 return self.check_user_read(pull_request, user) or owner
136 136
137 137 def get(self, pull_request):
138 138 return self.__get_pull_request(pull_request)
139 139
140 140 def _prepare_get_all_query(self, repo_name, source=False, statuses=None,
141 141 opened_by=None, order_by=None,
142 142 order_dir='desc', only_created=True):
143 143 repo = None
144 144 if repo_name:
145 145 repo = self._get_repo(repo_name)
146 146
147 147 q = PullRequest.query()
148 148
149 149 # source or target
150 150 if repo and source:
151 151 q = q.filter(PullRequest.source_repo == repo)
152 152 elif repo:
153 153 q = q.filter(PullRequest.target_repo == repo)
154 154
155 155 # closed,opened
156 156 if statuses:
157 157 q = q.filter(PullRequest.status.in_(statuses))
158 158
159 159 # opened by filter
160 160 if opened_by:
161 161 q = q.filter(PullRequest.user_id.in_(opened_by))
162 162
163 163 # only get those that are in "created" state
164 164 if only_created:
165 165 q = q.filter(PullRequest.pull_request_state == PullRequest.STATE_CREATED)
166 166
167 167 if order_by:
168 168 order_map = {
169 169 'name_raw': PullRequest.pull_request_id,
170 170 'id': PullRequest.pull_request_id,
171 171 'title': PullRequest.title,
172 172 'updated_on_raw': PullRequest.updated_on,
173 173 'target_repo': PullRequest.target_repo_id
174 174 }
175 175 if order_dir == 'asc':
176 176 q = q.order_by(order_map[order_by].asc())
177 177 else:
178 178 q = q.order_by(order_map[order_by].desc())
179 179
180 180 return q
181 181
182 182 def count_all(self, repo_name, source=False, statuses=None,
183 183 opened_by=None):
184 184 """
185 185 Count the number of pull requests for a specific repository.
186 186
187 187 :param repo_name: target or source repo
188 188 :param source: boolean flag to specify if repo_name refers to source
189 189 :param statuses: list of pull request statuses
190 190 :param opened_by: author user of the pull request
191 191 :returns: int number of pull requests
192 192 """
193 193 q = self._prepare_get_all_query(
194 194 repo_name, source=source, statuses=statuses, opened_by=opened_by)
195 195
196 196 return q.count()
197 197
198 198 def get_all(self, repo_name, source=False, statuses=None, opened_by=None,
199 199 offset=0, length=None, order_by=None, order_dir='desc'):
200 200 """
201 201 Get all pull requests for a specific repository.
202 202
203 203 :param repo_name: target or source repo
204 204 :param source: boolean flag to specify if repo_name refers to source
205 205 :param statuses: list of pull request statuses
206 206 :param opened_by: author user of the pull request
207 207 :param offset: pagination offset
208 208 :param length: length of returned list
209 209 :param order_by: order of the returned list
210 210 :param order_dir: 'asc' or 'desc' ordering direction
211 211 :returns: list of pull requests
212 212 """
213 213 q = self._prepare_get_all_query(
214 214 repo_name, source=source, statuses=statuses, opened_by=opened_by,
215 215 order_by=order_by, order_dir=order_dir)
216 216
217 217 if length:
218 218 pull_requests = q.limit(length).offset(offset).all()
219 219 else:
220 220 pull_requests = q.all()
221 221
222 222 return pull_requests
223 223
224 224 def count_awaiting_review(self, repo_name, source=False, statuses=None,
225 225 opened_by=None):
226 226 """
227 227 Count the number of pull requests for a specific repository that are
228 228 awaiting review.
229 229
230 230 :param repo_name: target or source repo
231 231 :param source: boolean flag to specify if repo_name refers to source
232 232 :param statuses: list of pull request statuses
233 233 :param opened_by: author user of the pull request
234 234 :returns: int number of pull requests
235 235 """
236 236 pull_requests = self.get_awaiting_review(
237 237 repo_name, source=source, statuses=statuses, opened_by=opened_by)
238 238
239 239 return len(pull_requests)
240 240
241 241 def get_awaiting_review(self, repo_name, source=False, statuses=None,
242 242 opened_by=None, offset=0, length=None,
243 243 order_by=None, order_dir='desc'):
244 244 """
245 245 Get all pull requests for a specific repository that are awaiting
246 246 review.
247 247
248 248 :param repo_name: target or source repo
249 249 :param source: boolean flag to specify if repo_name refers to source
250 250 :param statuses: list of pull request statuses
251 251 :param opened_by: author user of the pull request
252 252 :param offset: pagination offset
253 253 :param length: length of returned list
254 254 :param order_by: order of the returned list
255 255 :param order_dir: 'asc' or 'desc' ordering direction
256 256 :returns: list of pull requests
257 257 """
258 258 pull_requests = self.get_all(
259 259 repo_name, source=source, statuses=statuses, opened_by=opened_by,
260 260 order_by=order_by, order_dir=order_dir)
261 261
262 262 _filtered_pull_requests = []
263 263 for pr in pull_requests:
264 264 status = pr.calculated_review_status()
265 265 if status in [ChangesetStatus.STATUS_NOT_REVIEWED,
266 266 ChangesetStatus.STATUS_UNDER_REVIEW]:
267 267 _filtered_pull_requests.append(pr)
268 268 if length:
269 269 return _filtered_pull_requests[offset:offset+length]
270 270 else:
271 271 return _filtered_pull_requests
272 272
273 273 def count_awaiting_my_review(self, repo_name, source=False, statuses=None,
274 274 opened_by=None, user_id=None):
275 275 """
276 276 Count the number of pull requests for a specific repository that are
277 277 awaiting review from a specific user.
278 278
279 279 :param repo_name: target or source repo
280 280 :param source: boolean flag to specify if repo_name refers to source
281 281 :param statuses: list of pull request statuses
282 282 :param opened_by: author user of the pull request
283 283 :param user_id: reviewer user of the pull request
284 284 :returns: int number of pull requests
285 285 """
286 286 pull_requests = self.get_awaiting_my_review(
287 287 repo_name, source=source, statuses=statuses, opened_by=opened_by,
288 288 user_id=user_id)
289 289
290 290 return len(pull_requests)
291 291
292 292 def get_awaiting_my_review(self, repo_name, source=False, statuses=None,
293 293 opened_by=None, user_id=None, offset=0,
294 294 length=None, order_by=None, order_dir='desc'):
295 295 """
296 296 Get all pull requests for a specific repository that are awaiting
297 297 review from a specific user.
298 298
299 299 :param repo_name: target or source repo
300 300 :param source: boolean flag to specify if repo_name refers to source
301 301 :param statuses: list of pull request statuses
302 302 :param opened_by: author user of the pull request
303 303 :param user_id: reviewer user of the pull request
304 304 :param offset: pagination offset
305 305 :param length: length of returned list
306 306 :param order_by: order of the returned list
307 307 :param order_dir: 'asc' or 'desc' ordering direction
308 308 :returns: list of pull requests
309 309 """
310 310 pull_requests = self.get_all(
311 311 repo_name, source=source, statuses=statuses, opened_by=opened_by,
312 312 order_by=order_by, order_dir=order_dir)
313 313
314 314 _my = PullRequestModel().get_not_reviewed(user_id)
315 315 my_participation = []
316 316 for pr in pull_requests:
317 317 if pr in _my:
318 318 my_participation.append(pr)
319 319 _filtered_pull_requests = my_participation
320 320 if length:
321 321 return _filtered_pull_requests[offset:offset+length]
322 322 else:
323 323 return _filtered_pull_requests
324 324
325 325 def get_not_reviewed(self, user_id):
326 326 return [
327 327 x.pull_request for x in PullRequestReviewers.query().filter(
328 328 PullRequestReviewers.user_id == user_id).all()
329 329 ]
330 330
331 331 def _prepare_participating_query(self, user_id=None, statuses=None,
332 332 order_by=None, order_dir='desc'):
333 333 q = PullRequest.query()
334 334 if user_id:
335 335 reviewers_subquery = Session().query(
336 336 PullRequestReviewers.pull_request_id).filter(
337 337 PullRequestReviewers.user_id == user_id).subquery()
338 338 user_filter = or_(
339 339 PullRequest.user_id == user_id,
340 340 PullRequest.pull_request_id.in_(reviewers_subquery)
341 341 )
342 342 q = PullRequest.query().filter(user_filter)
343 343
344 344 # closed,opened
345 345 if statuses:
346 346 q = q.filter(PullRequest.status.in_(statuses))
347 347
348 348 if order_by:
349 349 order_map = {
350 350 'name_raw': PullRequest.pull_request_id,
351 351 'title': PullRequest.title,
352 352 'updated_on_raw': PullRequest.updated_on,
353 353 'target_repo': PullRequest.target_repo_id
354 354 }
355 355 if order_dir == 'asc':
356 356 q = q.order_by(order_map[order_by].asc())
357 357 else:
358 358 q = q.order_by(order_map[order_by].desc())
359 359
360 360 return q
361 361
362 362 def count_im_participating_in(self, user_id=None, statuses=None):
363 363 q = self._prepare_participating_query(user_id, statuses=statuses)
364 364 return q.count()
365 365
366 366 def get_im_participating_in(
367 367 self, user_id=None, statuses=None, offset=0,
368 368 length=None, order_by=None, order_dir='desc'):
369 369 """
370 370 Get all Pull requests that i'm participating in, or i have opened
371 371 """
372 372
373 373 q = self._prepare_participating_query(
374 374 user_id, statuses=statuses, order_by=order_by,
375 375 order_dir=order_dir)
376 376
377 377 if length:
378 378 pull_requests = q.limit(length).offset(offset).all()
379 379 else:
380 380 pull_requests = q.all()
381 381
382 382 return pull_requests
383 383
384 384 def get_versions(self, pull_request):
385 385 """
386 386 returns version of pull request sorted by ID descending
387 387 """
388 388 return PullRequestVersion.query()\
389 389 .filter(PullRequestVersion.pull_request == pull_request)\
390 390 .order_by(PullRequestVersion.pull_request_version_id.asc())\
391 391 .all()
392 392
393 393 def get_pr_version(self, pull_request_id, version=None):
394 394 at_version = None
395 395
396 396 if version and version == 'latest':
397 397 pull_request_ver = PullRequest.get(pull_request_id)
398 398 pull_request_obj = pull_request_ver
399 399 _org_pull_request_obj = pull_request_obj
400 400 at_version = 'latest'
401 401 elif version:
402 402 pull_request_ver = PullRequestVersion.get_or_404(version)
403 403 pull_request_obj = pull_request_ver
404 404 _org_pull_request_obj = pull_request_ver.pull_request
405 405 at_version = pull_request_ver.pull_request_version_id
406 406 else:
407 407 _org_pull_request_obj = pull_request_obj = PullRequest.get_or_404(
408 408 pull_request_id)
409 409
410 410 pull_request_display_obj = PullRequest.get_pr_display_object(
411 411 pull_request_obj, _org_pull_request_obj)
412 412
413 413 return _org_pull_request_obj, pull_request_obj, \
414 414 pull_request_display_obj, at_version
415 415
416 416 def create(self, created_by, source_repo, source_ref, target_repo,
417 417 target_ref, revisions, reviewers, title, description=None,
418 418 description_renderer=None,
419 419 reviewer_data=None, translator=None, auth_user=None):
420 420 translator = translator or get_current_request().translate
421 421
422 422 created_by_user = self._get_user(created_by)
423 423 auth_user = auth_user or created_by_user.AuthUser()
424 424 source_repo = self._get_repo(source_repo)
425 425 target_repo = self._get_repo(target_repo)
426 426
427 427 pull_request = PullRequest()
428 428 pull_request.source_repo = source_repo
429 429 pull_request.source_ref = source_ref
430 430 pull_request.target_repo = target_repo
431 431 pull_request.target_ref = target_ref
432 432 pull_request.revisions = revisions
433 433 pull_request.title = title
434 434 pull_request.description = description
435 435 pull_request.description_renderer = description_renderer
436 436 pull_request.author = created_by_user
437 437 pull_request.reviewer_data = reviewer_data
438 438 pull_request.pull_request_state = pull_request.STATE_CREATING
439 439 Session().add(pull_request)
440 440 Session().flush()
441 441
442 442 reviewer_ids = set()
443 443 # members / reviewers
444 444 for reviewer_object in reviewers:
445 445 user_id, reasons, mandatory, rules = reviewer_object
446 446 user = self._get_user(user_id)
447 447
448 448 # skip duplicates
449 449 if user.user_id in reviewer_ids:
450 450 continue
451 451
452 452 reviewer_ids.add(user.user_id)
453 453
454 454 reviewer = PullRequestReviewers()
455 455 reviewer.user = user
456 456 reviewer.pull_request = pull_request
457 457 reviewer.reasons = reasons
458 458 reviewer.mandatory = mandatory
459 459
460 460 # NOTE(marcink): pick only first rule for now
461 461 rule_id = list(rules)[0] if rules else None
462 462 rule = RepoReviewRule.get(rule_id) if rule_id else None
463 463 if rule:
464 464 review_group = rule.user_group_vote_rule(user_id)
465 465 # we check if this particular reviewer is member of a voting group
466 466 if review_group:
467 467 # NOTE(marcink):
468 468 # can be that user is member of more but we pick the first same,
469 469 # same as default reviewers algo
470 470 review_group = review_group[0]
471 471
472 472 rule_data = {
473 473 'rule_name':
474 474 rule.review_rule_name,
475 475 'rule_user_group_entry_id':
476 476 review_group.repo_review_rule_users_group_id,
477 477 'rule_user_group_name':
478 478 review_group.users_group.users_group_name,
479 479 'rule_user_group_members':
480 480 [x.user.username for x in review_group.users_group.members],
481 481 'rule_user_group_members_id':
482 482 [x.user.user_id for x in review_group.users_group.members],
483 483 }
484 484 # e.g {'vote_rule': -1, 'mandatory': True}
485 485 rule_data.update(review_group.rule_data())
486 486
487 487 reviewer.rule_data = rule_data
488 488
489 489 Session().add(reviewer)
490 490 Session().flush()
491 491
492 492 # Set approval status to "Under Review" for all commits which are
493 493 # part of this pull request.
494 494 ChangesetStatusModel().set_status(
495 495 repo=target_repo,
496 496 status=ChangesetStatus.STATUS_UNDER_REVIEW,
497 497 user=created_by_user,
498 498 pull_request=pull_request
499 499 )
500 500 # we commit early at this point. This has to do with a fact
501 501 # that before queries do some row-locking. And because of that
502 502 # we need to commit and finish transaction before below validate call
503 503 # that for large repos could be long resulting in long row locks
504 504 Session().commit()
505 505
506 506 # prepare workspace, and run initial merge simulation. Set state during that
507 507 # operation
508 508 pull_request = PullRequest.get(pull_request.pull_request_id)
509 509
510 510 # set as merging, for simulation, and if finished to created so we mark
511 511 # simulation is working fine
512 512 with pull_request.set_state(PullRequest.STATE_MERGING,
513 513 final_state=PullRequest.STATE_CREATED):
514 514 MergeCheck.validate(
515 515 pull_request, auth_user=auth_user, translator=translator)
516 516
517 517 self.notify_reviewers(pull_request, reviewer_ids)
518 518 self.trigger_pull_request_hook(
519 519 pull_request, created_by_user, 'create')
520 520
521 521 creation_data = pull_request.get_api_data(with_merge_state=False)
522 522 self._log_audit_action(
523 523 'repo.pull_request.create', {'data': creation_data},
524 524 auth_user, pull_request)
525 525
526 526 return pull_request
527 527
528 528 def trigger_pull_request_hook(self, pull_request, user, action, data=None):
529 529 pull_request = self.__get_pull_request(pull_request)
530 530 target_scm = pull_request.target_repo.scm_instance()
531 531 if action == 'create':
532 532 trigger_hook = hooks_utils.trigger_log_create_pull_request_hook
533 533 elif action == 'merge':
534 534 trigger_hook = hooks_utils.trigger_log_merge_pull_request_hook
535 535 elif action == 'close':
536 536 trigger_hook = hooks_utils.trigger_log_close_pull_request_hook
537 537 elif action == 'review_status_change':
538 538 trigger_hook = hooks_utils.trigger_log_review_pull_request_hook
539 539 elif action == 'update':
540 540 trigger_hook = hooks_utils.trigger_log_update_pull_request_hook
541 541 elif action == 'comment':
542 542 # dummy hook ! for comment. We want this function to handle all cases
543 543 def trigger_hook(*args, **kwargs):
544 544 pass
545 545 comment = data['comment']
546 546 events.trigger(events.PullRequestCommentEvent(pull_request, comment))
547 547 else:
548 548 return
549 549
550 550 trigger_hook(
551 551 username=user.username,
552 552 repo_name=pull_request.target_repo.repo_name,
553 553 repo_alias=target_scm.alias,
554 554 pull_request=pull_request,
555 555 data=data)
556 556
557 557 def _get_commit_ids(self, pull_request):
558 558 """
559 559 Return the commit ids of the merged pull request.
560 560
561 561 This method is not dealing correctly yet with the lack of autoupdates
562 562 nor with the implicit target updates.
563 563 For example: if a commit in the source repo is already in the target it
564 564 will be reported anyways.
565 565 """
566 566 merge_rev = pull_request.merge_rev
567 567 if merge_rev is None:
568 568 raise ValueError('This pull request was not merged yet')
569 569
570 570 commit_ids = list(pull_request.revisions)
571 571 if merge_rev not in commit_ids:
572 572 commit_ids.append(merge_rev)
573 573
574 574 return commit_ids
575 575
576 576 def merge_repo(self, pull_request, user, extras):
577 577 log.debug("Merging pull request %s", pull_request.pull_request_id)
578 578 extras['user_agent'] = 'internal-merge'
579 579 merge_state = self._merge_pull_request(pull_request, user, extras)
580 580 if merge_state.executed:
581 581 log.debug("Merge was successful, updating the pull request comments.")
582 582 self._comment_and_close_pr(pull_request, user, merge_state)
583 583
584 584 self._log_audit_action(
585 585 'repo.pull_request.merge',
586 586 {'merge_state': merge_state.__dict__},
587 587 user, pull_request)
588 588
589 589 else:
590 590 log.warn("Merge failed, not updating the pull request.")
591 591 return merge_state
592 592
593 593 def _merge_pull_request(self, pull_request, user, extras, merge_msg=None):
594 594 target_vcs = pull_request.target_repo.scm_instance()
595 595 source_vcs = pull_request.source_repo.scm_instance()
596 596
597 597 message = safe_unicode(merge_msg or vcs_settings.MERGE_MESSAGE_TMPL).format(
598 598 pr_id=pull_request.pull_request_id,
599 599 pr_title=pull_request.title,
600 600 source_repo=source_vcs.name,
601 601 source_ref_name=pull_request.source_ref_parts.name,
602 602 target_repo=target_vcs.name,
603 603 target_ref_name=pull_request.target_ref_parts.name,
604 604 )
605 605
606 606 workspace_id = self._workspace_id(pull_request)
607 607 repo_id = pull_request.target_repo.repo_id
608 608 use_rebase = self._use_rebase_for_merging(pull_request)
609 609 close_branch = self._close_branch_before_merging(pull_request)
610 610
611 611 target_ref = self._refresh_reference(
612 612 pull_request.target_ref_parts, target_vcs)
613 613
614 614 callback_daemon, extras = prepare_callback_daemon(
615 615 extras, protocol=vcs_settings.HOOKS_PROTOCOL,
616 616 host=vcs_settings.HOOKS_HOST,
617 617 use_direct_calls=vcs_settings.HOOKS_DIRECT_CALLS)
618 618
619 619 with callback_daemon:
620 620 # TODO: johbo: Implement a clean way to run a config_override
621 621 # for a single call.
622 622 target_vcs.config.set(
623 623 'rhodecode', 'RC_SCM_DATA', json.dumps(extras))
624 624
625 625 user_name = user.short_contact
626 626 merge_state = target_vcs.merge(
627 627 repo_id, workspace_id, target_ref, source_vcs,
628 628 pull_request.source_ref_parts,
629 629 user_name=user_name, user_email=user.email,
630 630 message=message, use_rebase=use_rebase,
631 631 close_branch=close_branch)
632 632 return merge_state
633 633
634 634 def _comment_and_close_pr(self, pull_request, user, merge_state, close_msg=None):
635 635 pull_request.merge_rev = merge_state.merge_ref.commit_id
636 636 pull_request.updated_on = datetime.datetime.now()
637 637 close_msg = close_msg or 'Pull request merged and closed'
638 638
639 639 CommentsModel().create(
640 640 text=safe_unicode(close_msg),
641 641 repo=pull_request.target_repo.repo_id,
642 642 user=user.user_id,
643 643 pull_request=pull_request.pull_request_id,
644 644 f_path=None,
645 645 line_no=None,
646 646 closing_pr=True
647 647 )
648 648
649 649 Session().add(pull_request)
650 650 Session().flush()
651 651 # TODO: paris: replace invalidation with less radical solution
652 652 ScmModel().mark_for_invalidation(
653 653 pull_request.target_repo.repo_name)
654 654 self.trigger_pull_request_hook(pull_request, user, 'merge')
655 655
656 656 def has_valid_update_type(self, pull_request):
657 657 source_ref_type = pull_request.source_ref_parts.type
658 658 return source_ref_type in self.REF_TYPES
659 659
660 660 def update_commits(self, pull_request):
661 661 """
662 662 Get the updated list of commits for the pull request
663 663 and return the new pull request version and the list
664 664 of commits processed by this update action
665 665 """
666 666 pull_request = self.__get_pull_request(pull_request)
667 667 source_ref_type = pull_request.source_ref_parts.type
668 668 source_ref_name = pull_request.source_ref_parts.name
669 669 source_ref_id = pull_request.source_ref_parts.commit_id
670 670
671 671 target_ref_type = pull_request.target_ref_parts.type
672 672 target_ref_name = pull_request.target_ref_parts.name
673 673 target_ref_id = pull_request.target_ref_parts.commit_id
674 674
675 675 if not self.has_valid_update_type(pull_request):
676 676 log.debug("Skipping update of pull request %s due to ref type: %s",
677 677 pull_request, source_ref_type)
678 678 return UpdateResponse(
679 679 executed=False,
680 680 reason=UpdateFailureReason.WRONG_REF_TYPE,
681 681 old=pull_request, new=None, changes=None,
682 682 source_changed=False, target_changed=False)
683 683
684 684 # source repo
685 685 source_repo = pull_request.source_repo.scm_instance()
686 686 try:
687 687 source_commit = source_repo.get_commit(commit_id=source_ref_name)
688 688 except CommitDoesNotExistError:
689 689 return UpdateResponse(
690 690 executed=False,
691 691 reason=UpdateFailureReason.MISSING_SOURCE_REF,
692 692 old=pull_request, new=None, changes=None,
693 693 source_changed=False, target_changed=False)
694 694
695 695 source_changed = source_ref_id != source_commit.raw_id
696 696
697 697 # target repo
698 698 target_repo = pull_request.target_repo.scm_instance()
699 699 try:
700 700 target_commit = target_repo.get_commit(commit_id=target_ref_name)
701 701 except CommitDoesNotExistError:
702 702 return UpdateResponse(
703 703 executed=False,
704 704 reason=UpdateFailureReason.MISSING_TARGET_REF,
705 705 old=pull_request, new=None, changes=None,
706 706 source_changed=False, target_changed=False)
707 707 target_changed = target_ref_id != target_commit.raw_id
708 708
709 709 if not (source_changed or target_changed):
710 710 log.debug("Nothing changed in pull request %s", pull_request)
711 711 return UpdateResponse(
712 712 executed=False,
713 713 reason=UpdateFailureReason.NO_CHANGE,
714 714 old=pull_request, new=None, changes=None,
715 715 source_changed=target_changed, target_changed=source_changed)
716 716
717 717 change_in_found = 'target repo' if target_changed else 'source repo'
718 718 log.debug('Updating pull request because of change in %s detected',
719 719 change_in_found)
720 720
721 721 # Finally there is a need for an update, in case of source change
722 722 # we create a new version, else just an update
723 723 if source_changed:
724 724 pull_request_version = self._create_version_from_snapshot(pull_request)
725 725 self._link_comments_to_version(pull_request_version)
726 726 else:
727 727 try:
728 728 ver = pull_request.versions[-1]
729 729 except IndexError:
730 730 ver = None
731 731
732 732 pull_request.pull_request_version_id = \
733 733 ver.pull_request_version_id if ver else None
734 734 pull_request_version = pull_request
735 735
736 736 try:
737 737 if target_ref_type in self.REF_TYPES:
738 738 target_commit = target_repo.get_commit(target_ref_name)
739 739 else:
740 740 target_commit = target_repo.get_commit(target_ref_id)
741 741 except CommitDoesNotExistError:
742 742 return UpdateResponse(
743 743 executed=False,
744 744 reason=UpdateFailureReason.MISSING_TARGET_REF,
745 745 old=pull_request, new=None, changes=None,
746 746 source_changed=source_changed, target_changed=target_changed)
747 747
748 748 # re-compute commit ids
749 749 old_commit_ids = pull_request.revisions
750 750 pre_load = ["author", "branch", "date", "message"]
751 751 commit_ranges = target_repo.compare(
752 752 target_commit.raw_id, source_commit.raw_id, source_repo, merge=True,
753 753 pre_load=pre_load)
754 754
755 755 ancestor = target_repo.get_common_ancestor(
756 756 target_commit.raw_id, source_commit.raw_id, source_repo)
757 757
758 758 pull_request.source_ref = '%s:%s:%s' % (
759 759 source_ref_type, source_ref_name, source_commit.raw_id)
760 760 pull_request.target_ref = '%s:%s:%s' % (
761 761 target_ref_type, target_ref_name, ancestor)
762 762
763 763 pull_request.revisions = [
764 764 commit.raw_id for commit in reversed(commit_ranges)]
765 765 pull_request.updated_on = datetime.datetime.now()
766 766 Session().add(pull_request)
767 767 new_commit_ids = pull_request.revisions
768 768
769 769 old_diff_data, new_diff_data = self._generate_update_diffs(
770 770 pull_request, pull_request_version)
771 771
772 772 # calculate commit and file changes
773 773 changes = self._calculate_commit_id_changes(
774 774 old_commit_ids, new_commit_ids)
775 775 file_changes = self._calculate_file_changes(
776 776 old_diff_data, new_diff_data)
777 777
778 778 # set comments as outdated if DIFFS changed
779 779 CommentsModel().outdate_comments(
780 780 pull_request, old_diff_data=old_diff_data,
781 781 new_diff_data=new_diff_data)
782 782
783 783 commit_changes = (changes.added or changes.removed)
784 784 file_node_changes = (
785 785 file_changes.added or file_changes.modified or file_changes.removed)
786 786 pr_has_changes = commit_changes or file_node_changes
787 787
788 788 # Add an automatic comment to the pull request, in case
789 789 # anything has changed
790 790 if pr_has_changes:
791 791 update_comment = CommentsModel().create(
792 792 text=self._render_update_message(changes, file_changes),
793 793 repo=pull_request.target_repo,
794 794 user=pull_request.author,
795 795 pull_request=pull_request,
796 796 send_email=False, renderer=DEFAULT_COMMENTS_RENDERER)
797 797
798 798 # Update status to "Under Review" for added commits
799 799 for commit_id in changes.added:
800 800 ChangesetStatusModel().set_status(
801 801 repo=pull_request.source_repo,
802 802 status=ChangesetStatus.STATUS_UNDER_REVIEW,
803 803 comment=update_comment,
804 804 user=pull_request.author,
805 805 pull_request=pull_request,
806 806 revision=commit_id)
807 807
808 808 log.debug(
809 809 'Updated pull request %s, added_ids: %s, common_ids: %s, '
810 810 'removed_ids: %s', pull_request.pull_request_id,
811 811 changes.added, changes.common, changes.removed)
812 812 log.debug(
813 813 'Updated pull request with the following file changes: %s',
814 814 file_changes)
815 815
816 816 log.info(
817 817 "Updated pull request %s from commit %s to commit %s, "
818 818 "stored new version %s of this pull request.",
819 819 pull_request.pull_request_id, source_ref_id,
820 820 pull_request.source_ref_parts.commit_id,
821 821 pull_request_version.pull_request_version_id)
822 822 Session().commit()
823 823 self.trigger_pull_request_hook(pull_request, pull_request.author, 'update')
824 824
825 825 return UpdateResponse(
826 826 executed=True, reason=UpdateFailureReason.NONE,
827 827 old=pull_request, new=pull_request_version, changes=changes,
828 828 source_changed=source_changed, target_changed=target_changed)
829 829
830 830 def _create_version_from_snapshot(self, pull_request):
831 831 version = PullRequestVersion()
832 832 version.title = pull_request.title
833 833 version.description = pull_request.description
834 834 version.status = pull_request.status
835 835 version.pull_request_state = pull_request.pull_request_state
836 836 version.created_on = datetime.datetime.now()
837 837 version.updated_on = pull_request.updated_on
838 838 version.user_id = pull_request.user_id
839 839 version.source_repo = pull_request.source_repo
840 840 version.source_ref = pull_request.source_ref
841 841 version.target_repo = pull_request.target_repo
842 842 version.target_ref = pull_request.target_ref
843 843
844 844 version._last_merge_source_rev = pull_request._last_merge_source_rev
845 845 version._last_merge_target_rev = pull_request._last_merge_target_rev
846 846 version.last_merge_status = pull_request.last_merge_status
847 847 version.shadow_merge_ref = pull_request.shadow_merge_ref
848 848 version.merge_rev = pull_request.merge_rev
849 849 version.reviewer_data = pull_request.reviewer_data
850 850
851 851 version.revisions = pull_request.revisions
852 852 version.pull_request = pull_request
853 853 Session().add(version)
854 854 Session().flush()
855 855
856 856 return version
857 857
858 858 def _generate_update_diffs(self, pull_request, pull_request_version):
859 859
860 860 diff_context = (
861 861 self.DIFF_CONTEXT +
862 862 CommentsModel.needed_extra_diff_context())
863 863 hide_whitespace_changes = False
864 864 source_repo = pull_request_version.source_repo
865 865 source_ref_id = pull_request_version.source_ref_parts.commit_id
866 866 target_ref_id = pull_request_version.target_ref_parts.commit_id
867 867 old_diff = self._get_diff_from_pr_or_version(
868 868 source_repo, source_ref_id, target_ref_id,
869 869 hide_whitespace_changes=hide_whitespace_changes, diff_context=diff_context)
870 870
871 871 source_repo = pull_request.source_repo
872 872 source_ref_id = pull_request.source_ref_parts.commit_id
873 873 target_ref_id = pull_request.target_ref_parts.commit_id
874 874
875 875 new_diff = self._get_diff_from_pr_or_version(
876 876 source_repo, source_ref_id, target_ref_id,
877 877 hide_whitespace_changes=hide_whitespace_changes, diff_context=diff_context)
878 878
879 879 old_diff_data = diffs.DiffProcessor(old_diff)
880 880 old_diff_data.prepare()
881 881 new_diff_data = diffs.DiffProcessor(new_diff)
882 882 new_diff_data.prepare()
883 883
884 884 return old_diff_data, new_diff_data
885 885
886 886 def _link_comments_to_version(self, pull_request_version):
887 887 """
888 888 Link all unlinked comments of this pull request to the given version.
889 889
890 890 :param pull_request_version: The `PullRequestVersion` to which
891 891 the comments shall be linked.
892 892
893 893 """
894 894 pull_request = pull_request_version.pull_request
895 895 comments = ChangesetComment.query()\
896 896 .filter(
897 897 # TODO: johbo: Should we query for the repo at all here?
898 898 # Pending decision on how comments of PRs are to be related
899 899 # to either the source repo, the target repo or no repo at all.
900 900 ChangesetComment.repo_id == pull_request.target_repo.repo_id,
901 901 ChangesetComment.pull_request == pull_request,
902 902 ChangesetComment.pull_request_version == None)\
903 903 .order_by(ChangesetComment.comment_id.asc())
904 904
905 905 # TODO: johbo: Find out why this breaks if it is done in a bulk
906 906 # operation.
907 907 for comment in comments:
908 908 comment.pull_request_version_id = (
909 909 pull_request_version.pull_request_version_id)
910 910 Session().add(comment)
911 911
912 912 def _calculate_commit_id_changes(self, old_ids, new_ids):
913 913 added = [x for x in new_ids if x not in old_ids]
914 914 common = [x for x in new_ids if x in old_ids]
915 915 removed = [x for x in old_ids if x not in new_ids]
916 916 total = new_ids
917 917 return ChangeTuple(added, common, removed, total)
918 918
919 919 def _calculate_file_changes(self, old_diff_data, new_diff_data):
920 920
921 921 old_files = OrderedDict()
922 922 for diff_data in old_diff_data.parsed_diff:
923 923 old_files[diff_data['filename']] = md5_safe(diff_data['raw_diff'])
924 924
925 925 added_files = []
926 926 modified_files = []
927 927 removed_files = []
928 928 for diff_data in new_diff_data.parsed_diff:
929 929 new_filename = diff_data['filename']
930 930 new_hash = md5_safe(diff_data['raw_diff'])
931 931
932 932 old_hash = old_files.get(new_filename)
933 933 if not old_hash:
934 934 # file is not present in old diff, means it's added
935 935 added_files.append(new_filename)
936 936 else:
937 937 if new_hash != old_hash:
938 938 modified_files.append(new_filename)
939 939 # now remove a file from old, since we have seen it already
940 940 del old_files[new_filename]
941 941
942 942 # removed files is when there are present in old, but not in NEW,
943 943 # since we remove old files that are present in new diff, left-overs
944 944 # if any should be the removed files
945 945 removed_files.extend(old_files.keys())
946 946
947 947 return FileChangeTuple(added_files, modified_files, removed_files)
948 948
949 949 def _render_update_message(self, changes, file_changes):
950 950 """
951 951 render the message using DEFAULT_COMMENTS_RENDERER (RST renderer),
952 952 so it's always looking the same disregarding on which default
953 953 renderer system is using.
954 954
955 955 :param changes: changes named tuple
956 956 :param file_changes: file changes named tuple
957 957
958 958 """
959 959 new_status = ChangesetStatus.get_status_lbl(
960 960 ChangesetStatus.STATUS_UNDER_REVIEW)
961 961
962 962 changed_files = (
963 963 file_changes.added + file_changes.modified + file_changes.removed)
964 964
965 965 params = {
966 966 'under_review_label': new_status,
967 967 'added_commits': changes.added,
968 968 'removed_commits': changes.removed,
969 969 'changed_files': changed_files,
970 970 'added_files': file_changes.added,
971 971 'modified_files': file_changes.modified,
972 972 'removed_files': file_changes.removed,
973 973 }
974 974 renderer = RstTemplateRenderer()
975 975 return renderer.render('pull_request_update.mako', **params)
976 976
977 977 def edit(self, pull_request, title, description, description_renderer, user):
978 978 pull_request = self.__get_pull_request(pull_request)
979 979 old_data = pull_request.get_api_data(with_merge_state=False)
980 980 if pull_request.is_closed():
981 981 raise ValueError('This pull request is closed')
982 982 if title:
983 983 pull_request.title = title
984 984 pull_request.description = description
985 985 pull_request.updated_on = datetime.datetime.now()
986 986 pull_request.description_renderer = description_renderer
987 987 Session().add(pull_request)
988 988 self._log_audit_action(
989 989 'repo.pull_request.edit', {'old_data': old_data},
990 990 user, pull_request)
991 991
992 992 def update_reviewers(self, pull_request, reviewer_data, user):
993 993 """
994 994 Update the reviewers in the pull request
995 995
996 996 :param pull_request: the pr to update
997 997 :param reviewer_data: list of tuples
998 998 [(user, ['reason1', 'reason2'], mandatory_flag, [rules])]
999 999 """
1000 1000 pull_request = self.__get_pull_request(pull_request)
1001 1001 if pull_request.is_closed():
1002 1002 raise ValueError('This pull request is closed')
1003 1003
1004 1004 reviewers = {}
1005 1005 for user_id, reasons, mandatory, rules in reviewer_data:
1006 1006 if isinstance(user_id, (int, compat.string_types)):
1007 1007 user_id = self._get_user(user_id).user_id
1008 1008 reviewers[user_id] = {
1009 1009 'reasons': reasons, 'mandatory': mandatory}
1010 1010
1011 1011 reviewers_ids = set(reviewers.keys())
1012 1012 current_reviewers = PullRequestReviewers.query()\
1013 1013 .filter(PullRequestReviewers.pull_request ==
1014 1014 pull_request).all()
1015 1015 current_reviewers_ids = set([x.user.user_id for x in current_reviewers])
1016 1016
1017 1017 ids_to_add = reviewers_ids.difference(current_reviewers_ids)
1018 1018 ids_to_remove = current_reviewers_ids.difference(reviewers_ids)
1019 1019
1020 1020 log.debug("Adding %s reviewers", ids_to_add)
1021 1021 log.debug("Removing %s reviewers", ids_to_remove)
1022 1022 changed = False
1023 1023 for uid in ids_to_add:
1024 1024 changed = True
1025 1025 _usr = self._get_user(uid)
1026 1026 reviewer = PullRequestReviewers()
1027 1027 reviewer.user = _usr
1028 1028 reviewer.pull_request = pull_request
1029 1029 reviewer.reasons = reviewers[uid]['reasons']
1030 1030 # NOTE(marcink): mandatory shouldn't be changed now
1031 1031 # reviewer.mandatory = reviewers[uid]['reasons']
1032 1032 Session().add(reviewer)
1033 1033 self._log_audit_action(
1034 1034 'repo.pull_request.reviewer.add', {'data': reviewer.get_dict()},
1035 1035 user, pull_request)
1036 1036
1037 1037 for uid in ids_to_remove:
1038 1038 changed = True
1039 1039 reviewers = PullRequestReviewers.query()\
1040 1040 .filter(PullRequestReviewers.user_id == uid,
1041 1041 PullRequestReviewers.pull_request == pull_request)\
1042 1042 .all()
1043 1043 # use .all() in case we accidentally added the same person twice
1044 1044 # this CAN happen due to the lack of DB checks
1045 1045 for obj in reviewers:
1046 1046 old_data = obj.get_dict()
1047 1047 Session().delete(obj)
1048 1048 self._log_audit_action(
1049 1049 'repo.pull_request.reviewer.delete',
1050 1050 {'old_data': old_data}, user, pull_request)
1051 1051
1052 1052 if changed:
1053 1053 pull_request.updated_on = datetime.datetime.now()
1054 1054 Session().add(pull_request)
1055 1055
1056 1056 self.notify_reviewers(pull_request, ids_to_add)
1057 1057 return ids_to_add, ids_to_remove
1058 1058
1059 1059 def get_url(self, pull_request, request=None, permalink=False):
1060 1060 if not request:
1061 1061 request = get_current_request()
1062 1062
1063 1063 if permalink:
1064 1064 return request.route_url(
1065 1065 'pull_requests_global',
1066 1066 pull_request_id=pull_request.pull_request_id,)
1067 1067 else:
1068 1068 return request.route_url('pullrequest_show',
1069 1069 repo_name=safe_str(pull_request.target_repo.repo_name),
1070 1070 pull_request_id=pull_request.pull_request_id,)
1071 1071
1072 1072 def get_shadow_clone_url(self, pull_request, request=None):
1073 1073 """
1074 1074 Returns qualified url pointing to the shadow repository. If this pull
1075 1075 request is closed there is no shadow repository and ``None`` will be
1076 1076 returned.
1077 1077 """
1078 1078 if pull_request.is_closed():
1079 1079 return None
1080 1080 else:
1081 1081 pr_url = urllib.unquote(self.get_url(pull_request, request=request))
1082 1082 return safe_unicode('{pr_url}/repository'.format(pr_url=pr_url))
1083 1083
1084 1084 def notify_reviewers(self, pull_request, reviewers_ids):
1085 1085 # notification to reviewers
1086 1086 if not reviewers_ids:
1087 1087 return
1088 1088
1089 1089 pull_request_obj = pull_request
1090 1090 # get the current participants of this pull request
1091 1091 recipients = reviewers_ids
1092 1092 notification_type = EmailNotificationModel.TYPE_PULL_REQUEST
1093 1093
1094 1094 pr_source_repo = pull_request_obj.source_repo
1095 1095 pr_target_repo = pull_request_obj.target_repo
1096 1096
1097 1097 pr_url = h.route_url('pullrequest_show',
1098 1098 repo_name=pr_target_repo.repo_name,
1099 1099 pull_request_id=pull_request_obj.pull_request_id,)
1100 1100
1101 1101 # set some variables for email notification
1102 1102 pr_target_repo_url = h.route_url(
1103 1103 'repo_summary', repo_name=pr_target_repo.repo_name)
1104 1104
1105 1105 pr_source_repo_url = h.route_url(
1106 1106 'repo_summary', repo_name=pr_source_repo.repo_name)
1107 1107
1108 1108 # pull request specifics
1109 1109 pull_request_commits = [
1110 1110 (x.raw_id, x.message)
1111 1111 for x in map(pr_source_repo.get_commit, pull_request.revisions)]
1112 1112
1113 1113 kwargs = {
1114 1114 'user': pull_request.author,
1115 1115 'pull_request': pull_request_obj,
1116 1116 'pull_request_commits': pull_request_commits,
1117 1117
1118 1118 'pull_request_target_repo': pr_target_repo,
1119 1119 'pull_request_target_repo_url': pr_target_repo_url,
1120 1120
1121 1121 'pull_request_source_repo': pr_source_repo,
1122 1122 'pull_request_source_repo_url': pr_source_repo_url,
1123 1123
1124 1124 'pull_request_url': pr_url,
1125 1125 }
1126 1126
1127 1127 # pre-generate the subject for notification itself
1128 1128 (subject,
1129 1129 _h, _e, # we don't care about those
1130 1130 body_plaintext) = EmailNotificationModel().render_email(
1131 1131 notification_type, **kwargs)
1132 1132
1133 1133 # create notification objects, and emails
1134 1134 NotificationModel().create(
1135 1135 created_by=pull_request.author,
1136 1136 notification_subject=subject,
1137 1137 notification_body=body_plaintext,
1138 1138 notification_type=notification_type,
1139 1139 recipients=recipients,
1140 1140 email_kwargs=kwargs,
1141 1141 )
1142 1142
1143 1143 def delete(self, pull_request, user):
1144 1144 pull_request = self.__get_pull_request(pull_request)
1145 1145 old_data = pull_request.get_api_data(with_merge_state=False)
1146 1146 self._cleanup_merge_workspace(pull_request)
1147 1147 self._log_audit_action(
1148 1148 'repo.pull_request.delete', {'old_data': old_data},
1149 1149 user, pull_request)
1150 1150 Session().delete(pull_request)
1151 1151
1152 1152 def close_pull_request(self, pull_request, user):
1153 1153 pull_request = self.__get_pull_request(pull_request)
1154 1154 self._cleanup_merge_workspace(pull_request)
1155 1155 pull_request.status = PullRequest.STATUS_CLOSED
1156 1156 pull_request.updated_on = datetime.datetime.now()
1157 1157 Session().add(pull_request)
1158 1158 self.trigger_pull_request_hook(
1159 1159 pull_request, pull_request.author, 'close')
1160 1160
1161 1161 pr_data = pull_request.get_api_data(with_merge_state=False)
1162 1162 self._log_audit_action(
1163 1163 'repo.pull_request.close', {'data': pr_data}, user, pull_request)
1164 1164
1165 1165 def close_pull_request_with_comment(
1166 1166 self, pull_request, user, repo, message=None, auth_user=None):
1167 1167
1168 1168 pull_request_review_status = pull_request.calculated_review_status()
1169 1169
1170 1170 if pull_request_review_status == ChangesetStatus.STATUS_APPROVED:
1171 1171 # approved only if we have voting consent
1172 1172 status = ChangesetStatus.STATUS_APPROVED
1173 1173 else:
1174 1174 status = ChangesetStatus.STATUS_REJECTED
1175 1175 status_lbl = ChangesetStatus.get_status_lbl(status)
1176 1176
1177 1177 default_message = (
1178 1178 'Closing with status change {transition_icon} {status}.'
1179 1179 ).format(transition_icon='>', status=status_lbl)
1180 1180 text = message or default_message
1181 1181
1182 1182 # create a comment, and link it to new status
1183 1183 comment = CommentsModel().create(
1184 1184 text=text,
1185 1185 repo=repo.repo_id,
1186 1186 user=user.user_id,
1187 1187 pull_request=pull_request.pull_request_id,
1188 1188 status_change=status_lbl,
1189 1189 status_change_type=status,
1190 1190 closing_pr=True,
1191 1191 auth_user=auth_user,
1192 1192 )
1193 1193
1194 1194 # calculate old status before we change it
1195 1195 old_calculated_status = pull_request.calculated_review_status()
1196 1196 ChangesetStatusModel().set_status(
1197 1197 repo.repo_id,
1198 1198 status,
1199 1199 user.user_id,
1200 1200 comment=comment,
1201 1201 pull_request=pull_request.pull_request_id
1202 1202 )
1203 1203
1204 1204 Session().flush()
1205 1205 events.trigger(events.PullRequestCommentEvent(pull_request, comment))
1206 1206 # we now calculate the status of pull request again, and based on that
1207 1207 # calculation trigger status change. This might happen in cases
1208 1208 # that non-reviewer admin closes a pr, which means his vote doesn't
1209 1209 # change the status, while if he's a reviewer this might change it.
1210 1210 calculated_status = pull_request.calculated_review_status()
1211 1211 if old_calculated_status != calculated_status:
1212 1212 self.trigger_pull_request_hook(
1213 1213 pull_request, user, 'review_status_change',
1214 1214 data={'status': calculated_status})
1215 1215
1216 1216 # finally close the PR
1217 1217 PullRequestModel().close_pull_request(
1218 1218 pull_request.pull_request_id, user)
1219 1219
1220 1220 return comment, status
1221 1221
1222 1222 def merge_status(self, pull_request, translator=None,
1223 1223 force_shadow_repo_refresh=False):
1224 1224 _ = translator or get_current_request().translate
1225 1225
1226 1226 if not self._is_merge_enabled(pull_request):
1227 1227 return False, _('Server-side pull request merging is disabled.')
1228 1228 if pull_request.is_closed():
1229 1229 return False, _('This pull request is closed.')
1230 1230 merge_possible, msg = self._check_repo_requirements(
1231 1231 target=pull_request.target_repo, source=pull_request.source_repo,
1232 1232 translator=_)
1233 1233 if not merge_possible:
1234 1234 return merge_possible, msg
1235 1235
1236 1236 try:
1237 1237 resp = self._try_merge(
1238 1238 pull_request,
1239 1239 force_shadow_repo_refresh=force_shadow_repo_refresh)
1240 1240 log.debug("Merge response: %s", resp)
1241 1241 status = resp.possible, resp.merge_status_message
1242 1242 except NotImplementedError:
1243 1243 status = False, _('Pull request merging is not supported.')
1244 1244
1245 1245 return status
1246 1246
1247 1247 def _check_repo_requirements(self, target, source, translator):
1248 1248 """
1249 1249 Check if `target` and `source` have compatible requirements.
1250 1250
1251 1251 Currently this is just checking for largefiles.
1252 1252 """
1253 1253 _ = translator
1254 1254 target_has_largefiles = self._has_largefiles(target)
1255 1255 source_has_largefiles = self._has_largefiles(source)
1256 1256 merge_possible = True
1257 1257 message = u''
1258 1258
1259 1259 if target_has_largefiles != source_has_largefiles:
1260 1260 merge_possible = False
1261 1261 if source_has_largefiles:
1262 1262 message = _(
1263 1263 'Target repository large files support is disabled.')
1264 1264 else:
1265 1265 message = _(
1266 1266 'Source repository large files support is disabled.')
1267 1267
1268 1268 return merge_possible, message
1269 1269
1270 1270 def _has_largefiles(self, repo):
1271 1271 largefiles_ui = VcsSettingsModel(repo=repo).get_ui_settings(
1272 1272 'extensions', 'largefiles')
1273 1273 return largefiles_ui and largefiles_ui[0].active
1274 1274
1275 1275 def _try_merge(self, pull_request, force_shadow_repo_refresh=False):
1276 1276 """
1277 1277 Try to merge the pull request and return the merge status.
1278 1278 """
1279 1279 log.debug(
1280 1280 "Trying out if the pull request %s can be merged. Force_refresh=%s",
1281 1281 pull_request.pull_request_id, force_shadow_repo_refresh)
1282 1282 target_vcs = pull_request.target_repo.scm_instance()
1283 1283 # Refresh the target reference.
1284 1284 try:
1285 1285 target_ref = self._refresh_reference(
1286 1286 pull_request.target_ref_parts, target_vcs)
1287 1287 except CommitDoesNotExistError:
1288 1288 merge_state = MergeResponse(
1289 1289 False, False, None, MergeFailureReason.MISSING_TARGET_REF,
1290 1290 metadata={'target_ref': pull_request.target_ref_parts})
1291 1291 return merge_state
1292 1292
1293 1293 target_locked = pull_request.target_repo.locked
1294 1294 if target_locked and target_locked[0]:
1295 1295 locked_by = 'user:{}'.format(target_locked[0])
1296 1296 log.debug("The target repository is locked by %s.", locked_by)
1297 1297 merge_state = MergeResponse(
1298 1298 False, False, None, MergeFailureReason.TARGET_IS_LOCKED,
1299 1299 metadata={'locked_by': locked_by})
1300 1300 elif force_shadow_repo_refresh or self._needs_merge_state_refresh(
1301 1301 pull_request, target_ref):
1302 1302 log.debug("Refreshing the merge status of the repository.")
1303 1303 merge_state = self._refresh_merge_state(
1304 1304 pull_request, target_vcs, target_ref)
1305 1305 else:
1306 possible = pull_request.\
1307 last_merge_status == MergeFailureReason.NONE
1306 possible = pull_request.last_merge_status == MergeFailureReason.NONE
1307 metadata = {
1308 'target_ref': pull_request.target_ref_parts,
1309 'source_ref': pull_request.source_ref_parts
1310 }
1308 1311 merge_state = MergeResponse(
1309 possible, False, None, pull_request.last_merge_status)
1312 possible, False, None, pull_request.last_merge_status, metadata=metadata)
1310 1313
1311 1314 return merge_state
1312 1315
1313 1316 def _refresh_reference(self, reference, vcs_repository):
1314 1317 if reference.type in self.UPDATABLE_REF_TYPES:
1315 1318 name_or_id = reference.name
1316 1319 else:
1317 1320 name_or_id = reference.commit_id
1318 1321 refreshed_commit = vcs_repository.get_commit(name_or_id)
1319 1322 refreshed_reference = Reference(
1320 1323 reference.type, reference.name, refreshed_commit.raw_id)
1321 1324 return refreshed_reference
1322 1325
1323 1326 def _needs_merge_state_refresh(self, pull_request, target_reference):
1324 1327 return not(
1325 1328 pull_request.revisions and
1326 1329 pull_request.revisions[0] == pull_request._last_merge_source_rev and
1327 1330 target_reference.commit_id == pull_request._last_merge_target_rev)
1328 1331
1329 1332 def _refresh_merge_state(self, pull_request, target_vcs, target_reference):
1330 1333 workspace_id = self._workspace_id(pull_request)
1331 1334 source_vcs = pull_request.source_repo.scm_instance()
1332 1335 repo_id = pull_request.target_repo.repo_id
1333 1336 use_rebase = self._use_rebase_for_merging(pull_request)
1334 1337 close_branch = self._close_branch_before_merging(pull_request)
1335 1338 merge_state = target_vcs.merge(
1336 1339 repo_id, workspace_id,
1337 1340 target_reference, source_vcs, pull_request.source_ref_parts,
1338 1341 dry_run=True, use_rebase=use_rebase,
1339 1342 close_branch=close_branch)
1340 1343
1341 1344 # Do not store the response if there was an unknown error.
1342 1345 if merge_state.failure_reason != MergeFailureReason.UNKNOWN:
1343 1346 pull_request._last_merge_source_rev = \
1344 1347 pull_request.source_ref_parts.commit_id
1345 1348 pull_request._last_merge_target_rev = target_reference.commit_id
1346 1349 pull_request.last_merge_status = merge_state.failure_reason
1347 1350 pull_request.shadow_merge_ref = merge_state.merge_ref
1348 1351 Session().add(pull_request)
1349 1352 Session().commit()
1350 1353
1351 1354 return merge_state
1352 1355
1353 1356 def _workspace_id(self, pull_request):
1354 1357 workspace_id = 'pr-%s' % pull_request.pull_request_id
1355 1358 return workspace_id
1356 1359
1357 1360 def generate_repo_data(self, repo, commit_id=None, branch=None,
1358 1361 bookmark=None, translator=None):
1359 1362 from rhodecode.model.repo import RepoModel
1360 1363
1361 1364 all_refs, selected_ref = \
1362 1365 self._get_repo_pullrequest_sources(
1363 1366 repo.scm_instance(), commit_id=commit_id,
1364 1367 branch=branch, bookmark=bookmark, translator=translator)
1365 1368
1366 1369 refs_select2 = []
1367 1370 for element in all_refs:
1368 1371 children = [{'id': x[0], 'text': x[1]} for x in element[0]]
1369 1372 refs_select2.append({'text': element[1], 'children': children})
1370 1373
1371 1374 return {
1372 1375 'user': {
1373 1376 'user_id': repo.user.user_id,
1374 1377 'username': repo.user.username,
1375 1378 'firstname': repo.user.first_name,
1376 1379 'lastname': repo.user.last_name,
1377 1380 'gravatar_link': h.gravatar_url(repo.user.email, 14),
1378 1381 },
1379 1382 'name': repo.repo_name,
1380 1383 'link': RepoModel().get_url(repo),
1381 1384 'description': h.chop_at_smart(repo.description_safe, '\n'),
1382 1385 'refs': {
1383 1386 'all_refs': all_refs,
1384 1387 'selected_ref': selected_ref,
1385 1388 'select2_refs': refs_select2
1386 1389 }
1387 1390 }
1388 1391
1389 1392 def generate_pullrequest_title(self, source, source_ref, target):
1390 1393 return u'{source}#{at_ref} to {target}'.format(
1391 1394 source=source,
1392 1395 at_ref=source_ref,
1393 1396 target=target,
1394 1397 )
1395 1398
1396 1399 def _cleanup_merge_workspace(self, pull_request):
1397 1400 # Merging related cleanup
1398 1401 repo_id = pull_request.target_repo.repo_id
1399 1402 target_scm = pull_request.target_repo.scm_instance()
1400 1403 workspace_id = self._workspace_id(pull_request)
1401 1404
1402 1405 try:
1403 1406 target_scm.cleanup_merge_workspace(repo_id, workspace_id)
1404 1407 except NotImplementedError:
1405 1408 pass
1406 1409
1407 1410 def _get_repo_pullrequest_sources(
1408 1411 self, repo, commit_id=None, branch=None, bookmark=None,
1409 1412 translator=None):
1410 1413 """
1411 1414 Return a structure with repo's interesting commits, suitable for
1412 1415 the selectors in pullrequest controller
1413 1416
1414 1417 :param commit_id: a commit that must be in the list somehow
1415 1418 and selected by default
1416 1419 :param branch: a branch that must be in the list and selected
1417 1420 by default - even if closed
1418 1421 :param bookmark: a bookmark that must be in the list and selected
1419 1422 """
1420 1423 _ = translator or get_current_request().translate
1421 1424
1422 1425 commit_id = safe_str(commit_id) if commit_id else None
1423 1426 branch = safe_unicode(branch) if branch else None
1424 1427 bookmark = safe_unicode(bookmark) if bookmark else None
1425 1428
1426 1429 selected = None
1427 1430
1428 1431 # order matters: first source that has commit_id in it will be selected
1429 1432 sources = []
1430 1433 sources.append(('book', repo.bookmarks.items(), _('Bookmarks'), bookmark))
1431 1434 sources.append(('branch', repo.branches.items(), _('Branches'), branch))
1432 1435
1433 1436 if commit_id:
1434 1437 ref_commit = (h.short_id(commit_id), commit_id)
1435 1438 sources.append(('rev', [ref_commit], _('Commit IDs'), commit_id))
1436 1439
1437 1440 sources.append(
1438 1441 ('branch', repo.branches_closed.items(), _('Closed Branches'), branch),
1439 1442 )
1440 1443
1441 1444 groups = []
1442 1445
1443 1446 for group_key, ref_list, group_name, match in sources:
1444 1447 group_refs = []
1445 1448 for ref_name, ref_id in ref_list:
1446 1449 ref_key = u'{}:{}:{}'.format(group_key, ref_name, ref_id)
1447 1450 group_refs.append((ref_key, ref_name))
1448 1451
1449 1452 if not selected:
1450 1453 if set([commit_id, match]) & set([ref_id, ref_name]):
1451 1454 selected = ref_key
1452 1455
1453 1456 if group_refs:
1454 1457 groups.append((group_refs, group_name))
1455 1458
1456 1459 if not selected:
1457 1460 ref = commit_id or branch or bookmark
1458 1461 if ref:
1459 1462 raise CommitDoesNotExistError(
1460 1463 u'No commit refs could be found matching: {}'.format(ref))
1461 1464 elif repo.DEFAULT_BRANCH_NAME in repo.branches:
1462 1465 selected = u'branch:{}:{}'.format(
1463 1466 safe_unicode(repo.DEFAULT_BRANCH_NAME),
1464 1467 safe_unicode(repo.branches[repo.DEFAULT_BRANCH_NAME])
1465 1468 )
1466 1469 elif repo.commit_ids:
1467 1470 # make the user select in this case
1468 1471 selected = None
1469 1472 else:
1470 1473 raise EmptyRepositoryError()
1471 1474 return groups, selected
1472 1475
1473 1476 def get_diff(self, source_repo, source_ref_id, target_ref_id,
1474 1477 hide_whitespace_changes, diff_context):
1475 1478
1476 1479 return self._get_diff_from_pr_or_version(
1477 1480 source_repo, source_ref_id, target_ref_id,
1478 1481 hide_whitespace_changes=hide_whitespace_changes, diff_context=diff_context)
1479 1482
1480 1483 def _get_diff_from_pr_or_version(
1481 1484 self, source_repo, source_ref_id, target_ref_id,
1482 1485 hide_whitespace_changes, diff_context):
1483 1486
1484 1487 target_commit = source_repo.get_commit(
1485 1488 commit_id=safe_str(target_ref_id))
1486 1489 source_commit = source_repo.get_commit(
1487 1490 commit_id=safe_str(source_ref_id))
1488 1491 if isinstance(source_repo, Repository):
1489 1492 vcs_repo = source_repo.scm_instance()
1490 1493 else:
1491 1494 vcs_repo = source_repo
1492 1495
1493 1496 # TODO: johbo: In the context of an update, we cannot reach
1494 1497 # the old commit anymore with our normal mechanisms. It needs
1495 1498 # some sort of special support in the vcs layer to avoid this
1496 1499 # workaround.
1497 1500 if (source_commit.raw_id == vcs_repo.EMPTY_COMMIT_ID and
1498 1501 vcs_repo.alias == 'git'):
1499 1502 source_commit.raw_id = safe_str(source_ref_id)
1500 1503
1501 1504 log.debug('calculating diff between '
1502 1505 'source_ref:%s and target_ref:%s for repo `%s`',
1503 1506 target_ref_id, source_ref_id,
1504 1507 safe_unicode(vcs_repo.path))
1505 1508
1506 1509 vcs_diff = vcs_repo.get_diff(
1507 1510 commit1=target_commit, commit2=source_commit,
1508 1511 ignore_whitespace=hide_whitespace_changes, context=diff_context)
1509 1512 return vcs_diff
1510 1513
1511 1514 def _is_merge_enabled(self, pull_request):
1512 1515 return self._get_general_setting(
1513 1516 pull_request, 'rhodecode_pr_merge_enabled')
1514 1517
1515 1518 def _use_rebase_for_merging(self, pull_request):
1516 1519 repo_type = pull_request.target_repo.repo_type
1517 1520 if repo_type == 'hg':
1518 1521 return self._get_general_setting(
1519 1522 pull_request, 'rhodecode_hg_use_rebase_for_merging')
1520 1523 elif repo_type == 'git':
1521 1524 return self._get_general_setting(
1522 1525 pull_request, 'rhodecode_git_use_rebase_for_merging')
1523 1526
1524 1527 return False
1525 1528
1526 1529 def _close_branch_before_merging(self, pull_request):
1527 1530 repo_type = pull_request.target_repo.repo_type
1528 1531 if repo_type == 'hg':
1529 1532 return self._get_general_setting(
1530 1533 pull_request, 'rhodecode_hg_close_branch_before_merging')
1531 1534 elif repo_type == 'git':
1532 1535 return self._get_general_setting(
1533 1536 pull_request, 'rhodecode_git_close_branch_before_merging')
1534 1537
1535 1538 return False
1536 1539
1537 1540 def _get_general_setting(self, pull_request, settings_key, default=False):
1538 1541 settings_model = VcsSettingsModel(repo=pull_request.target_repo)
1539 1542 settings = settings_model.get_general_settings()
1540 1543 return settings.get(settings_key, default)
1541 1544
1542 1545 def _log_audit_action(self, action, action_data, user, pull_request):
1543 1546 audit_logger.store(
1544 1547 action=action,
1545 1548 action_data=action_data,
1546 1549 user=user,
1547 1550 repo=pull_request.target_repo)
1548 1551
1549 1552 def get_reviewer_functions(self):
1550 1553 """
1551 1554 Fetches functions for validation and fetching default reviewers.
1552 1555 If available we use the EE package, else we fallback to CE
1553 1556 package functions
1554 1557 """
1555 1558 try:
1556 1559 from rc_reviewers.utils import get_default_reviewers_data
1557 1560 from rc_reviewers.utils import validate_default_reviewers
1558 1561 except ImportError:
1559 1562 from rhodecode.apps.repository.utils import get_default_reviewers_data
1560 1563 from rhodecode.apps.repository.utils import validate_default_reviewers
1561 1564
1562 1565 return get_default_reviewers_data, validate_default_reviewers
1563 1566
1564 1567
1565 1568 class MergeCheck(object):
1566 1569 """
1567 1570 Perform Merge Checks and returns a check object which stores information
1568 1571 about merge errors, and merge conditions
1569 1572 """
1570 1573 TODO_CHECK = 'todo'
1571 1574 PERM_CHECK = 'perm'
1572 1575 REVIEW_CHECK = 'review'
1573 1576 MERGE_CHECK = 'merge'
1574 1577
1575 1578 def __init__(self):
1576 1579 self.review_status = None
1577 1580 self.merge_possible = None
1578 1581 self.merge_msg = ''
1579 1582 self.failed = None
1580 1583 self.errors = []
1581 1584 self.error_details = OrderedDict()
1582 1585
1583 1586 def push_error(self, error_type, message, error_key, details):
1584 1587 self.failed = True
1585 1588 self.errors.append([error_type, message])
1586 1589 self.error_details[error_key] = dict(
1587 1590 details=details,
1588 1591 error_type=error_type,
1589 1592 message=message
1590 1593 )
1591 1594
1592 1595 @classmethod
1593 1596 def validate(cls, pull_request, auth_user, translator, fail_early=False,
1594 1597 force_shadow_repo_refresh=False):
1595 1598 _ = translator
1596 1599 merge_check = cls()
1597 1600
1598 1601 # permissions to merge
1599 1602 user_allowed_to_merge = PullRequestModel().check_user_merge(
1600 1603 pull_request, auth_user)
1601 1604 if not user_allowed_to_merge:
1602 1605 log.debug("MergeCheck: cannot merge, approval is pending.")
1603 1606
1604 1607 msg = _('User `{}` not allowed to perform merge.').format(auth_user.username)
1605 1608 merge_check.push_error('error', msg, cls.PERM_CHECK, auth_user.username)
1606 1609 if fail_early:
1607 1610 return merge_check
1608 1611
1609 1612 # permission to merge into the target branch
1610 1613 target_commit_id = pull_request.target_ref_parts.commit_id
1611 1614 if pull_request.target_ref_parts.type == 'branch':
1612 1615 branch_name = pull_request.target_ref_parts.name
1613 1616 else:
1614 1617 # for mercurial we can always figure out the branch from the commit
1615 1618 # in case of bookmark
1616 1619 target_commit = pull_request.target_repo.get_commit(target_commit_id)
1617 1620 branch_name = target_commit.branch
1618 1621
1619 1622 rule, branch_perm = auth_user.get_rule_and_branch_permission(
1620 1623 pull_request.target_repo.repo_name, branch_name)
1621 1624 if branch_perm and branch_perm == 'branch.none':
1622 1625 msg = _('Target branch `{}` changes rejected by rule {}.').format(
1623 1626 branch_name, rule)
1624 1627 merge_check.push_error('error', msg, cls.PERM_CHECK, auth_user.username)
1625 1628 if fail_early:
1626 1629 return merge_check
1627 1630
1628 1631 # review status, must be always present
1629 1632 review_status = pull_request.calculated_review_status()
1630 1633 merge_check.review_status = review_status
1631 1634
1632 1635 status_approved = review_status == ChangesetStatus.STATUS_APPROVED
1633 1636 if not status_approved:
1634 1637 log.debug("MergeCheck: cannot merge, approval is pending.")
1635 1638
1636 1639 msg = _('Pull request reviewer approval is pending.')
1637 1640
1638 1641 merge_check.push_error('warning', msg, cls.REVIEW_CHECK, review_status)
1639 1642
1640 1643 if fail_early:
1641 1644 return merge_check
1642 1645
1643 1646 # left over TODOs
1644 1647 todos = CommentsModel().get_pull_request_unresolved_todos(pull_request)
1645 1648 if todos:
1646 1649 log.debug("MergeCheck: cannot merge, {} "
1647 1650 "unresolved TODOs left.".format(len(todos)))
1648 1651
1649 1652 if len(todos) == 1:
1650 1653 msg = _('Cannot merge, {} TODO still not resolved.').format(
1651 1654 len(todos))
1652 1655 else:
1653 1656 msg = _('Cannot merge, {} TODOs still not resolved.').format(
1654 1657 len(todos))
1655 1658
1656 1659 merge_check.push_error('warning', msg, cls.TODO_CHECK, todos)
1657 1660
1658 1661 if fail_early:
1659 1662 return merge_check
1660 1663
1661 1664 # merge possible, here is the filesystem simulation + shadow repo
1662 1665 merge_status, msg = PullRequestModel().merge_status(
1663 1666 pull_request, translator=translator,
1664 1667 force_shadow_repo_refresh=force_shadow_repo_refresh)
1665 1668 merge_check.merge_possible = merge_status
1666 1669 merge_check.merge_msg = msg
1667 1670 if not merge_status:
1668 1671 log.debug("MergeCheck: cannot merge, pull request merge not possible.")
1669 1672 merge_check.push_error('warning', msg, cls.MERGE_CHECK, None)
1670 1673
1671 1674 if fail_early:
1672 1675 return merge_check
1673 1676
1674 1677 log.debug('MergeCheck: is failed: %s', merge_check.failed)
1675 1678 return merge_check
1676 1679
1677 1680 @classmethod
1678 1681 def get_merge_conditions(cls, pull_request, translator):
1679 1682 _ = translator
1680 1683 merge_details = {}
1681 1684
1682 1685 model = PullRequestModel()
1683 1686 use_rebase = model._use_rebase_for_merging(pull_request)
1684 1687
1685 1688 if use_rebase:
1686 1689 merge_details['merge_strategy'] = dict(
1687 1690 details={},
1688 1691 message=_('Merge strategy: rebase')
1689 1692 )
1690 1693 else:
1691 1694 merge_details['merge_strategy'] = dict(
1692 1695 details={},
1693 1696 message=_('Merge strategy: explicit merge commit')
1694 1697 )
1695 1698
1696 1699 close_branch = model._close_branch_before_merging(pull_request)
1697 1700 if close_branch:
1698 1701 repo_type = pull_request.target_repo.repo_type
1699 1702 close_msg = ''
1700 1703 if repo_type == 'hg':
1701 1704 close_msg = _('Source branch will be closed after merge.')
1702 1705 elif repo_type == 'git':
1703 1706 close_msg = _('Source branch will be deleted after merge.')
1704 1707
1705 1708 merge_details['close_branch'] = dict(
1706 1709 details={},
1707 1710 message=close_msg
1708 1711 )
1709 1712
1710 1713 return merge_details
1711 1714
1712 1715
1713 1716 ChangeTuple = collections.namedtuple(
1714 1717 'ChangeTuple', ['added', 'common', 'removed', 'total'])
1715 1718
1716 1719 FileChangeTuple = collections.namedtuple(
1717 1720 'FileChangeTuple', ['added', 'modified', 'removed'])
@@ -1,78 +1,81 b''
1 1
2 2 <div class="pull-request-wrap">
3 3
4 4 % if c.pr_merge_possible:
5 5 <h2 class="merge-status">
6 6 <span class="merge-icon success"><i class="icon-ok"></i></span>
7 7 ${_('This pull request can be merged automatically.')}
8 8 </h2>
9 9 % else:
10 10 <h2 class="merge-status">
11 11 <span class="merge-icon warning"><i class="icon-false"></i></span>
12 12 ${_('Merge is not currently possible because of below failed checks.')}
13 13 </h2>
14 14 % endif
15 15
16 16 % if c.pr_merge_errors.items():
17 17 <ul>
18 18 % for pr_check_key, pr_check_details in c.pr_merge_errors.items():
19 19 <% pr_check_type = pr_check_details['error_type'] %>
20 20 <li>
21 21 <span class="merge-message ${pr_check_type}" data-role="merge-message">
22 22 - ${pr_check_details['message']}
23 23 % if pr_check_key == 'todo':
24 24 % for co in pr_check_details['details']:
25 25 <a class="permalink" href="#comment-${co.comment_id}" onclick="Rhodecode.comments.scrollToComment($('#comment-${co.comment_id}'), 0, ${h.json.dumps(co.outdated)})"> #${co.comment_id}</a>${'' if loop.last else ','}
26 26 % endfor
27 27 % endif
28 28 </span>
29 29 </li>
30 30 % endfor
31 <li>
32 Try <a href="${h.current_route_path(request, force_refresh=1)}">forced recheck</a> of the merge workspace in case current status seems wrong.
33 </li>
31 34 </ul>
32 35 % endif
33 36
34 37 <div class="pull-request-merge-actions">
35 38 % if c.allowed_to_merge:
36 39 ## Merge info, show only if all errors are taken care of
37 40 % if not c.pr_merge_errors and c.pr_merge_info:
38 41 <div class="pull-request-merge-info">
39 42 <ul>
40 43 % for pr_merge_key, pr_merge_details in c.pr_merge_info.items():
41 44 <li>
42 45 - ${pr_merge_details['message']}
43 46 </li>
44 47 % endfor
45 48 </ul>
46 49 </div>
47 50 % endif
48 51
49 52 <div>
50 53 ${h.secure_form(h.route_path('pullrequest_merge', repo_name=c.repo_name, pull_request_id=c.pull_request.pull_request_id), id='merge_pull_request_form', request=request)}
51 54 <% merge_disabled = ' disabled' if c.pr_merge_possible is False else '' %>
52 55 <a class="btn" href="#" onclick="refreshMergeChecks(); return false;">${_('refresh checks')}</a>
53 56 <input type="submit" id="merge_pull_request" value="${_('Merge Pull Request')}" class="btn${merge_disabled}"${merge_disabled}>
54 57 ${h.end_form()}
55 58 </div>
56 59 % elif c.rhodecode_user.username != h.DEFAULT_USER:
57 60 <a class="btn" href="#" onclick="refreshMergeChecks(); return false;">${_('refresh checks')}</a>
58 61 <input type="submit" value="${_('Merge Pull Request')}" class="btn disabled" disabled="disabled" title="${_('You are not allowed to merge this pull request.')}">
59 62 % else:
60 63 <input type="submit" value="${_('Login to Merge this Pull Request')}" class="btn disabled" disabled="disabled">
61 64 % endif
62 65 </div>
63 66
64 67 % if c.allowed_to_close:
65 68 ## close PR action, injected later next to COMMENT button
66 69 <div id="close-pull-request-action" style="display: none">
67 70 % if c.pull_request_review_status == c.REVIEW_STATUS_APPROVED:
68 71 <a class="btn btn-approved-status" href="#close-as-approved" onclick="closePullRequest('${c.REVIEW_STATUS_APPROVED}'); return false;">
69 72 ${_('Close with status {}').format(h.commit_status_lbl(c.REVIEW_STATUS_APPROVED))}
70 73 </a>
71 74 % else:
72 75 <a class="btn btn-rejected-status" href="#close-as-rejected" onclick="closePullRequest('${c.REVIEW_STATUS_REJECTED}'); return false;">
73 76 ${_('Close with status {}').format(h.commit_status_lbl(c.REVIEW_STATUS_REJECTED))}
74 77 </a>
75 78 % endif
76 79 </div>
77 80 % endif
78 81 </div>
General Comments 0
You need to be logged in to leave comments. Login now