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

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

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