##// END OF EJS Templates
comments: added immutable parameter to forbid editing/deleting certain comments
marcink -
r4327:da58ea77 default
parent child Browse files
Show More
@@ -0,0 +1,43 b''
1 # -*- coding: utf-8 -*-
2
3 import logging
4 from sqlalchemy import *
5
6 from alembic.migration import MigrationContext
7 from alembic.operations import Operations
8 from sqlalchemy import BigInteger
9
10 from rhodecode.lib.dbmigrate.versions import _reset_base
11 from rhodecode.model import init_model_encryption
12
13
14 log = logging.getLogger(__name__)
15
16
17 def upgrade(migrate_engine):
18 """
19 Upgrade operations go here.
20 Don't create your own engine; bind migrate_engine to your metadata
21 """
22 _reset_base(migrate_engine)
23 from rhodecode.lib.dbmigrate.schema import db_4_18_0_1 as db
24
25 init_model_encryption(db)
26
27 context = MigrationContext.configure(migrate_engine.connect())
28 op = Operations(context)
29
30 comments = db.ChangesetComment.__table__
31
32 with op.batch_alter_table(comments.name) as batch_op:
33 new_column = Column('immutable_state', Unicode(128), nullable=True)
34 batch_op.add_column(new_column)
35
36
37 def downgrade(migrate_engine):
38 meta = MetaData()
39 meta.bind = migrate_engine
40
41
42 def fixups(models, _SESSION):
43 pass
@@ -1,60 +1,60 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2020 RhodeCode GmbH
3 # Copyright (C) 2010-2020 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 os
21 import os
22 from collections import OrderedDict
22 from collections import OrderedDict
23
23
24 import sys
24 import sys
25 import platform
25 import platform
26
26
27 VERSION = tuple(open(os.path.join(
27 VERSION = tuple(open(os.path.join(
28 os.path.dirname(__file__), 'VERSION')).read().split('.'))
28 os.path.dirname(__file__), 'VERSION')).read().split('.'))
29
29
30 BACKENDS = OrderedDict()
30 BACKENDS = OrderedDict()
31
31
32 BACKENDS['hg'] = 'Mercurial repository'
32 BACKENDS['hg'] = 'Mercurial repository'
33 BACKENDS['git'] = 'Git repository'
33 BACKENDS['git'] = 'Git repository'
34 BACKENDS['svn'] = 'Subversion repository'
34 BACKENDS['svn'] = 'Subversion repository'
35
35
36
36
37 CELERY_ENABLED = False
37 CELERY_ENABLED = False
38 CELERY_EAGER = False
38 CELERY_EAGER = False
39
39
40 # link to config for pyramid
40 # link to config for pyramid
41 CONFIG = {}
41 CONFIG = {}
42
42
43 # Populated with the settings dictionary from application init in
43 # Populated with the settings dictionary from application init in
44 # rhodecode.conf.environment.load_pyramid_environment
44 # rhodecode.conf.environment.load_pyramid_environment
45 PYRAMID_SETTINGS = {}
45 PYRAMID_SETTINGS = {}
46
46
47 # Linked module for extensions
47 # Linked module for extensions
48 EXTENSIONS = {}
48 EXTENSIONS = {}
49
49
50 __version__ = ('.'.join((str(each) for each in VERSION[:3])))
50 __version__ = ('.'.join((str(each) for each in VERSION[:3])))
51 __dbversion__ = 105 # defines current db version for migrations
51 __dbversion__ = 106 # defines current db version for migrations
52 __platform__ = platform.system()
52 __platform__ = platform.system()
53 __license__ = 'AGPLv3, and Commercial License'
53 __license__ = 'AGPLv3, and Commercial License'
54 __author__ = 'RhodeCode GmbH'
54 __author__ = 'RhodeCode GmbH'
55 __url__ = 'https://code.rhodecode.com'
55 __url__ = 'https://code.rhodecode.com'
56
56
57 is_windows = __platform__ in ['Windows']
57 is_windows = __platform__ in ['Windows']
58 is_unix = not is_windows
58 is_unix = not is_windows
59 is_test = False
59 is_test = False
60 disable_error_handler = False
60 disable_error_handler = False
@@ -1,402 +1,402 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2020 RhodeCode GmbH
3 # Copyright (C) 2016-2020 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 os
21 import os
22 import logging
22 import logging
23 import datetime
23 import datetime
24
24
25 from pyramid.view import view_config
25 from pyramid.view import view_config
26 from pyramid.renderers import render_to_response
26 from pyramid.renderers import render_to_response
27 from rhodecode.apps._base import BaseAppView
27 from rhodecode.apps._base import BaseAppView
28 from rhodecode.lib.celerylib import run_task, tasks
28 from rhodecode.lib.celerylib import run_task, tasks
29 from rhodecode.lib.utils2 import AttributeDict
29 from rhodecode.lib.utils2 import AttributeDict
30 from rhodecode.model.db import User
30 from rhodecode.model.db import User
31 from rhodecode.model.notification import EmailNotificationModel
31 from rhodecode.model.notification import EmailNotificationModel
32
32
33 log = logging.getLogger(__name__)
33 log = logging.getLogger(__name__)
34
34
35
35
36 class DebugStyleView(BaseAppView):
36 class DebugStyleView(BaseAppView):
37 def load_default_context(self):
37 def load_default_context(self):
38 c = self._get_local_tmpl_context()
38 c = self._get_local_tmpl_context()
39
39
40 return c
40 return c
41
41
42 @view_config(
42 @view_config(
43 route_name='debug_style_home', request_method='GET',
43 route_name='debug_style_home', request_method='GET',
44 renderer=None)
44 renderer=None)
45 def index(self):
45 def index(self):
46 c = self.load_default_context()
46 c = self.load_default_context()
47 c.active = 'index'
47 c.active = 'index'
48
48
49 return render_to_response(
49 return render_to_response(
50 'debug_style/index.html', self._get_template_context(c),
50 'debug_style/index.html', self._get_template_context(c),
51 request=self.request)
51 request=self.request)
52
52
53 @view_config(
53 @view_config(
54 route_name='debug_style_email', request_method='GET',
54 route_name='debug_style_email', request_method='GET',
55 renderer=None)
55 renderer=None)
56 @view_config(
56 @view_config(
57 route_name='debug_style_email_plain_rendered', request_method='GET',
57 route_name='debug_style_email_plain_rendered', request_method='GET',
58 renderer=None)
58 renderer=None)
59 def render_email(self):
59 def render_email(self):
60 c = self.load_default_context()
60 c = self.load_default_context()
61 email_id = self.request.matchdict['email_id']
61 email_id = self.request.matchdict['email_id']
62 c.active = 'emails'
62 c.active = 'emails'
63
63
64 pr = AttributeDict(
64 pr = AttributeDict(
65 pull_request_id=123,
65 pull_request_id=123,
66 title='digital_ocean: fix redis, elastic search start on boot, '
66 title='digital_ocean: fix redis, elastic search start on boot, '
67 'fix fd limits on supervisor, set postgres 11 version',
67 'fix fd limits on supervisor, set postgres 11 version',
68 description='''
68 description='''
69 Check if we should use full-topic or mini-topic.
69 Check if we should use full-topic or mini-topic.
70
70
71 - full topic produces some problems with merge states etc
71 - full topic produces some problems with merge states etc
72 - server-mini-topic needs probably tweeks.
72 - server-mini-topic needs probably tweeks.
73 ''',
73 ''',
74 repo_name='foobar',
74 repo_name='foobar',
75 source_ref_parts=AttributeDict(type='branch', name='fix-ticket-2000'),
75 source_ref_parts=AttributeDict(type='branch', name='fix-ticket-2000'),
76 target_ref_parts=AttributeDict(type='branch', name='master'),
76 target_ref_parts=AttributeDict(type='branch', name='master'),
77 )
77 )
78 target_repo = AttributeDict(repo_name='repo_group/target_repo')
78 target_repo = AttributeDict(repo_name='repo_group/target_repo')
79 source_repo = AttributeDict(repo_name='repo_group/source_repo')
79 source_repo = AttributeDict(repo_name='repo_group/source_repo')
80 user = User.get_by_username(self.request.GET.get('user')) or self._rhodecode_db_user
80 user = User.get_by_username(self.request.GET.get('user')) or self._rhodecode_db_user
81 # file/commit changes for PR update
81 # file/commit changes for PR update
82 commit_changes = AttributeDict({
82 commit_changes = AttributeDict({
83 'added': ['aaaaaaabbbbb', 'cccccccddddddd'],
83 'added': ['aaaaaaabbbbb', 'cccccccddddddd'],
84 'removed': ['eeeeeeeeeee'],
84 'removed': ['eeeeeeeeeee'],
85 })
85 })
86 file_changes = AttributeDict({
86 file_changes = AttributeDict({
87 'added': ['a/file1.md', 'file2.py'],
87 'added': ['a/file1.md', 'file2.py'],
88 'modified': ['b/modified_file.rst'],
88 'modified': ['b/modified_file.rst'],
89 'removed': ['.idea'],
89 'removed': ['.idea'],
90 })
90 })
91
91
92 exc_traceback = {
92 exc_traceback = {
93 'exc_utc_date': '2020-03-26T12:54:50.683281',
93 'exc_utc_date': '2020-03-26T12:54:50.683281',
94 'exc_id': 139638856342656,
94 'exc_id': 139638856342656,
95 'exc_timestamp': '1585227290.683288',
95 'exc_timestamp': '1585227290.683288',
96 'version': 'v1',
96 'version': 'v1',
97 'exc_message': 'Traceback (most recent call last):\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/tweens.py", line 41, in excview_tween\n response = handler(request)\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/router.py", line 148, in handle_request\n registry, request, context, context_iface, view_name\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/view.py", line 667, in _call_view\n response = view_callable(context, request)\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/config/views.py", line 188, in attr_view\n return view(context, request)\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/config/views.py", line 214, in predicate_wrapper\n return view(context, request)\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/viewderivers.py", line 401, in viewresult_to_response\n result = view(context, request)\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/viewderivers.py", line 132, in _class_view\n response = getattr(inst, attr)()\n File "/mnt/hgfs/marcink/workspace/rhodecode-enterprise-ce/rhodecode/apps/debug_style/views.py", line 355, in render_email\n template_type, **email_kwargs.get(email_id, {}))\n File "/mnt/hgfs/marcink/workspace/rhodecode-enterprise-ce/rhodecode/model/notification.py", line 402, in render_email\n body = email_template.render(None, **_kwargs)\n File "/mnt/hgfs/marcink/workspace/rhodecode-enterprise-ce/rhodecode/lib/partial_renderer.py", line 95, in render\n return self._render_with_exc(tmpl, args, kwargs)\n File "/mnt/hgfs/marcink/workspace/rhodecode-enterprise-ce/rhodecode/lib/partial_renderer.py", line 79, in _render_with_exc\n return render_func.render(*args, **kwargs)\n File "/nix/store/dakh34sxz4yfr435c0cwjz0sd6hnd5g3-python2.7-mako-1.1.0/lib/python2.7/site-packages/mako/template.py", line 476, in render\n return runtime._render(self, self.callable_, args, data)\n File "/nix/store/dakh34sxz4yfr435c0cwjz0sd6hnd5g3-python2.7-mako-1.1.0/lib/python2.7/site-packages/mako/runtime.py", line 883, in _render\n **_kwargs_for_callable(callable_, data)\n File "/nix/store/dakh34sxz4yfr435c0cwjz0sd6hnd5g3-python2.7-mako-1.1.0/lib/python2.7/site-packages/mako/runtime.py", line 920, in _render_context\n _exec_template(inherit, lclcontext, args=args, kwargs=kwargs)\n File "/nix/store/dakh34sxz4yfr435c0cwjz0sd6hnd5g3-python2.7-mako-1.1.0/lib/python2.7/site-packages/mako/runtime.py", line 947, in _exec_template\n callable_(context, *args, **kwargs)\n File "rhodecode_templates_email_templates_base_mako", line 63, in render_body\n File "rhodecode_templates_email_templates_exception_tracker_mako", line 43, in render_body\nAttributeError: \'str\' object has no attribute \'get\'\n',
97 'exc_message': 'Traceback (most recent call last):\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/tweens.py", line 41, in excview_tween\n response = handler(request)\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/router.py", line 148, in handle_request\n registry, request, context, context_iface, view_name\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/view.py", line 667, in _call_view\n response = view_callable(context, request)\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/config/views.py", line 188, in attr_view\n return view(context, request)\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/config/views.py", line 214, in predicate_wrapper\n return view(context, request)\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/viewderivers.py", line 401, in viewresult_to_response\n result = view(context, request)\n File "/nix/store/s43k2r9rysfbzmsjdqnxgzvvb7zjhkxb-python2.7-pyramid-1.10.4/lib/python2.7/site-packages/pyramid/viewderivers.py", line 132, in _class_view\n response = getattr(inst, attr)()\n File "/mnt/hgfs/marcink/workspace/rhodecode-enterprise-ce/rhodecode/apps/debug_style/views.py", line 355, in render_email\n template_type, **email_kwargs.get(email_id, {}))\n File "/mnt/hgfs/marcink/workspace/rhodecode-enterprise-ce/rhodecode/model/notification.py", line 402, in render_email\n body = email_template.render(None, **_kwargs)\n File "/mnt/hgfs/marcink/workspace/rhodecode-enterprise-ce/rhodecode/lib/partial_renderer.py", line 95, in render\n return self._render_with_exc(tmpl, args, kwargs)\n File "/mnt/hgfs/marcink/workspace/rhodecode-enterprise-ce/rhodecode/lib/partial_renderer.py", line 79, in _render_with_exc\n return render_func.render(*args, **kwargs)\n File "/nix/store/dakh34sxz4yfr435c0cwjz0sd6hnd5g3-python2.7-mako-1.1.0/lib/python2.7/site-packages/mako/template.py", line 476, in render\n return runtime._render(self, self.callable_, args, data)\n File "/nix/store/dakh34sxz4yfr435c0cwjz0sd6hnd5g3-python2.7-mako-1.1.0/lib/python2.7/site-packages/mako/runtime.py", line 883, in _render\n **_kwargs_for_callable(callable_, data)\n File "/nix/store/dakh34sxz4yfr435c0cwjz0sd6hnd5g3-python2.7-mako-1.1.0/lib/python2.7/site-packages/mako/runtime.py", line 920, in _render_context\n _exec_template(inherit, lclcontext, args=args, kwargs=kwargs)\n File "/nix/store/dakh34sxz4yfr435c0cwjz0sd6hnd5g3-python2.7-mako-1.1.0/lib/python2.7/site-packages/mako/runtime.py", line 947, in _exec_template\n callable_(context, *args, **kwargs)\n File "rhodecode_templates_email_templates_base_mako", line 63, in render_body\n File "rhodecode_templates_email_templates_exception_tracker_mako", line 43, in render_body\nAttributeError: \'str\' object has no attribute \'get\'\n',
98 'exc_type': 'AttributeError'
98 'exc_type': 'AttributeError'
99 }
99 }
100 email_kwargs = {
100 email_kwargs = {
101 'test': {},
101 'test': {},
102 'message': {
102 'message': {
103 'body': 'message body !'
103 'body': 'message body !'
104 },
104 },
105 'email_test': {
105 'email_test': {
106 'user': user,
106 'user': user,
107 'date': datetime.datetime.now(),
107 'date': datetime.datetime.now(),
108 },
108 },
109 'exception': {
109 'exception': {
110 'email_prefix': '[RHODECODE ERROR]',
110 'email_prefix': '[RHODECODE ERROR]',
111 'exc_id': exc_traceback['exc_id'],
111 'exc_id': exc_traceback['exc_id'],
112 'exc_url': 'http://server-url/{}'.format(exc_traceback['exc_id']),
112 'exc_url': 'http://server-url/{}'.format(exc_traceback['exc_id']),
113 'exc_type_name': 'NameError',
113 'exc_type_name': 'NameError',
114 'exc_traceback': exc_traceback,
114 'exc_traceback': exc_traceback,
115 },
115 },
116 'password_reset': {
116 'password_reset': {
117 'password_reset_url': 'http://example.com/reset-rhodecode-password/token',
117 'password_reset_url': 'http://example.com/reset-rhodecode-password/token',
118
118
119 'user': user,
119 'user': user,
120 'date': datetime.datetime.now(),
120 'date': datetime.datetime.now(),
121 'email': 'test@rhodecode.com',
121 'email': 'test@rhodecode.com',
122 'first_admin_email': User.get_first_super_admin().email
122 'first_admin_email': User.get_first_super_admin().email
123 },
123 },
124 'password_reset_confirmation': {
124 'password_reset_confirmation': {
125 'new_password': 'new-password-example',
125 'new_password': 'new-password-example',
126 'user': user,
126 'user': user,
127 'date': datetime.datetime.now(),
127 'date': datetime.datetime.now(),
128 'email': 'test@rhodecode.com',
128 'email': 'test@rhodecode.com',
129 'first_admin_email': User.get_first_super_admin().email
129 'first_admin_email': User.get_first_super_admin().email
130 },
130 },
131 'registration': {
131 'registration': {
132 'user': user,
132 'user': user,
133 'date': datetime.datetime.now(),
133 'date': datetime.datetime.now(),
134 },
134 },
135
135
136 'pull_request_comment': {
136 'pull_request_comment': {
137 'user': user,
137 'user': user,
138
138
139 'status_change': None,
139 'status_change': None,
140 'status_change_type': None,
140 'status_change_type': None,
141
141
142 'pull_request': pr,
142 'pull_request': pr,
143 'pull_request_commits': [],
143 'pull_request_commits': [],
144
144
145 'pull_request_target_repo': target_repo,
145 'pull_request_target_repo': target_repo,
146 'pull_request_target_repo_url': 'http://target-repo/url',
146 'pull_request_target_repo_url': 'http://target-repo/url',
147
147
148 'pull_request_source_repo': source_repo,
148 'pull_request_source_repo': source_repo,
149 'pull_request_source_repo_url': 'http://source-repo/url',
149 'pull_request_source_repo_url': 'http://source-repo/url',
150
150
151 'pull_request_url': 'http://localhost/pr1',
151 'pull_request_url': 'http://localhost/pr1',
152 'pr_comment_url': 'http://comment-url',
152 'pr_comment_url': 'http://comment-url',
153 'pr_comment_reply_url': 'http://comment-url#reply',
153 'pr_comment_reply_url': 'http://comment-url#reply',
154
154
155 'comment_file': None,
155 'comment_file': None,
156 'comment_line': None,
156 'comment_line': None,
157 'comment_type': 'note',
157 'comment_type': 'note',
158 'comment_body': 'This is my comment body. *I like !*',
158 'comment_body': 'This is my comment body. *I like !*',
159 'comment_id': 2048,
159 'comment_id': 2048,
160 'renderer_type': 'markdown',
160 'renderer_type': 'markdown',
161 'mention': True,
161 'mention': True,
162
162
163 },
163 },
164 'pull_request_comment+status': {
164 'pull_request_comment+status': {
165 'user': user,
165 'user': user,
166
166
167 'status_change': 'approved',
167 'status_change': 'approved',
168 'status_change_type': 'approved',
168 'status_change_type': 'approved',
169
169
170 'pull_request': pr,
170 'pull_request': pr,
171 'pull_request_commits': [],
171 'pull_request_commits': [],
172
172
173 'pull_request_target_repo': target_repo,
173 'pull_request_target_repo': target_repo,
174 'pull_request_target_repo_url': 'http://target-repo/url',
174 'pull_request_target_repo_url': 'http://target-repo/url',
175
175
176 'pull_request_source_repo': source_repo,
176 'pull_request_source_repo': source_repo,
177 'pull_request_source_repo_url': 'http://source-repo/url',
177 'pull_request_source_repo_url': 'http://source-repo/url',
178
178
179 'pull_request_url': 'http://localhost/pr1',
179 'pull_request_url': 'http://localhost/pr1',
180 'pr_comment_url': 'http://comment-url',
180 'pr_comment_url': 'http://comment-url',
181 'pr_comment_reply_url': 'http://comment-url#reply',
181 'pr_comment_reply_url': 'http://comment-url#reply',
182
182
183 'comment_type': 'todo',
183 'comment_type': 'todo',
184 'comment_file': None,
184 'comment_file': None,
185 'comment_line': None,
185 'comment_line': None,
186 'comment_body': '''
186 'comment_body': '''
187 I think something like this would be better
187 I think something like this would be better
188
188
189 ```py
189 ```py
190
190
191 def db():
191 def db():
192 global connection
192 global connection
193 return connection
193 return connection
194
194
195 ```
195 ```
196
196
197 ''',
197 ''',
198 'comment_id': 2048,
198 'comment_id': 2048,
199 'renderer_type': 'markdown',
199 'renderer_type': 'markdown',
200 'mention': True,
200 'mention': True,
201
201
202 },
202 },
203 'pull_request_comment+file': {
203 'pull_request_comment+file': {
204 'user': user,
204 'user': user,
205
205
206 'status_change': None,
206 'status_change': None,
207 'status_change_type': None,
207 'status_change_type': None,
208
208
209 'pull_request': pr,
209 'pull_request': pr,
210 'pull_request_commits': [],
210 'pull_request_commits': [],
211
211
212 'pull_request_target_repo': target_repo,
212 'pull_request_target_repo': target_repo,
213 'pull_request_target_repo_url': 'http://target-repo/url',
213 'pull_request_target_repo_url': 'http://target-repo/url',
214
214
215 'pull_request_source_repo': source_repo,
215 'pull_request_source_repo': source_repo,
216 'pull_request_source_repo_url': 'http://source-repo/url',
216 'pull_request_source_repo_url': 'http://source-repo/url',
217
217
218 'pull_request_url': 'http://localhost/pr1',
218 'pull_request_url': 'http://localhost/pr1',
219
219
220 'pr_comment_url': 'http://comment-url',
220 'pr_comment_url': 'http://comment-url',
221 'pr_comment_reply_url': 'http://comment-url#reply',
221 'pr_comment_reply_url': 'http://comment-url#reply',
222
222
223 'comment_file': 'rhodecode/model/db.py',
223 'comment_file': 'rhodecode/model/get_flow_commits',
224 'comment_line': 'o1210',
224 'comment_line': 'o1210',
225 'comment_type': 'todo',
225 'comment_type': 'todo',
226 'comment_body': '''
226 'comment_body': '''
227 I like this !
227 I like this !
228
228
229 But please check this code::
229 But please check this code::
230
230
231 def main():
231 def main():
232 print 'ok'
232 print 'ok'
233
233
234 This should work better !
234 This should work better !
235 ''',
235 ''',
236 'comment_id': 2048,
236 'comment_id': 2048,
237 'renderer_type': 'rst',
237 'renderer_type': 'rst',
238 'mention': True,
238 'mention': True,
239
239
240 },
240 },
241
241
242 'pull_request_update': {
242 'pull_request_update': {
243 'updating_user': user,
243 'updating_user': user,
244
244
245 'status_change': None,
245 'status_change': None,
246 'status_change_type': None,
246 'status_change_type': None,
247
247
248 'pull_request': pr,
248 'pull_request': pr,
249 'pull_request_commits': [],
249 'pull_request_commits': [],
250
250
251 'pull_request_target_repo': target_repo,
251 'pull_request_target_repo': target_repo,
252 'pull_request_target_repo_url': 'http://target-repo/url',
252 'pull_request_target_repo_url': 'http://target-repo/url',
253
253
254 'pull_request_source_repo': source_repo,
254 'pull_request_source_repo': source_repo,
255 'pull_request_source_repo_url': 'http://source-repo/url',
255 'pull_request_source_repo_url': 'http://source-repo/url',
256
256
257 'pull_request_url': 'http://localhost/pr1',
257 'pull_request_url': 'http://localhost/pr1',
258
258
259 # update comment links
259 # update comment links
260 'pr_comment_url': 'http://comment-url',
260 'pr_comment_url': 'http://comment-url',
261 'pr_comment_reply_url': 'http://comment-url#reply',
261 'pr_comment_reply_url': 'http://comment-url#reply',
262 'ancestor_commit_id': 'f39bd443',
262 'ancestor_commit_id': 'f39bd443',
263 'added_commits': commit_changes.added,
263 'added_commits': commit_changes.added,
264 'removed_commits': commit_changes.removed,
264 'removed_commits': commit_changes.removed,
265 'changed_files': (file_changes.added + file_changes.modified + file_changes.removed),
265 'changed_files': (file_changes.added + file_changes.modified + file_changes.removed),
266 'added_files': file_changes.added,
266 'added_files': file_changes.added,
267 'modified_files': file_changes.modified,
267 'modified_files': file_changes.modified,
268 'removed_files': file_changes.removed,
268 'removed_files': file_changes.removed,
269 },
269 },
270
270
271 'cs_comment': {
271 'cs_comment': {
272 'user': user,
272 'user': user,
273 'commit': AttributeDict(idx=123, raw_id='a'*40, message='Commit message'),
273 'commit': AttributeDict(idx=123, raw_id='a'*40, message='Commit message'),
274 'status_change': None,
274 'status_change': None,
275 'status_change_type': None,
275 'status_change_type': None,
276
276
277 'commit_target_repo_url': 'http://foo.example.com/#comment1',
277 'commit_target_repo_url': 'http://foo.example.com/#comment1',
278 'repo_name': 'test-repo',
278 'repo_name': 'test-repo',
279 'comment_type': 'note',
279 'comment_type': 'note',
280 'comment_file': None,
280 'comment_file': None,
281 'comment_line': None,
281 'comment_line': None,
282 'commit_comment_url': 'http://comment-url',
282 'commit_comment_url': 'http://comment-url',
283 'commit_comment_reply_url': 'http://comment-url#reply',
283 'commit_comment_reply_url': 'http://comment-url#reply',
284 'comment_body': 'This is my comment body. *I like !*',
284 'comment_body': 'This is my comment body. *I like !*',
285 'comment_id': 2048,
285 'comment_id': 2048,
286 'renderer_type': 'markdown',
286 'renderer_type': 'markdown',
287 'mention': True,
287 'mention': True,
288 },
288 },
289 'cs_comment+status': {
289 'cs_comment+status': {
290 'user': user,
290 'user': user,
291 'commit': AttributeDict(idx=123, raw_id='a' * 40, message='Commit message'),
291 'commit': AttributeDict(idx=123, raw_id='a' * 40, message='Commit message'),
292 'status_change': 'approved',
292 'status_change': 'approved',
293 'status_change_type': 'approved',
293 'status_change_type': 'approved',
294
294
295 'commit_target_repo_url': 'http://foo.example.com/#comment1',
295 'commit_target_repo_url': 'http://foo.example.com/#comment1',
296 'repo_name': 'test-repo',
296 'repo_name': 'test-repo',
297 'comment_type': 'note',
297 'comment_type': 'note',
298 'comment_file': None,
298 'comment_file': None,
299 'comment_line': None,
299 'comment_line': None,
300 'commit_comment_url': 'http://comment-url',
300 'commit_comment_url': 'http://comment-url',
301 'commit_comment_reply_url': 'http://comment-url#reply',
301 'commit_comment_reply_url': 'http://comment-url#reply',
302 'comment_body': '''
302 'comment_body': '''
303 Hello **world**
303 Hello **world**
304
304
305 This is a multiline comment :)
305 This is a multiline comment :)
306
306
307 - list
307 - list
308 - list2
308 - list2
309 ''',
309 ''',
310 'comment_id': 2048,
310 'comment_id': 2048,
311 'renderer_type': 'markdown',
311 'renderer_type': 'markdown',
312 'mention': True,
312 'mention': True,
313 },
313 },
314 'cs_comment+file': {
314 'cs_comment+file': {
315 'user': user,
315 'user': user,
316 'commit': AttributeDict(idx=123, raw_id='a' * 40, message='Commit message'),
316 'commit': AttributeDict(idx=123, raw_id='a' * 40, message='Commit message'),
317 'status_change': None,
317 'status_change': None,
318 'status_change_type': None,
318 'status_change_type': None,
319
319
320 'commit_target_repo_url': 'http://foo.example.com/#comment1',
320 'commit_target_repo_url': 'http://foo.example.com/#comment1',
321 'repo_name': 'test-repo',
321 'repo_name': 'test-repo',
322
322
323 'comment_type': 'note',
323 'comment_type': 'note',
324 'comment_file': 'test-file.py',
324 'comment_file': 'test-file.py',
325 'comment_line': 'n100',
325 'comment_line': 'n100',
326
326
327 'commit_comment_url': 'http://comment-url',
327 'commit_comment_url': 'http://comment-url',
328 'commit_comment_reply_url': 'http://comment-url#reply',
328 'commit_comment_reply_url': 'http://comment-url#reply',
329 'comment_body': 'This is my comment body. *I like !*',
329 'comment_body': 'This is my comment body. *I like !*',
330 'comment_id': 2048,
330 'comment_id': 2048,
331 'renderer_type': 'markdown',
331 'renderer_type': 'markdown',
332 'mention': True,
332 'mention': True,
333 },
333 },
334
334
335 'pull_request': {
335 'pull_request': {
336 'user': user,
336 'user': user,
337 'pull_request': pr,
337 'pull_request': pr,
338 'pull_request_commits': [
338 'pull_request_commits': [
339 ('472d1df03bf7206e278fcedc6ac92b46b01c4e21', '''\
339 ('472d1df03bf7206e278fcedc6ac92b46b01c4e21', '''\
340 my-account: moved email closer to profile as it's similar data just moved outside.
340 my-account: moved email closer to profile as it's similar data just moved outside.
341 '''),
341 '''),
342 ('cbfa3061b6de2696c7161ed15ba5c6a0045f90a7', '''\
342 ('cbfa3061b6de2696c7161ed15ba5c6a0045f90a7', '''\
343 users: description edit fixes
343 users: description edit fixes
344
344
345 - tests
345 - tests
346 - added metatags info
346 - added metatags info
347 '''),
347 '''),
348 ],
348 ],
349
349
350 'pull_request_target_repo': target_repo,
350 'pull_request_target_repo': target_repo,
351 'pull_request_target_repo_url': 'http://target-repo/url',
351 'pull_request_target_repo_url': 'http://target-repo/url',
352
352
353 'pull_request_source_repo': source_repo,
353 'pull_request_source_repo': source_repo,
354 'pull_request_source_repo_url': 'http://source-repo/url',
354 'pull_request_source_repo_url': 'http://source-repo/url',
355
355
356 'pull_request_url': 'http://code.rhodecode.com/_pull-request/123',
356 'pull_request_url': 'http://code.rhodecode.com/_pull-request/123',
357 }
357 }
358
358
359 }
359 }
360
360
361 template_type = email_id.split('+')[0]
361 template_type = email_id.split('+')[0]
362 (c.subject, c.headers, c.email_body,
362 (c.subject, c.headers, c.email_body,
363 c.email_body_plaintext) = EmailNotificationModel().render_email(
363 c.email_body_plaintext) = EmailNotificationModel().render_email(
364 template_type, **email_kwargs.get(email_id, {}))
364 template_type, **email_kwargs.get(email_id, {}))
365
365
366 test_email = self.request.GET.get('email')
366 test_email = self.request.GET.get('email')
367 if test_email:
367 if test_email:
368 recipients = [test_email]
368 recipients = [test_email]
369 run_task(tasks.send_email, recipients, c.subject,
369 run_task(tasks.send_email, recipients, c.subject,
370 c.email_body_plaintext, c.email_body)
370 c.email_body_plaintext, c.email_body)
371
371
372 if self.request.matched_route.name == 'debug_style_email_plain_rendered':
372 if self.request.matched_route.name == 'debug_style_email_plain_rendered':
373 template = 'debug_style/email_plain_rendered.mako'
373 template = 'debug_style/email_plain_rendered.mako'
374 else:
374 else:
375 template = 'debug_style/email.mako'
375 template = 'debug_style/email.mako'
376 return render_to_response(
376 return render_to_response(
377 template, self._get_template_context(c),
377 template, self._get_template_context(c),
378 request=self.request)
378 request=self.request)
379
379
380 @view_config(
380 @view_config(
381 route_name='debug_style_template', request_method='GET',
381 route_name='debug_style_template', request_method='GET',
382 renderer=None)
382 renderer=None)
383 def template(self):
383 def template(self):
384 t_path = self.request.matchdict['t_path']
384 t_path = self.request.matchdict['t_path']
385 c = self.load_default_context()
385 c = self.load_default_context()
386 c.active = os.path.splitext(t_path)[0]
386 c.active = os.path.splitext(t_path)[0]
387 c.came_from = ''
387 c.came_from = ''
388 c.email_types = {
388 c.email_types = {
389 'cs_comment+file': {},
389 'cs_comment+file': {},
390 'cs_comment+status': {},
390 'cs_comment+status': {},
391
391
392 'pull_request_comment+file': {},
392 'pull_request_comment+file': {},
393 'pull_request_comment+status': {},
393 'pull_request_comment+status': {},
394
394
395 'pull_request_update': {},
395 'pull_request_update': {},
396 }
396 }
397 c.email_types.update(EmailNotificationModel.email_types)
397 c.email_types.update(EmailNotificationModel.email_types)
398
398
399 return render_to_response(
399 return render_to_response(
400 'debug_style/' + t_path, self._get_template_context(c),
400 'debug_style/' + t_path, self._get_template_context(c),
401 request=self.request)
401 request=self.request)
402
402
@@ -1,320 +1,348 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2020 RhodeCode GmbH
3 # Copyright (C) 2010-2020 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.tests import TestController
23 from rhodecode.tests import TestController
24
24
25 from rhodecode.model.db import (
25 from rhodecode.model.db import ChangesetComment, Notification
26 ChangesetComment, Notification, UserNotification)
27 from rhodecode.model.meta import Session
26 from rhodecode.model.meta import Session
28 from rhodecode.lib import helpers as h
27 from rhodecode.lib import helpers as h
29
28
30
29
31 def route_path(name, params=None, **kwargs):
30 def route_path(name, params=None, **kwargs):
32 import urllib
31 import urllib
33
32
34 base_url = {
33 base_url = {
35 'repo_commit': '/{repo_name}/changeset/{commit_id}',
34 'repo_commit': '/{repo_name}/changeset/{commit_id}',
36 'repo_commit_comment_create': '/{repo_name}/changeset/{commit_id}/comment/create',
35 'repo_commit_comment_create': '/{repo_name}/changeset/{commit_id}/comment/create',
37 'repo_commit_comment_preview': '/{repo_name}/changeset/{commit_id}/comment/preview',
36 'repo_commit_comment_preview': '/{repo_name}/changeset/{commit_id}/comment/preview',
38 'repo_commit_comment_delete': '/{repo_name}/changeset/{commit_id}/comment/{comment_id}/delete',
37 'repo_commit_comment_delete': '/{repo_name}/changeset/{commit_id}/comment/{comment_id}/delete',
39 }[name].format(**kwargs)
38 }[name].format(**kwargs)
40
39
41 if params:
40 if params:
42 base_url = '{}?{}'.format(base_url, urllib.urlencode(params))
41 base_url = '{}?{}'.format(base_url, urllib.urlencode(params))
43 return base_url
42 return base_url
44
43
45
44
46 @pytest.mark.backends("git", "hg", "svn")
45 @pytest.mark.backends("git", "hg", "svn")
47 class TestRepoCommitCommentsView(TestController):
46 class TestRepoCommitCommentsView(TestController):
48
47
49 @pytest.fixture(autouse=True)
48 @pytest.fixture(autouse=True)
50 def prepare(self, request, baseapp):
49 def prepare(self, request, baseapp):
51 for x in ChangesetComment.query().all():
50 for x in ChangesetComment.query().all():
52 Session().delete(x)
51 Session().delete(x)
53 Session().commit()
52 Session().commit()
54
53
55 for x in Notification.query().all():
54 for x in Notification.query().all():
56 Session().delete(x)
55 Session().delete(x)
57 Session().commit()
56 Session().commit()
58
57
59 request.addfinalizer(self.cleanup)
58 request.addfinalizer(self.cleanup)
60
59
61 def cleanup(self):
60 def cleanup(self):
62 for x in ChangesetComment.query().all():
61 for x in ChangesetComment.query().all():
63 Session().delete(x)
62 Session().delete(x)
64 Session().commit()
63 Session().commit()
65
64
66 for x in Notification.query().all():
65 for x in Notification.query().all():
67 Session().delete(x)
66 Session().delete(x)
68 Session().commit()
67 Session().commit()
69
68
70 @pytest.mark.parametrize('comment_type', ChangesetComment.COMMENT_TYPES)
69 @pytest.mark.parametrize('comment_type', ChangesetComment.COMMENT_TYPES)
71 def test_create(self, comment_type, backend):
70 def test_create(self, comment_type, backend):
72 self.log_user()
71 self.log_user()
73 commit = backend.repo.get_commit('300')
72 commit = backend.repo.get_commit('300')
74 commit_id = commit.raw_id
73 commit_id = commit.raw_id
75 text = u'CommentOnCommit'
74 text = u'CommentOnCommit'
76
75
77 params = {'text': text, 'csrf_token': self.csrf_token,
76 params = {'text': text, 'csrf_token': self.csrf_token,
78 'comment_type': comment_type}
77 'comment_type': comment_type}
79 self.app.post(
78 self.app.post(
80 route_path('repo_commit_comment_create',
79 route_path('repo_commit_comment_create',
81 repo_name=backend.repo_name, commit_id=commit_id),
80 repo_name=backend.repo_name, commit_id=commit_id),
82 params=params)
81 params=params)
83
82
84 response = self.app.get(
83 response = self.app.get(
85 route_path('repo_commit',
84 route_path('repo_commit',
86 repo_name=backend.repo_name, commit_id=commit_id))
85 repo_name=backend.repo_name, commit_id=commit_id))
87
86
88 # test DB
87 # test DB
89 assert ChangesetComment.query().count() == 1
88 assert ChangesetComment.query().count() == 1
90 assert_comment_links(response, ChangesetComment.query().count(), 0)
89 assert_comment_links(response, ChangesetComment.query().count(), 0)
91
90
92 assert Notification.query().count() == 1
91 assert Notification.query().count() == 1
93 assert ChangesetComment.query().count() == 1
92 assert ChangesetComment.query().count() == 1
94
93
95 notification = Notification.query().all()[0]
94 notification = Notification.query().all()[0]
96
95
97 comment_id = ChangesetComment.query().first().comment_id
96 comment_id = ChangesetComment.query().first().comment_id
98 assert notification.type_ == Notification.TYPE_CHANGESET_COMMENT
97 assert notification.type_ == Notification.TYPE_CHANGESET_COMMENT
99
98
100 author = notification.created_by_user.username_and_name
99 author = notification.created_by_user.username_and_name
101 sbj = '@{0} left a {1} on commit `{2}` in the `{3}` repository'.format(
100 sbj = '@{0} left a {1} on commit `{2}` in the `{3}` repository'.format(
102 author, comment_type, h.show_id(commit), backend.repo_name)
101 author, comment_type, h.show_id(commit), backend.repo_name)
103 assert sbj == notification.subject
102 assert sbj == notification.subject
104
103
105 lnk = (u'/{0}/changeset/{1}#comment-{2}'.format(
104 lnk = (u'/{0}/changeset/{1}#comment-{2}'.format(
106 backend.repo_name, commit_id, comment_id))
105 backend.repo_name, commit_id, comment_id))
107 assert lnk in notification.body
106 assert lnk in notification.body
108
107
109 @pytest.mark.parametrize('comment_type', ChangesetComment.COMMENT_TYPES)
108 @pytest.mark.parametrize('comment_type', ChangesetComment.COMMENT_TYPES)
110 def test_create_inline(self, comment_type, backend):
109 def test_create_inline(self, comment_type, backend):
111 self.log_user()
110 self.log_user()
112 commit = backend.repo.get_commit('300')
111 commit = backend.repo.get_commit('300')
113 commit_id = commit.raw_id
112 commit_id = commit.raw_id
114 text = u'CommentOnCommit'
113 text = u'CommentOnCommit'
115 f_path = 'vcs/web/simplevcs/views/repository.py'
114 f_path = 'vcs/web/simplevcs/views/repository.py'
116 line = 'n1'
115 line = 'n1'
117
116
118 params = {'text': text, 'f_path': f_path, 'line': line,
117 params = {'text': text, 'f_path': f_path, 'line': line,
119 'comment_type': comment_type,
118 'comment_type': comment_type,
120 'csrf_token': self.csrf_token}
119 'csrf_token': self.csrf_token}
121
120
122 self.app.post(
121 self.app.post(
123 route_path('repo_commit_comment_create',
122 route_path('repo_commit_comment_create',
124 repo_name=backend.repo_name, commit_id=commit_id),
123 repo_name=backend.repo_name, commit_id=commit_id),
125 params=params)
124 params=params)
126
125
127 response = self.app.get(
126 response = self.app.get(
128 route_path('repo_commit',
127 route_path('repo_commit',
129 repo_name=backend.repo_name, commit_id=commit_id))
128 repo_name=backend.repo_name, commit_id=commit_id))
130
129
131 # test DB
130 # test DB
132 assert ChangesetComment.query().count() == 1
131 assert ChangesetComment.query().count() == 1
133 assert_comment_links(response, 0, ChangesetComment.query().count())
132 assert_comment_links(response, 0, ChangesetComment.query().count())
134
133
135 if backend.alias == 'svn':
134 if backend.alias == 'svn':
136 response.mustcontain(
135 response.mustcontain(
137 '''data-f-path="vcs/commands/summary.py" '''
136 '''data-f-path="vcs/commands/summary.py" '''
138 '''data-anchor-id="c-300-ad05457a43f8"'''
137 '''data-anchor-id="c-300-ad05457a43f8"'''
139 )
138 )
140 if backend.alias == 'git':
139 if backend.alias == 'git':
141 response.mustcontain(
140 response.mustcontain(
142 '''data-f-path="vcs/backends/hg.py" '''
141 '''data-f-path="vcs/backends/hg.py" '''
143 '''data-anchor-id="c-883e775e89ea-9c390eb52cd6"'''
142 '''data-anchor-id="c-883e775e89ea-9c390eb52cd6"'''
144 )
143 )
145
144
146 if backend.alias == 'hg':
145 if backend.alias == 'hg':
147 response.mustcontain(
146 response.mustcontain(
148 '''data-f-path="vcs/backends/hg.py" '''
147 '''data-f-path="vcs/backends/hg.py" '''
149 '''data-anchor-id="c-e58d85a3973b-9c390eb52cd6"'''
148 '''data-anchor-id="c-e58d85a3973b-9c390eb52cd6"'''
150 )
149 )
151
150
152 assert Notification.query().count() == 1
151 assert Notification.query().count() == 1
153 assert ChangesetComment.query().count() == 1
152 assert ChangesetComment.query().count() == 1
154
153
155 notification = Notification.query().all()[0]
154 notification = Notification.query().all()[0]
156 comment = ChangesetComment.query().first()
155 comment = ChangesetComment.query().first()
157 assert notification.type_ == Notification.TYPE_CHANGESET_COMMENT
156 assert notification.type_ == Notification.TYPE_CHANGESET_COMMENT
158
157
159 assert comment.revision == commit_id
158 assert comment.revision == commit_id
160
159
161 author = notification.created_by_user.username_and_name
160 author = notification.created_by_user.username_and_name
162 sbj = '@{0} left a {1} on file `{2}` in commit `{3}` in the `{4}` repository'.format(
161 sbj = '@{0} left a {1} on file `{2}` in commit `{3}` in the `{4}` repository'.format(
163 author, comment_type, f_path, h.show_id(commit), backend.repo_name)
162 author, comment_type, f_path, h.show_id(commit), backend.repo_name)
164
163
165 assert sbj == notification.subject
164 assert sbj == notification.subject
166
165
167 lnk = (u'/{0}/changeset/{1}#comment-{2}'.format(
166 lnk = (u'/{0}/changeset/{1}#comment-{2}'.format(
168 backend.repo_name, commit_id, comment.comment_id))
167 backend.repo_name, commit_id, comment.comment_id))
169 assert lnk in notification.body
168 assert lnk in notification.body
170 assert 'on line n1' in notification.body
169 assert 'on line n1' in notification.body
171
170
172 def test_create_with_mention(self, backend):
171 def test_create_with_mention(self, backend):
173 self.log_user()
172 self.log_user()
174
173
175 commit_id = backend.repo.get_commit('300').raw_id
174 commit_id = backend.repo.get_commit('300').raw_id
176 text = u'@test_regular check CommentOnCommit'
175 text = u'@test_regular check CommentOnCommit'
177
176
178 params = {'text': text, 'csrf_token': self.csrf_token}
177 params = {'text': text, 'csrf_token': self.csrf_token}
179 self.app.post(
178 self.app.post(
180 route_path('repo_commit_comment_create',
179 route_path('repo_commit_comment_create',
181 repo_name=backend.repo_name, commit_id=commit_id),
180 repo_name=backend.repo_name, commit_id=commit_id),
182 params=params)
181 params=params)
183
182
184 response = self.app.get(
183 response = self.app.get(
185 route_path('repo_commit',
184 route_path('repo_commit',
186 repo_name=backend.repo_name, commit_id=commit_id))
185 repo_name=backend.repo_name, commit_id=commit_id))
187 # test DB
186 # test DB
188 assert ChangesetComment.query().count() == 1
187 assert ChangesetComment.query().count() == 1
189 assert_comment_links(response, ChangesetComment.query().count(), 0)
188 assert_comment_links(response, ChangesetComment.query().count(), 0)
190
189
191 notification = Notification.query().one()
190 notification = Notification.query().one()
192
191
193 assert len(notification.recipients) == 2
192 assert len(notification.recipients) == 2
194 users = [x.username for x in notification.recipients]
193 users = [x.username for x in notification.recipients]
195
194
196 # test_regular gets notification by @mention
195 # test_regular gets notification by @mention
197 assert sorted(users) == [u'test_admin', u'test_regular']
196 assert sorted(users) == [u'test_admin', u'test_regular']
198
197
199 def test_create_with_status_change(self, backend):
198 def test_create_with_status_change(self, backend):
200 self.log_user()
199 self.log_user()
201 commit = backend.repo.get_commit('300')
200 commit = backend.repo.get_commit('300')
202 commit_id = commit.raw_id
201 commit_id = commit.raw_id
203 text = u'CommentOnCommit'
202 text = u'CommentOnCommit'
204 f_path = 'vcs/web/simplevcs/views/repository.py'
203 f_path = 'vcs/web/simplevcs/views/repository.py'
205 line = 'n1'
204 line = 'n1'
206
205
207 params = {'text': text, 'changeset_status': 'approved',
206 params = {'text': text, 'changeset_status': 'approved',
208 'csrf_token': self.csrf_token}
207 'csrf_token': self.csrf_token}
209
208
210 self.app.post(
209 self.app.post(
211 route_path(
210 route_path(
212 'repo_commit_comment_create',
211 'repo_commit_comment_create',
213 repo_name=backend.repo_name, commit_id=commit_id),
212 repo_name=backend.repo_name, commit_id=commit_id),
214 params=params)
213 params=params)
215
214
216 response = self.app.get(
215 response = self.app.get(
217 route_path('repo_commit',
216 route_path('repo_commit',
218 repo_name=backend.repo_name, commit_id=commit_id))
217 repo_name=backend.repo_name, commit_id=commit_id))
219
218
220 # test DB
219 # test DB
221 assert ChangesetComment.query().count() == 1
220 assert ChangesetComment.query().count() == 1
222 assert_comment_links(response, ChangesetComment.query().count(), 0)
221 assert_comment_links(response, ChangesetComment.query().count(), 0)
223
222
224 assert Notification.query().count() == 1
223 assert Notification.query().count() == 1
225 assert ChangesetComment.query().count() == 1
224 assert ChangesetComment.query().count() == 1
226
225
227 notification = Notification.query().all()[0]
226 notification = Notification.query().all()[0]
228
227
229 comment_id = ChangesetComment.query().first().comment_id
228 comment_id = ChangesetComment.query().first().comment_id
230 assert notification.type_ == Notification.TYPE_CHANGESET_COMMENT
229 assert notification.type_ == Notification.TYPE_CHANGESET_COMMENT
231
230
232 author = notification.created_by_user.username_and_name
231 author = notification.created_by_user.username_and_name
233 sbj = '[status: Approved] @{0} left a note on commit `{1}` in the `{2}` repository'.format(
232 sbj = '[status: Approved] @{0} left a note on commit `{1}` in the `{2}` repository'.format(
234 author, h.show_id(commit), backend.repo_name)
233 author, h.show_id(commit), backend.repo_name)
235 assert sbj == notification.subject
234 assert sbj == notification.subject
236
235
237 lnk = (u'/{0}/changeset/{1}#comment-{2}'.format(
236 lnk = (u'/{0}/changeset/{1}#comment-{2}'.format(
238 backend.repo_name, commit_id, comment_id))
237 backend.repo_name, commit_id, comment_id))
239 assert lnk in notification.body
238 assert lnk in notification.body
240
239
241 def test_delete(self, backend):
240 def test_delete(self, backend):
242 self.log_user()
241 self.log_user()
243 commit_id = backend.repo.get_commit('300').raw_id
242 commit_id = backend.repo.get_commit('300').raw_id
244 text = u'CommentOnCommit'
243 text = u'CommentOnCommit'
245
244
246 params = {'text': text, 'csrf_token': self.csrf_token}
245 params = {'text': text, 'csrf_token': self.csrf_token}
247 self.app.post(
246 self.app.post(
248 route_path(
247 route_path(
249 'repo_commit_comment_create',
248 'repo_commit_comment_create',
250 repo_name=backend.repo_name, commit_id=commit_id),
249 repo_name=backend.repo_name, commit_id=commit_id),
251 params=params)
250 params=params)
252
251
253 comments = ChangesetComment.query().all()
252 comments = ChangesetComment.query().all()
254 assert len(comments) == 1
253 assert len(comments) == 1
255 comment_id = comments[0].comment_id
254 comment_id = comments[0].comment_id
256
255
257 self.app.post(
256 self.app.post(
258 route_path('repo_commit_comment_delete',
257 route_path('repo_commit_comment_delete',
259 repo_name=backend.repo_name,
258 repo_name=backend.repo_name,
260 commit_id=commit_id,
259 commit_id=commit_id,
261 comment_id=comment_id),
260 comment_id=comment_id),
262 params={'csrf_token': self.csrf_token})
261 params={'csrf_token': self.csrf_token})
263
262
264 comments = ChangesetComment.query().all()
263 comments = ChangesetComment.query().all()
265 assert len(comments) == 0
264 assert len(comments) == 0
266
265
267 response = self.app.get(
266 response = self.app.get(
268 route_path('repo_commit',
267 route_path('repo_commit',
269 repo_name=backend.repo_name, commit_id=commit_id))
268 repo_name=backend.repo_name, commit_id=commit_id))
270 assert_comment_links(response, 0, 0)
269 assert_comment_links(response, 0, 0)
271
270
272 @pytest.mark.parametrize('renderer, input, output', [
271 def test_delete_forbidden_for_immutable_comments(self, backend):
272 self.log_user()
273 commit_id = backend.repo.get_commit('300').raw_id
274 text = u'CommentOnCommit'
275
276 params = {'text': text, 'csrf_token': self.csrf_token}
277 self.app.post(
278 route_path(
279 'repo_commit_comment_create',
280 repo_name=backend.repo_name, commit_id=commit_id),
281 params=params)
282
283 comments = ChangesetComment.query().all()
284 assert len(comments) == 1
285 comment_id = comments[0].comment_id
286
287 comment = ChangesetComment.get(comment_id)
288 comment.immutable_state = ChangesetComment.OP_IMMUTABLE
289 Session().add(comment)
290 Session().commit()
291
292 self.app.post(
293 route_path('repo_commit_comment_delete',
294 repo_name=backend.repo_name,
295 commit_id=commit_id,
296 comment_id=comment_id),
297 params={'csrf_token': self.csrf_token},
298 status=403)
299
300 @pytest.mark.parametrize('renderer, text_input, output', [
273 ('rst', 'plain text', '<p>plain text</p>'),
301 ('rst', 'plain text', '<p>plain text</p>'),
274 ('rst', 'header\n======', '<h1 class="title">header</h1>'),
302 ('rst', 'header\n======', '<h1 class="title">header</h1>'),
275 ('rst', '*italics*', '<em>italics</em>'),
303 ('rst', '*italics*', '<em>italics</em>'),
276 ('rst', '**bold**', '<strong>bold</strong>'),
304 ('rst', '**bold**', '<strong>bold</strong>'),
277 ('markdown', 'plain text', '<p>plain text</p>'),
305 ('markdown', 'plain text', '<p>plain text</p>'),
278 ('markdown', '# header', '<h1>header</h1>'),
306 ('markdown', '# header', '<h1>header</h1>'),
279 ('markdown', '*italics*', '<em>italics</em>'),
307 ('markdown', '*italics*', '<em>italics</em>'),
280 ('markdown', '**bold**', '<strong>bold</strong>'),
308 ('markdown', '**bold**', '<strong>bold</strong>'),
281 ], ids=['rst-plain', 'rst-header', 'rst-italics', 'rst-bold', 'md-plain',
309 ], ids=['rst-plain', 'rst-header', 'rst-italics', 'rst-bold', 'md-plain',
282 'md-header', 'md-italics', 'md-bold', ])
310 'md-header', 'md-italics', 'md-bold', ])
283 def test_preview(self, renderer, input, output, backend, xhr_header):
311 def test_preview(self, renderer, text_input, output, backend, xhr_header):
284 self.log_user()
312 self.log_user()
285 params = {
313 params = {
286 'renderer': renderer,
314 'renderer': renderer,
287 'text': input,
315 'text': text_input,
288 'csrf_token': self.csrf_token
316 'csrf_token': self.csrf_token
289 }
317 }
290 commit_id = '0' * 16 # fake this for tests
318 commit_id = '0' * 16 # fake this for tests
291 response = self.app.post(
319 response = self.app.post(
292 route_path('repo_commit_comment_preview',
320 route_path('repo_commit_comment_preview',
293 repo_name=backend.repo_name, commit_id=commit_id,),
321 repo_name=backend.repo_name, commit_id=commit_id,),
294 params=params,
322 params=params,
295 extra_environ=xhr_header)
323 extra_environ=xhr_header)
296
324
297 response.mustcontain(output)
325 response.mustcontain(output)
298
326
299
327
300 def assert_comment_links(response, comments, inline_comments):
328 def assert_comment_links(response, comments, inline_comments):
301 if comments == 1:
329 if comments == 1:
302 comments_text = "%d General" % comments
330 comments_text = "%d General" % comments
303 else:
331 else:
304 comments_text = "%d General" % comments
332 comments_text = "%d General" % comments
305
333
306 if inline_comments == 1:
334 if inline_comments == 1:
307 inline_comments_text = "%d Inline" % inline_comments
335 inline_comments_text = "%d Inline" % inline_comments
308 else:
336 else:
309 inline_comments_text = "%d Inline" % inline_comments
337 inline_comments_text = "%d Inline" % inline_comments
310
338
311 if comments:
339 if comments:
312 response.mustcontain('<a href="#comments">%s</a>,' % comments_text)
340 response.mustcontain('<a href="#comments">%s</a>,' % comments_text)
313 else:
341 else:
314 response.mustcontain(comments_text)
342 response.mustcontain(comments_text)
315
343
316 if inline_comments:
344 if inline_comments:
317 response.mustcontain(
345 response.mustcontain(
318 'id="inline-comments-counter">%s' % inline_comments_text)
346 'id="inline-comments-counter">%s' % inline_comments_text)
319 else:
347 else:
320 response.mustcontain(inline_comments_text)
348 response.mustcontain(inline_comments_text)
@@ -1,606 +1,610 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2020 RhodeCode GmbH
3 # Copyright (C) 2010-2020 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 import collections
23 import collections
24
24
25 from pyramid.httpexceptions import HTTPNotFound, HTTPBadRequest, HTTPFound
25 from pyramid.httpexceptions import HTTPNotFound, HTTPBadRequest, HTTPFound, HTTPForbidden
26 from pyramid.view import view_config
26 from pyramid.view import view_config
27 from pyramid.renderers import render
27 from pyramid.renderers import render
28 from pyramid.response import Response
28 from pyramid.response import Response
29
29
30 from rhodecode.apps._base import RepoAppView
30 from rhodecode.apps._base import RepoAppView
31 from rhodecode.apps.file_store import utils as store_utils
31 from rhodecode.apps.file_store import utils as store_utils
32 from rhodecode.apps.file_store.exceptions import FileNotAllowedException, FileOverSizeException
32 from rhodecode.apps.file_store.exceptions import FileNotAllowedException, FileOverSizeException
33
33
34 from rhodecode.lib import diffs, codeblocks
34 from rhodecode.lib import diffs, codeblocks
35 from rhodecode.lib.auth import (
35 from rhodecode.lib.auth import (
36 LoginRequired, HasRepoPermissionAnyDecorator, NotAnonymous, CSRFRequired)
36 LoginRequired, HasRepoPermissionAnyDecorator, NotAnonymous, CSRFRequired)
37
37
38 from rhodecode.lib.compat import OrderedDict
38 from rhodecode.lib.compat import OrderedDict
39 from rhodecode.lib.diffs import (
39 from rhodecode.lib.diffs import (
40 cache_diff, load_cached_diff, diff_cache_exist, get_diff_context,
40 cache_diff, load_cached_diff, diff_cache_exist, get_diff_context,
41 get_diff_whitespace_flag)
41 get_diff_whitespace_flag)
42 from rhodecode.lib.exceptions import StatusChangeOnClosedPullRequestError
42 from rhodecode.lib.exceptions import StatusChangeOnClosedPullRequestError
43 import rhodecode.lib.helpers as h
43 import rhodecode.lib.helpers as h
44 from rhodecode.lib.utils2 import safe_unicode, str2bool
44 from rhodecode.lib.utils2 import safe_unicode, str2bool
45 from rhodecode.lib.vcs.backends.base import EmptyCommit
45 from rhodecode.lib.vcs.backends.base import EmptyCommit
46 from rhodecode.lib.vcs.exceptions import (
46 from rhodecode.lib.vcs.exceptions import (
47 RepositoryError, CommitDoesNotExistError)
47 RepositoryError, CommitDoesNotExistError)
48 from rhodecode.model.db import ChangesetComment, ChangesetStatus, FileStore
48 from rhodecode.model.db import ChangesetComment, ChangesetStatus, FileStore
49 from rhodecode.model.changeset_status import ChangesetStatusModel
49 from rhodecode.model.changeset_status import ChangesetStatusModel
50 from rhodecode.model.comment import CommentsModel
50 from rhodecode.model.comment import CommentsModel
51 from rhodecode.model.meta import Session
51 from rhodecode.model.meta import Session
52 from rhodecode.model.settings import VcsSettingsModel
52 from rhodecode.model.settings import VcsSettingsModel
53
53
54 log = logging.getLogger(__name__)
54 log = logging.getLogger(__name__)
55
55
56
56
57 def _update_with_GET(params, request):
57 def _update_with_GET(params, request):
58 for k in ['diff1', 'diff2', 'diff']:
58 for k in ['diff1', 'diff2', 'diff']:
59 params[k] += request.GET.getall(k)
59 params[k] += request.GET.getall(k)
60
60
61
61
62 class RepoCommitsView(RepoAppView):
62 class RepoCommitsView(RepoAppView):
63 def load_default_context(self):
63 def load_default_context(self):
64 c = self._get_local_tmpl_context(include_app_defaults=True)
64 c = self._get_local_tmpl_context(include_app_defaults=True)
65 c.rhodecode_repo = self.rhodecode_vcs_repo
65 c.rhodecode_repo = self.rhodecode_vcs_repo
66
66
67 return c
67 return c
68
68
69 def _is_diff_cache_enabled(self, target_repo):
69 def _is_diff_cache_enabled(self, target_repo):
70 caching_enabled = self._get_general_setting(
70 caching_enabled = self._get_general_setting(
71 target_repo, 'rhodecode_diff_cache')
71 target_repo, 'rhodecode_diff_cache')
72 log.debug('Diff caching enabled: %s', caching_enabled)
72 log.debug('Diff caching enabled: %s', caching_enabled)
73 return caching_enabled
73 return caching_enabled
74
74
75 def _commit(self, commit_id_range, method):
75 def _commit(self, commit_id_range, method):
76 _ = self.request.translate
76 _ = self.request.translate
77 c = self.load_default_context()
77 c = self.load_default_context()
78 c.fulldiff = self.request.GET.get('fulldiff')
78 c.fulldiff = self.request.GET.get('fulldiff')
79
79
80 # fetch global flags of ignore ws or context lines
80 # fetch global flags of ignore ws or context lines
81 diff_context = get_diff_context(self.request)
81 diff_context = get_diff_context(self.request)
82 hide_whitespace_changes = get_diff_whitespace_flag(self.request)
82 hide_whitespace_changes = get_diff_whitespace_flag(self.request)
83
83
84 # diff_limit will cut off the whole diff if the limit is applied
84 # diff_limit will cut off the whole diff if the limit is applied
85 # otherwise it will just hide the big files from the front-end
85 # otherwise it will just hide the big files from the front-end
86 diff_limit = c.visual.cut_off_limit_diff
86 diff_limit = c.visual.cut_off_limit_diff
87 file_limit = c.visual.cut_off_limit_file
87 file_limit = c.visual.cut_off_limit_file
88
88
89 # get ranges of commit ids if preset
89 # get ranges of commit ids if preset
90 commit_range = commit_id_range.split('...')[:2]
90 commit_range = commit_id_range.split('...')[:2]
91
91
92 try:
92 try:
93 pre_load = ['affected_files', 'author', 'branch', 'date',
93 pre_load = ['affected_files', 'author', 'branch', 'date',
94 'message', 'parents']
94 'message', 'parents']
95 if self.rhodecode_vcs_repo.alias == 'hg':
95 if self.rhodecode_vcs_repo.alias == 'hg':
96 pre_load += ['hidden', 'obsolete', 'phase']
96 pre_load += ['hidden', 'obsolete', 'phase']
97
97
98 if len(commit_range) == 2:
98 if len(commit_range) == 2:
99 commits = self.rhodecode_vcs_repo.get_commits(
99 commits = self.rhodecode_vcs_repo.get_commits(
100 start_id=commit_range[0], end_id=commit_range[1],
100 start_id=commit_range[0], end_id=commit_range[1],
101 pre_load=pre_load, translate_tags=False)
101 pre_load=pre_load, translate_tags=False)
102 commits = list(commits)
102 commits = list(commits)
103 else:
103 else:
104 commits = [self.rhodecode_vcs_repo.get_commit(
104 commits = [self.rhodecode_vcs_repo.get_commit(
105 commit_id=commit_id_range, pre_load=pre_load)]
105 commit_id=commit_id_range, pre_load=pre_load)]
106
106
107 c.commit_ranges = commits
107 c.commit_ranges = commits
108 if not c.commit_ranges:
108 if not c.commit_ranges:
109 raise RepositoryError('The commit range returned an empty result')
109 raise RepositoryError('The commit range returned an empty result')
110 except CommitDoesNotExistError as e:
110 except CommitDoesNotExistError as e:
111 msg = _('No such commit exists. Org exception: `{}`').format(e)
111 msg = _('No such commit exists. Org exception: `{}`').format(e)
112 h.flash(msg, category='error')
112 h.flash(msg, category='error')
113 raise HTTPNotFound()
113 raise HTTPNotFound()
114 except Exception:
114 except Exception:
115 log.exception("General failure")
115 log.exception("General failure")
116 raise HTTPNotFound()
116 raise HTTPNotFound()
117
117
118 c.changes = OrderedDict()
118 c.changes = OrderedDict()
119 c.lines_added = 0
119 c.lines_added = 0
120 c.lines_deleted = 0
120 c.lines_deleted = 0
121
121
122 # auto collapse if we have more than limit
122 # auto collapse if we have more than limit
123 collapse_limit = diffs.DiffProcessor._collapse_commits_over
123 collapse_limit = diffs.DiffProcessor._collapse_commits_over
124 c.collapse_all_commits = len(c.commit_ranges) > collapse_limit
124 c.collapse_all_commits = len(c.commit_ranges) > collapse_limit
125
125
126 c.commit_statuses = ChangesetStatus.STATUSES
126 c.commit_statuses = ChangesetStatus.STATUSES
127 c.inline_comments = []
127 c.inline_comments = []
128 c.files = []
128 c.files = []
129
129
130 c.statuses = []
130 c.statuses = []
131 c.comments = []
131 c.comments = []
132 c.unresolved_comments = []
132 c.unresolved_comments = []
133 c.resolved_comments = []
133 c.resolved_comments = []
134 if len(c.commit_ranges) == 1:
134 if len(c.commit_ranges) == 1:
135 commit = c.commit_ranges[0]
135 commit = c.commit_ranges[0]
136 c.comments = CommentsModel().get_comments(
136 c.comments = CommentsModel().get_comments(
137 self.db_repo.repo_id,
137 self.db_repo.repo_id,
138 revision=commit.raw_id)
138 revision=commit.raw_id)
139 c.statuses.append(ChangesetStatusModel().get_status(
139 c.statuses.append(ChangesetStatusModel().get_status(
140 self.db_repo.repo_id, commit.raw_id))
140 self.db_repo.repo_id, commit.raw_id))
141 # comments from PR
141 # comments from PR
142 statuses = ChangesetStatusModel().get_statuses(
142 statuses = ChangesetStatusModel().get_statuses(
143 self.db_repo.repo_id, commit.raw_id,
143 self.db_repo.repo_id, commit.raw_id,
144 with_revisions=True)
144 with_revisions=True)
145 prs = set(st.pull_request for st in statuses
145 prs = set(st.pull_request for st in statuses
146 if st.pull_request is not None)
146 if st.pull_request is not None)
147 # from associated statuses, check the pull requests, and
147 # from associated statuses, check the pull requests, and
148 # show comments from them
148 # show comments from them
149 for pr in prs:
149 for pr in prs:
150 c.comments.extend(pr.comments)
150 c.comments.extend(pr.comments)
151
151
152 c.unresolved_comments = CommentsModel()\
152 c.unresolved_comments = CommentsModel()\
153 .get_commit_unresolved_todos(commit.raw_id)
153 .get_commit_unresolved_todos(commit.raw_id)
154 c.resolved_comments = CommentsModel()\
154 c.resolved_comments = CommentsModel()\
155 .get_commit_resolved_todos(commit.raw_id)
155 .get_commit_resolved_todos(commit.raw_id)
156
156
157 diff = None
157 diff = None
158 # Iterate over ranges (default commit view is always one commit)
158 # Iterate over ranges (default commit view is always one commit)
159 for commit in c.commit_ranges:
159 for commit in c.commit_ranges:
160 c.changes[commit.raw_id] = []
160 c.changes[commit.raw_id] = []
161
161
162 commit2 = commit
162 commit2 = commit
163 commit1 = commit.first_parent
163 commit1 = commit.first_parent
164
164
165 if method == 'show':
165 if method == 'show':
166 inline_comments = CommentsModel().get_inline_comments(
166 inline_comments = CommentsModel().get_inline_comments(
167 self.db_repo.repo_id, revision=commit.raw_id)
167 self.db_repo.repo_id, revision=commit.raw_id)
168 c.inline_cnt = CommentsModel().get_inline_comments_count(
168 c.inline_cnt = CommentsModel().get_inline_comments_count(
169 inline_comments)
169 inline_comments)
170 c.inline_comments = inline_comments
170 c.inline_comments = inline_comments
171
171
172 cache_path = self.rhodecode_vcs_repo.get_create_shadow_cache_pr_path(
172 cache_path = self.rhodecode_vcs_repo.get_create_shadow_cache_pr_path(
173 self.db_repo)
173 self.db_repo)
174 cache_file_path = diff_cache_exist(
174 cache_file_path = diff_cache_exist(
175 cache_path, 'diff', commit.raw_id,
175 cache_path, 'diff', commit.raw_id,
176 hide_whitespace_changes, diff_context, c.fulldiff)
176 hide_whitespace_changes, diff_context, c.fulldiff)
177
177
178 caching_enabled = self._is_diff_cache_enabled(self.db_repo)
178 caching_enabled = self._is_diff_cache_enabled(self.db_repo)
179 force_recache = str2bool(self.request.GET.get('force_recache'))
179 force_recache = str2bool(self.request.GET.get('force_recache'))
180
180
181 cached_diff = None
181 cached_diff = None
182 if caching_enabled:
182 if caching_enabled:
183 cached_diff = load_cached_diff(cache_file_path)
183 cached_diff = load_cached_diff(cache_file_path)
184
184
185 has_proper_diff_cache = cached_diff and cached_diff.get('diff')
185 has_proper_diff_cache = cached_diff and cached_diff.get('diff')
186 if not force_recache and has_proper_diff_cache:
186 if not force_recache and has_proper_diff_cache:
187 diffset = cached_diff['diff']
187 diffset = cached_diff['diff']
188 else:
188 else:
189 vcs_diff = self.rhodecode_vcs_repo.get_diff(
189 vcs_diff = self.rhodecode_vcs_repo.get_diff(
190 commit1, commit2,
190 commit1, commit2,
191 ignore_whitespace=hide_whitespace_changes,
191 ignore_whitespace=hide_whitespace_changes,
192 context=diff_context)
192 context=diff_context)
193
193
194 diff_processor = diffs.DiffProcessor(
194 diff_processor = diffs.DiffProcessor(
195 vcs_diff, format='newdiff', diff_limit=diff_limit,
195 vcs_diff, format='newdiff', diff_limit=diff_limit,
196 file_limit=file_limit, show_full_diff=c.fulldiff)
196 file_limit=file_limit, show_full_diff=c.fulldiff)
197
197
198 _parsed = diff_processor.prepare()
198 _parsed = diff_processor.prepare()
199
199
200 diffset = codeblocks.DiffSet(
200 diffset = codeblocks.DiffSet(
201 repo_name=self.db_repo_name,
201 repo_name=self.db_repo_name,
202 source_node_getter=codeblocks.diffset_node_getter(commit1),
202 source_node_getter=codeblocks.diffset_node_getter(commit1),
203 target_node_getter=codeblocks.diffset_node_getter(commit2))
203 target_node_getter=codeblocks.diffset_node_getter(commit2))
204
204
205 diffset = self.path_filter.render_patchset_filtered(
205 diffset = self.path_filter.render_patchset_filtered(
206 diffset, _parsed, commit1.raw_id, commit2.raw_id)
206 diffset, _parsed, commit1.raw_id, commit2.raw_id)
207
207
208 # save cached diff
208 # save cached diff
209 if caching_enabled:
209 if caching_enabled:
210 cache_diff(cache_file_path, diffset, None)
210 cache_diff(cache_file_path, diffset, None)
211
211
212 c.limited_diff = diffset.limited_diff
212 c.limited_diff = diffset.limited_diff
213 c.changes[commit.raw_id] = diffset
213 c.changes[commit.raw_id] = diffset
214 else:
214 else:
215 # TODO(marcink): no cache usage here...
215 # TODO(marcink): no cache usage here...
216 _diff = self.rhodecode_vcs_repo.get_diff(
216 _diff = self.rhodecode_vcs_repo.get_diff(
217 commit1, commit2,
217 commit1, commit2,
218 ignore_whitespace=hide_whitespace_changes, context=diff_context)
218 ignore_whitespace=hide_whitespace_changes, context=diff_context)
219 diff_processor = diffs.DiffProcessor(
219 diff_processor = diffs.DiffProcessor(
220 _diff, format='newdiff', diff_limit=diff_limit,
220 _diff, format='newdiff', diff_limit=diff_limit,
221 file_limit=file_limit, show_full_diff=c.fulldiff)
221 file_limit=file_limit, show_full_diff=c.fulldiff)
222 # downloads/raw we only need RAW diff nothing else
222 # downloads/raw we only need RAW diff nothing else
223 diff = self.path_filter.get_raw_patch(diff_processor)
223 diff = self.path_filter.get_raw_patch(diff_processor)
224 c.changes[commit.raw_id] = [None, None, None, None, diff, None, None]
224 c.changes[commit.raw_id] = [None, None, None, None, diff, None, None]
225
225
226 # sort comments by how they were generated
226 # sort comments by how they were generated
227 c.comments = sorted(c.comments, key=lambda x: x.comment_id)
227 c.comments = sorted(c.comments, key=lambda x: x.comment_id)
228
228
229 if len(c.commit_ranges) == 1:
229 if len(c.commit_ranges) == 1:
230 c.commit = c.commit_ranges[0]
230 c.commit = c.commit_ranges[0]
231 c.parent_tmpl = ''.join(
231 c.parent_tmpl = ''.join(
232 '# Parent %s\n' % x.raw_id for x in c.commit.parents)
232 '# Parent %s\n' % x.raw_id for x in c.commit.parents)
233
233
234 if method == 'download':
234 if method == 'download':
235 response = Response(diff)
235 response = Response(diff)
236 response.content_type = 'text/plain'
236 response.content_type = 'text/plain'
237 response.content_disposition = (
237 response.content_disposition = (
238 'attachment; filename=%s.diff' % commit_id_range[:12])
238 'attachment; filename=%s.diff' % commit_id_range[:12])
239 return response
239 return response
240 elif method == 'patch':
240 elif method == 'patch':
241 c.diff = safe_unicode(diff)
241 c.diff = safe_unicode(diff)
242 patch = render(
242 patch = render(
243 'rhodecode:templates/changeset/patch_changeset.mako',
243 'rhodecode:templates/changeset/patch_changeset.mako',
244 self._get_template_context(c), self.request)
244 self._get_template_context(c), self.request)
245 response = Response(patch)
245 response = Response(patch)
246 response.content_type = 'text/plain'
246 response.content_type = 'text/plain'
247 return response
247 return response
248 elif method == 'raw':
248 elif method == 'raw':
249 response = Response(diff)
249 response = Response(diff)
250 response.content_type = 'text/plain'
250 response.content_type = 'text/plain'
251 return response
251 return response
252 elif method == 'show':
252 elif method == 'show':
253 if len(c.commit_ranges) == 1:
253 if len(c.commit_ranges) == 1:
254 html = render(
254 html = render(
255 'rhodecode:templates/changeset/changeset.mako',
255 'rhodecode:templates/changeset/changeset.mako',
256 self._get_template_context(c), self.request)
256 self._get_template_context(c), self.request)
257 return Response(html)
257 return Response(html)
258 else:
258 else:
259 c.ancestor = None
259 c.ancestor = None
260 c.target_repo = self.db_repo
260 c.target_repo = self.db_repo
261 html = render(
261 html = render(
262 'rhodecode:templates/changeset/changeset_range.mako',
262 'rhodecode:templates/changeset/changeset_range.mako',
263 self._get_template_context(c), self.request)
263 self._get_template_context(c), self.request)
264 return Response(html)
264 return Response(html)
265
265
266 raise HTTPBadRequest()
266 raise HTTPBadRequest()
267
267
268 @LoginRequired()
268 @LoginRequired()
269 @HasRepoPermissionAnyDecorator(
269 @HasRepoPermissionAnyDecorator(
270 'repository.read', 'repository.write', 'repository.admin')
270 'repository.read', 'repository.write', 'repository.admin')
271 @view_config(
271 @view_config(
272 route_name='repo_commit', request_method='GET',
272 route_name='repo_commit', request_method='GET',
273 renderer=None)
273 renderer=None)
274 def repo_commit_show(self):
274 def repo_commit_show(self):
275 commit_id = self.request.matchdict['commit_id']
275 commit_id = self.request.matchdict['commit_id']
276 return self._commit(commit_id, method='show')
276 return self._commit(commit_id, method='show')
277
277
278 @LoginRequired()
278 @LoginRequired()
279 @HasRepoPermissionAnyDecorator(
279 @HasRepoPermissionAnyDecorator(
280 'repository.read', 'repository.write', 'repository.admin')
280 'repository.read', 'repository.write', 'repository.admin')
281 @view_config(
281 @view_config(
282 route_name='repo_commit_raw', request_method='GET',
282 route_name='repo_commit_raw', request_method='GET',
283 renderer=None)
283 renderer=None)
284 @view_config(
284 @view_config(
285 route_name='repo_commit_raw_deprecated', request_method='GET',
285 route_name='repo_commit_raw_deprecated', request_method='GET',
286 renderer=None)
286 renderer=None)
287 def repo_commit_raw(self):
287 def repo_commit_raw(self):
288 commit_id = self.request.matchdict['commit_id']
288 commit_id = self.request.matchdict['commit_id']
289 return self._commit(commit_id, method='raw')
289 return self._commit(commit_id, method='raw')
290
290
291 @LoginRequired()
291 @LoginRequired()
292 @HasRepoPermissionAnyDecorator(
292 @HasRepoPermissionAnyDecorator(
293 'repository.read', 'repository.write', 'repository.admin')
293 'repository.read', 'repository.write', 'repository.admin')
294 @view_config(
294 @view_config(
295 route_name='repo_commit_patch', request_method='GET',
295 route_name='repo_commit_patch', request_method='GET',
296 renderer=None)
296 renderer=None)
297 def repo_commit_patch(self):
297 def repo_commit_patch(self):
298 commit_id = self.request.matchdict['commit_id']
298 commit_id = self.request.matchdict['commit_id']
299 return self._commit(commit_id, method='patch')
299 return self._commit(commit_id, method='patch')
300
300
301 @LoginRequired()
301 @LoginRequired()
302 @HasRepoPermissionAnyDecorator(
302 @HasRepoPermissionAnyDecorator(
303 'repository.read', 'repository.write', 'repository.admin')
303 'repository.read', 'repository.write', 'repository.admin')
304 @view_config(
304 @view_config(
305 route_name='repo_commit_download', request_method='GET',
305 route_name='repo_commit_download', request_method='GET',
306 renderer=None)
306 renderer=None)
307 def repo_commit_download(self):
307 def repo_commit_download(self):
308 commit_id = self.request.matchdict['commit_id']
308 commit_id = self.request.matchdict['commit_id']
309 return self._commit(commit_id, method='download')
309 return self._commit(commit_id, method='download')
310
310
311 @LoginRequired()
311 @LoginRequired()
312 @NotAnonymous()
312 @NotAnonymous()
313 @HasRepoPermissionAnyDecorator(
313 @HasRepoPermissionAnyDecorator(
314 'repository.read', 'repository.write', 'repository.admin')
314 'repository.read', 'repository.write', 'repository.admin')
315 @CSRFRequired()
315 @CSRFRequired()
316 @view_config(
316 @view_config(
317 route_name='repo_commit_comment_create', request_method='POST',
317 route_name='repo_commit_comment_create', request_method='POST',
318 renderer='json_ext')
318 renderer='json_ext')
319 def repo_commit_comment_create(self):
319 def repo_commit_comment_create(self):
320 _ = self.request.translate
320 _ = self.request.translate
321 commit_id = self.request.matchdict['commit_id']
321 commit_id = self.request.matchdict['commit_id']
322
322
323 c = self.load_default_context()
323 c = self.load_default_context()
324 status = self.request.POST.get('changeset_status', None)
324 status = self.request.POST.get('changeset_status', None)
325 text = self.request.POST.get('text')
325 text = self.request.POST.get('text')
326 comment_type = self.request.POST.get('comment_type')
326 comment_type = self.request.POST.get('comment_type')
327 resolves_comment_id = self.request.POST.get('resolves_comment_id', None)
327 resolves_comment_id = self.request.POST.get('resolves_comment_id', None)
328
328
329 if status:
329 if status:
330 text = text or (_('Status change %(transition_icon)s %(status)s')
330 text = text or (_('Status change %(transition_icon)s %(status)s')
331 % {'transition_icon': '>',
331 % {'transition_icon': '>',
332 'status': ChangesetStatus.get_status_lbl(status)})
332 'status': ChangesetStatus.get_status_lbl(status)})
333
333
334 multi_commit_ids = []
334 multi_commit_ids = []
335 for _commit_id in self.request.POST.get('commit_ids', '').split(','):
335 for _commit_id in self.request.POST.get('commit_ids', '').split(','):
336 if _commit_id not in ['', None, EmptyCommit.raw_id]:
336 if _commit_id not in ['', None, EmptyCommit.raw_id]:
337 if _commit_id not in multi_commit_ids:
337 if _commit_id not in multi_commit_ids:
338 multi_commit_ids.append(_commit_id)
338 multi_commit_ids.append(_commit_id)
339
339
340 commit_ids = multi_commit_ids or [commit_id]
340 commit_ids = multi_commit_ids or [commit_id]
341
341
342 comment = None
342 comment = None
343 for current_id in filter(None, commit_ids):
343 for current_id in filter(None, commit_ids):
344 comment = CommentsModel().create(
344 comment = CommentsModel().create(
345 text=text,
345 text=text,
346 repo=self.db_repo.repo_id,
346 repo=self.db_repo.repo_id,
347 user=self._rhodecode_db_user.user_id,
347 user=self._rhodecode_db_user.user_id,
348 commit_id=current_id,
348 commit_id=current_id,
349 f_path=self.request.POST.get('f_path'),
349 f_path=self.request.POST.get('f_path'),
350 line_no=self.request.POST.get('line'),
350 line_no=self.request.POST.get('line'),
351 status_change=(ChangesetStatus.get_status_lbl(status)
351 status_change=(ChangesetStatus.get_status_lbl(status)
352 if status else None),
352 if status else None),
353 status_change_type=status,
353 status_change_type=status,
354 comment_type=comment_type,
354 comment_type=comment_type,
355 resolves_comment_id=resolves_comment_id,
355 resolves_comment_id=resolves_comment_id,
356 auth_user=self._rhodecode_user
356 auth_user=self._rhodecode_user
357 )
357 )
358
358
359 # get status if set !
359 # get status if set !
360 if status:
360 if status:
361 # if latest status was from pull request and it's closed
361 # if latest status was from pull request and it's closed
362 # disallow changing status !
362 # disallow changing status !
363 # dont_allow_on_closed_pull_request = True !
363 # dont_allow_on_closed_pull_request = True !
364
364
365 try:
365 try:
366 ChangesetStatusModel().set_status(
366 ChangesetStatusModel().set_status(
367 self.db_repo.repo_id,
367 self.db_repo.repo_id,
368 status,
368 status,
369 self._rhodecode_db_user.user_id,
369 self._rhodecode_db_user.user_id,
370 comment,
370 comment,
371 revision=current_id,
371 revision=current_id,
372 dont_allow_on_closed_pull_request=True
372 dont_allow_on_closed_pull_request=True
373 )
373 )
374 except StatusChangeOnClosedPullRequestError:
374 except StatusChangeOnClosedPullRequestError:
375 msg = _('Changing the status of a commit associated with '
375 msg = _('Changing the status of a commit associated with '
376 'a closed pull request is not allowed')
376 'a closed pull request is not allowed')
377 log.exception(msg)
377 log.exception(msg)
378 h.flash(msg, category='warning')
378 h.flash(msg, category='warning')
379 raise HTTPFound(h.route_path(
379 raise HTTPFound(h.route_path(
380 'repo_commit', repo_name=self.db_repo_name,
380 'repo_commit', repo_name=self.db_repo_name,
381 commit_id=current_id))
381 commit_id=current_id))
382
382
383 commit = self.db_repo.get_commit(current_id)
383 commit = self.db_repo.get_commit(current_id)
384 CommentsModel().trigger_commit_comment_hook(
384 CommentsModel().trigger_commit_comment_hook(
385 self.db_repo, self._rhodecode_user, 'create',
385 self.db_repo, self._rhodecode_user, 'create',
386 data={'comment': comment, 'commit': commit})
386 data={'comment': comment, 'commit': commit})
387
387
388 # finalize, commit and redirect
388 # finalize, commit and redirect
389 Session().commit()
389 Session().commit()
390
390
391 data = {
391 data = {
392 'target_id': h.safeid(h.safe_unicode(
392 'target_id': h.safeid(h.safe_unicode(
393 self.request.POST.get('f_path'))),
393 self.request.POST.get('f_path'))),
394 }
394 }
395 if comment:
395 if comment:
396 c.co = comment
396 c.co = comment
397 rendered_comment = render(
397 rendered_comment = render(
398 'rhodecode:templates/changeset/changeset_comment_block.mako',
398 'rhodecode:templates/changeset/changeset_comment_block.mako',
399 self._get_template_context(c), self.request)
399 self._get_template_context(c), self.request)
400
400
401 data.update(comment.get_dict())
401 data.update(comment.get_dict())
402 data.update({'rendered_text': rendered_comment})
402 data.update({'rendered_text': rendered_comment})
403
403
404 return data
404 return data
405
405
406 @LoginRequired()
406 @LoginRequired()
407 @NotAnonymous()
407 @NotAnonymous()
408 @HasRepoPermissionAnyDecorator(
408 @HasRepoPermissionAnyDecorator(
409 'repository.read', 'repository.write', 'repository.admin')
409 'repository.read', 'repository.write', 'repository.admin')
410 @CSRFRequired()
410 @CSRFRequired()
411 @view_config(
411 @view_config(
412 route_name='repo_commit_comment_preview', request_method='POST',
412 route_name='repo_commit_comment_preview', request_method='POST',
413 renderer='string', xhr=True)
413 renderer='string', xhr=True)
414 def repo_commit_comment_preview(self):
414 def repo_commit_comment_preview(self):
415 # Technically a CSRF token is not needed as no state changes with this
415 # Technically a CSRF token is not needed as no state changes with this
416 # call. However, as this is a POST is better to have it, so automated
416 # call. However, as this is a POST is better to have it, so automated
417 # tools don't flag it as potential CSRF.
417 # tools don't flag it as potential CSRF.
418 # Post is required because the payload could be bigger than the maximum
418 # Post is required because the payload could be bigger than the maximum
419 # allowed by GET.
419 # allowed by GET.
420
420
421 text = self.request.POST.get('text')
421 text = self.request.POST.get('text')
422 renderer = self.request.POST.get('renderer') or 'rst'
422 renderer = self.request.POST.get('renderer') or 'rst'
423 if text:
423 if text:
424 return h.render(text, renderer=renderer, mentions=True,
424 return h.render(text, renderer=renderer, mentions=True,
425 repo_name=self.db_repo_name)
425 repo_name=self.db_repo_name)
426 return ''
426 return ''
427
427
428 @LoginRequired()
428 @LoginRequired()
429 @NotAnonymous()
429 @NotAnonymous()
430 @HasRepoPermissionAnyDecorator(
430 @HasRepoPermissionAnyDecorator(
431 'repository.read', 'repository.write', 'repository.admin')
431 'repository.read', 'repository.write', 'repository.admin')
432 @CSRFRequired()
432 @CSRFRequired()
433 @view_config(
433 @view_config(
434 route_name='repo_commit_comment_attachment_upload', request_method='POST',
434 route_name='repo_commit_comment_attachment_upload', request_method='POST',
435 renderer='json_ext', xhr=True)
435 renderer='json_ext', xhr=True)
436 def repo_commit_comment_attachment_upload(self):
436 def repo_commit_comment_attachment_upload(self):
437 c = self.load_default_context()
437 c = self.load_default_context()
438 upload_key = 'attachment'
438 upload_key = 'attachment'
439
439
440 file_obj = self.request.POST.get(upload_key)
440 file_obj = self.request.POST.get(upload_key)
441
441
442 if file_obj is None:
442 if file_obj is None:
443 self.request.response.status = 400
443 self.request.response.status = 400
444 return {'store_fid': None,
444 return {'store_fid': None,
445 'access_path': None,
445 'access_path': None,
446 'error': '{} data field is missing'.format(upload_key)}
446 'error': '{} data field is missing'.format(upload_key)}
447
447
448 if not hasattr(file_obj, 'filename'):
448 if not hasattr(file_obj, 'filename'):
449 self.request.response.status = 400
449 self.request.response.status = 400
450 return {'store_fid': None,
450 return {'store_fid': None,
451 'access_path': None,
451 'access_path': None,
452 'error': 'filename cannot be read from the data field'}
452 'error': 'filename cannot be read from the data field'}
453
453
454 filename = file_obj.filename
454 filename = file_obj.filename
455 file_display_name = filename
455 file_display_name = filename
456
456
457 metadata = {
457 metadata = {
458 'user_uploaded': {'username': self._rhodecode_user.username,
458 'user_uploaded': {'username': self._rhodecode_user.username,
459 'user_id': self._rhodecode_user.user_id,
459 'user_id': self._rhodecode_user.user_id,
460 'ip': self._rhodecode_user.ip_addr}}
460 'ip': self._rhodecode_user.ip_addr}}
461
461
462 # TODO(marcink): allow .ini configuration for allowed_extensions, and file-size
462 # TODO(marcink): allow .ini configuration for allowed_extensions, and file-size
463 allowed_extensions = [
463 allowed_extensions = [
464 'gif', '.jpeg', '.jpg', '.png', '.docx', '.gz', '.log', '.pdf',
464 'gif', '.jpeg', '.jpg', '.png', '.docx', '.gz', '.log', '.pdf',
465 '.pptx', '.txt', '.xlsx', '.zip']
465 '.pptx', '.txt', '.xlsx', '.zip']
466 max_file_size = 10 * 1024 * 1024 # 10MB, also validated via dropzone.js
466 max_file_size = 10 * 1024 * 1024 # 10MB, also validated via dropzone.js
467
467
468 try:
468 try:
469 storage = store_utils.get_file_storage(self.request.registry.settings)
469 storage = store_utils.get_file_storage(self.request.registry.settings)
470 store_uid, metadata = storage.save_file(
470 store_uid, metadata = storage.save_file(
471 file_obj.file, filename, extra_metadata=metadata,
471 file_obj.file, filename, extra_metadata=metadata,
472 extensions=allowed_extensions, max_filesize=max_file_size)
472 extensions=allowed_extensions, max_filesize=max_file_size)
473 except FileNotAllowedException:
473 except FileNotAllowedException:
474 self.request.response.status = 400
474 self.request.response.status = 400
475 permitted_extensions = ', '.join(allowed_extensions)
475 permitted_extensions = ', '.join(allowed_extensions)
476 error_msg = 'File `{}` is not allowed. ' \
476 error_msg = 'File `{}` is not allowed. ' \
477 'Only following extensions are permitted: {}'.format(
477 'Only following extensions are permitted: {}'.format(
478 filename, permitted_extensions)
478 filename, permitted_extensions)
479 return {'store_fid': None,
479 return {'store_fid': None,
480 'access_path': None,
480 'access_path': None,
481 'error': error_msg}
481 'error': error_msg}
482 except FileOverSizeException:
482 except FileOverSizeException:
483 self.request.response.status = 400
483 self.request.response.status = 400
484 limit_mb = h.format_byte_size_binary(max_file_size)
484 limit_mb = h.format_byte_size_binary(max_file_size)
485 return {'store_fid': None,
485 return {'store_fid': None,
486 'access_path': None,
486 'access_path': None,
487 'error': 'File {} is exceeding allowed limit of {}.'.format(
487 'error': 'File {} is exceeding allowed limit of {}.'.format(
488 filename, limit_mb)}
488 filename, limit_mb)}
489
489
490 try:
490 try:
491 entry = FileStore.create(
491 entry = FileStore.create(
492 file_uid=store_uid, filename=metadata["filename"],
492 file_uid=store_uid, filename=metadata["filename"],
493 file_hash=metadata["sha256"], file_size=metadata["size"],
493 file_hash=metadata["sha256"], file_size=metadata["size"],
494 file_display_name=file_display_name,
494 file_display_name=file_display_name,
495 file_description=u'comment attachment `{}`'.format(safe_unicode(filename)),
495 file_description=u'comment attachment `{}`'.format(safe_unicode(filename)),
496 hidden=True, check_acl=True, user_id=self._rhodecode_user.user_id,
496 hidden=True, check_acl=True, user_id=self._rhodecode_user.user_id,
497 scope_repo_id=self.db_repo.repo_id
497 scope_repo_id=self.db_repo.repo_id
498 )
498 )
499 Session().add(entry)
499 Session().add(entry)
500 Session().commit()
500 Session().commit()
501 log.debug('Stored upload in DB as %s', entry)
501 log.debug('Stored upload in DB as %s', entry)
502 except Exception:
502 except Exception:
503 log.exception('Failed to store file %s', filename)
503 log.exception('Failed to store file %s', filename)
504 self.request.response.status = 400
504 self.request.response.status = 400
505 return {'store_fid': None,
505 return {'store_fid': None,
506 'access_path': None,
506 'access_path': None,
507 'error': 'File {} failed to store in DB.'.format(filename)}
507 'error': 'File {} failed to store in DB.'.format(filename)}
508
508
509 Session().commit()
509 Session().commit()
510
510
511 return {
511 return {
512 'store_fid': store_uid,
512 'store_fid': store_uid,
513 'access_path': h.route_path(
513 'access_path': h.route_path(
514 'download_file', fid=store_uid),
514 'download_file', fid=store_uid),
515 'fqn_access_path': h.route_url(
515 'fqn_access_path': h.route_url(
516 'download_file', fid=store_uid),
516 'download_file', fid=store_uid),
517 'repo_access_path': h.route_path(
517 'repo_access_path': h.route_path(
518 'repo_artifacts_get', repo_name=self.db_repo_name, uid=store_uid),
518 'repo_artifacts_get', repo_name=self.db_repo_name, uid=store_uid),
519 'repo_fqn_access_path': h.route_url(
519 'repo_fqn_access_path': h.route_url(
520 'repo_artifacts_get', repo_name=self.db_repo_name, uid=store_uid),
520 'repo_artifacts_get', repo_name=self.db_repo_name, uid=store_uid),
521 }
521 }
522
522
523 @LoginRequired()
523 @LoginRequired()
524 @NotAnonymous()
524 @NotAnonymous()
525 @HasRepoPermissionAnyDecorator(
525 @HasRepoPermissionAnyDecorator(
526 'repository.read', 'repository.write', 'repository.admin')
526 'repository.read', 'repository.write', 'repository.admin')
527 @CSRFRequired()
527 @CSRFRequired()
528 @view_config(
528 @view_config(
529 route_name='repo_commit_comment_delete', request_method='POST',
529 route_name='repo_commit_comment_delete', request_method='POST',
530 renderer='json_ext')
530 renderer='json_ext')
531 def repo_commit_comment_delete(self):
531 def repo_commit_comment_delete(self):
532 commit_id = self.request.matchdict['commit_id']
532 commit_id = self.request.matchdict['commit_id']
533 comment_id = self.request.matchdict['comment_id']
533 comment_id = self.request.matchdict['comment_id']
534
534
535 comment = ChangesetComment.get_or_404(comment_id)
535 comment = ChangesetComment.get_or_404(comment_id)
536 if not comment:
536 if not comment:
537 log.debug('Comment with id:%s not found, skipping', comment_id)
537 log.debug('Comment with id:%s not found, skipping', comment_id)
538 # comment already deleted in another call probably
538 # comment already deleted in another call probably
539 return True
539 return True
540
540
541 if comment.immutable:
542 # don't allow deleting comments that are immutable
543 raise HTTPForbidden()
544
541 is_repo_admin = h.HasRepoPermissionAny('repository.admin')(self.db_repo_name)
545 is_repo_admin = h.HasRepoPermissionAny('repository.admin')(self.db_repo_name)
542 super_admin = h.HasPermissionAny('hg.admin')()
546 super_admin = h.HasPermissionAny('hg.admin')()
543 comment_owner = (comment.author.user_id == self._rhodecode_db_user.user_id)
547 comment_owner = (comment.author.user_id == self._rhodecode_db_user.user_id)
544 is_repo_comment = comment.repo.repo_name == self.db_repo_name
548 is_repo_comment = comment.repo.repo_name == self.db_repo_name
545 comment_repo_admin = is_repo_admin and is_repo_comment
549 comment_repo_admin = is_repo_admin and is_repo_comment
546
550
547 if super_admin or comment_owner or comment_repo_admin:
551 if super_admin or comment_owner or comment_repo_admin:
548 CommentsModel().delete(comment=comment, auth_user=self._rhodecode_user)
552 CommentsModel().delete(comment=comment, auth_user=self._rhodecode_user)
549 Session().commit()
553 Session().commit()
550 return True
554 return True
551 else:
555 else:
552 log.warning('No permissions for user %s to delete comment_id: %s',
556 log.warning('No permissions for user %s to delete comment_id: %s',
553 self._rhodecode_db_user, comment_id)
557 self._rhodecode_db_user, comment_id)
554 raise HTTPNotFound()
558 raise HTTPNotFound()
555
559
556 @LoginRequired()
560 @LoginRequired()
557 @HasRepoPermissionAnyDecorator(
561 @HasRepoPermissionAnyDecorator(
558 'repository.read', 'repository.write', 'repository.admin')
562 'repository.read', 'repository.write', 'repository.admin')
559 @view_config(
563 @view_config(
560 route_name='repo_commit_data', request_method='GET',
564 route_name='repo_commit_data', request_method='GET',
561 renderer='json_ext', xhr=True)
565 renderer='json_ext', xhr=True)
562 def repo_commit_data(self):
566 def repo_commit_data(self):
563 commit_id = self.request.matchdict['commit_id']
567 commit_id = self.request.matchdict['commit_id']
564 self.load_default_context()
568 self.load_default_context()
565
569
566 try:
570 try:
567 return self.rhodecode_vcs_repo.get_commit(commit_id=commit_id)
571 return self.rhodecode_vcs_repo.get_commit(commit_id=commit_id)
568 except CommitDoesNotExistError as e:
572 except CommitDoesNotExistError as e:
569 return EmptyCommit(message=str(e))
573 return EmptyCommit(message=str(e))
570
574
571 @LoginRequired()
575 @LoginRequired()
572 @HasRepoPermissionAnyDecorator(
576 @HasRepoPermissionAnyDecorator(
573 'repository.read', 'repository.write', 'repository.admin')
577 'repository.read', 'repository.write', 'repository.admin')
574 @view_config(
578 @view_config(
575 route_name='repo_commit_children', request_method='GET',
579 route_name='repo_commit_children', request_method='GET',
576 renderer='json_ext', xhr=True)
580 renderer='json_ext', xhr=True)
577 def repo_commit_children(self):
581 def repo_commit_children(self):
578 commit_id = self.request.matchdict['commit_id']
582 commit_id = self.request.matchdict['commit_id']
579 self.load_default_context()
583 self.load_default_context()
580
584
581 try:
585 try:
582 commit = self.rhodecode_vcs_repo.get_commit(commit_id=commit_id)
586 commit = self.rhodecode_vcs_repo.get_commit(commit_id=commit_id)
583 children = commit.children
587 children = commit.children
584 except CommitDoesNotExistError:
588 except CommitDoesNotExistError:
585 children = []
589 children = []
586
590
587 result = {"results": children}
591 result = {"results": children}
588 return result
592 return result
589
593
590 @LoginRequired()
594 @LoginRequired()
591 @HasRepoPermissionAnyDecorator(
595 @HasRepoPermissionAnyDecorator(
592 'repository.read', 'repository.write', 'repository.admin')
596 'repository.read', 'repository.write', 'repository.admin')
593 @view_config(
597 @view_config(
594 route_name='repo_commit_parents', request_method='GET',
598 route_name='repo_commit_parents', request_method='GET',
595 renderer='json_ext')
599 renderer='json_ext')
596 def repo_commit_parents(self):
600 def repo_commit_parents(self):
597 commit_id = self.request.matchdict['commit_id']
601 commit_id = self.request.matchdict['commit_id']
598 self.load_default_context()
602 self.load_default_context()
599
603
600 try:
604 try:
601 commit = self.rhodecode_vcs_repo.get_commit(commit_id=commit_id)
605 commit = self.rhodecode_vcs_repo.get_commit(commit_id=commit_id)
602 parents = commit.parents
606 parents = commit.parents
603 except CommitDoesNotExistError:
607 except CommitDoesNotExistError:
604 parents = []
608 parents = []
605 result = {"results": parents}
609 result = {"results": parents}
606 return result
610 return result
@@ -1,1508 +1,1512 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2020 RhodeCode GmbH
3 # Copyright (C) 2011-2020 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.apps._base import RepoAppView, DataGridAppView
32 from rhodecode.apps._base import RepoAppView, DataGridAppView
33
33
34 from rhodecode.lib import helpers as h, diffs, codeblocks, channelstream
34 from rhodecode.lib import helpers as h, diffs, codeblocks, channelstream
35 from rhodecode.lib.base import vcs_operation_context
35 from rhodecode.lib.base import vcs_operation_context
36 from rhodecode.lib.diffs import load_cached_diff, cache_diff, diff_cache_exist
36 from rhodecode.lib.diffs import load_cached_diff, cache_diff, diff_cache_exist
37 from rhodecode.lib.ext_json import json
37 from rhodecode.lib.ext_json import json
38 from rhodecode.lib.auth import (
38 from rhodecode.lib.auth import (
39 LoginRequired, HasRepoPermissionAny, HasRepoPermissionAnyDecorator,
39 LoginRequired, HasRepoPermissionAny, HasRepoPermissionAnyDecorator,
40 NotAnonymous, CSRFRequired)
40 NotAnonymous, CSRFRequired)
41 from rhodecode.lib.utils2 import str2bool, safe_str, safe_unicode
41 from rhodecode.lib.utils2 import str2bool, safe_str, safe_unicode
42 from rhodecode.lib.vcs.backends.base import EmptyCommit, UpdateFailureReason
42 from rhodecode.lib.vcs.backends.base import EmptyCommit, UpdateFailureReason
43 from rhodecode.lib.vcs.exceptions import (CommitDoesNotExistError,
43 from rhodecode.lib.vcs.exceptions import (CommitDoesNotExistError,
44 RepositoryRequirementError, EmptyRepositoryError)
44 RepositoryRequirementError, EmptyRepositoryError)
45 from rhodecode.model.changeset_status import ChangesetStatusModel
45 from rhodecode.model.changeset_status import ChangesetStatusModel
46 from rhodecode.model.comment import CommentsModel
46 from rhodecode.model.comment import CommentsModel
47 from rhodecode.model.db import (func, or_, PullRequest, PullRequestVersion,
47 from rhodecode.model.db import (func, or_, PullRequest, PullRequestVersion,
48 ChangesetComment, ChangesetStatus, Repository)
48 ChangesetComment, ChangesetStatus, Repository)
49 from rhodecode.model.forms import PullRequestForm
49 from rhodecode.model.forms import PullRequestForm
50 from rhodecode.model.meta import Session
50 from rhodecode.model.meta import Session
51 from rhodecode.model.pull_request import PullRequestModel, MergeCheck
51 from rhodecode.model.pull_request import PullRequestModel, MergeCheck
52 from rhodecode.model.scm import ScmModel
52 from rhodecode.model.scm import ScmModel
53
53
54 log = logging.getLogger(__name__)
54 log = logging.getLogger(__name__)
55
55
56
56
57 class RepoPullRequestsView(RepoAppView, DataGridAppView):
57 class RepoPullRequestsView(RepoAppView, DataGridAppView):
58
58
59 def load_default_context(self):
59 def load_default_context(self):
60 c = self._get_local_tmpl_context(include_app_defaults=True)
60 c = self._get_local_tmpl_context(include_app_defaults=True)
61 c.REVIEW_STATUS_APPROVED = ChangesetStatus.STATUS_APPROVED
61 c.REVIEW_STATUS_APPROVED = ChangesetStatus.STATUS_APPROVED
62 c.REVIEW_STATUS_REJECTED = ChangesetStatus.STATUS_REJECTED
62 c.REVIEW_STATUS_REJECTED = ChangesetStatus.STATUS_REJECTED
63 # backward compat., we use for OLD PRs a plain renderer
63 # backward compat., we use for OLD PRs a plain renderer
64 c.renderer = 'plain'
64 c.renderer = 'plain'
65 return c
65 return c
66
66
67 def _get_pull_requests_list(
67 def _get_pull_requests_list(
68 self, repo_name, source, filter_type, opened_by, statuses):
68 self, repo_name, source, filter_type, opened_by, statuses):
69
69
70 draw, start, limit = self._extract_chunk(self.request)
70 draw, start, limit = self._extract_chunk(self.request)
71 search_q, order_by, order_dir = self._extract_ordering(self.request)
71 search_q, order_by, order_dir = self._extract_ordering(self.request)
72 _render = self.request.get_partial_renderer(
72 _render = self.request.get_partial_renderer(
73 'rhodecode:templates/data_table/_dt_elements.mako')
73 'rhodecode:templates/data_table/_dt_elements.mako')
74
74
75 # pagination
75 # pagination
76
76
77 if filter_type == 'awaiting_review':
77 if filter_type == 'awaiting_review':
78 pull_requests = PullRequestModel().get_awaiting_review(
78 pull_requests = PullRequestModel().get_awaiting_review(
79 repo_name, search_q=search_q, source=source, opened_by=opened_by,
79 repo_name, search_q=search_q, source=source, opened_by=opened_by,
80 statuses=statuses, offset=start, length=limit,
80 statuses=statuses, offset=start, length=limit,
81 order_by=order_by, order_dir=order_dir)
81 order_by=order_by, order_dir=order_dir)
82 pull_requests_total_count = PullRequestModel().count_awaiting_review(
82 pull_requests_total_count = PullRequestModel().count_awaiting_review(
83 repo_name, search_q=search_q, source=source, statuses=statuses,
83 repo_name, search_q=search_q, source=source, statuses=statuses,
84 opened_by=opened_by)
84 opened_by=opened_by)
85 elif filter_type == 'awaiting_my_review':
85 elif filter_type == 'awaiting_my_review':
86 pull_requests = PullRequestModel().get_awaiting_my_review(
86 pull_requests = PullRequestModel().get_awaiting_my_review(
87 repo_name, search_q=search_q, source=source, opened_by=opened_by,
87 repo_name, search_q=search_q, source=source, opened_by=opened_by,
88 user_id=self._rhodecode_user.user_id, statuses=statuses,
88 user_id=self._rhodecode_user.user_id, statuses=statuses,
89 offset=start, length=limit, order_by=order_by,
89 offset=start, length=limit, order_by=order_by,
90 order_dir=order_dir)
90 order_dir=order_dir)
91 pull_requests_total_count = PullRequestModel().count_awaiting_my_review(
91 pull_requests_total_count = PullRequestModel().count_awaiting_my_review(
92 repo_name, search_q=search_q, source=source, user_id=self._rhodecode_user.user_id,
92 repo_name, search_q=search_q, source=source, user_id=self._rhodecode_user.user_id,
93 statuses=statuses, opened_by=opened_by)
93 statuses=statuses, opened_by=opened_by)
94 else:
94 else:
95 pull_requests = PullRequestModel().get_all(
95 pull_requests = PullRequestModel().get_all(
96 repo_name, search_q=search_q, source=source, opened_by=opened_by,
96 repo_name, search_q=search_q, source=source, opened_by=opened_by,
97 statuses=statuses, offset=start, length=limit,
97 statuses=statuses, offset=start, length=limit,
98 order_by=order_by, order_dir=order_dir)
98 order_by=order_by, order_dir=order_dir)
99 pull_requests_total_count = PullRequestModel().count_all(
99 pull_requests_total_count = PullRequestModel().count_all(
100 repo_name, search_q=search_q, source=source, statuses=statuses,
100 repo_name, search_q=search_q, source=source, statuses=statuses,
101 opened_by=opened_by)
101 opened_by=opened_by)
102
102
103 data = []
103 data = []
104 comments_model = CommentsModel()
104 comments_model = CommentsModel()
105 for pr in pull_requests:
105 for pr in pull_requests:
106 comments = comments_model.get_all_comments(
106 comments = comments_model.get_all_comments(
107 self.db_repo.repo_id, pull_request=pr)
107 self.db_repo.repo_id, pull_request=pr)
108
108
109 data.append({
109 data.append({
110 'name': _render('pullrequest_name',
110 'name': _render('pullrequest_name',
111 pr.pull_request_id, pr.pull_request_state,
111 pr.pull_request_id, pr.pull_request_state,
112 pr.work_in_progress, pr.target_repo.repo_name),
112 pr.work_in_progress, 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('pullrequest_title', pr.title, pr.description),
116 'title': _render('pullrequest_title', pr.title, pr.description),
117 'description': h.escape(pr.description),
117 'description': h.escape(pr.description),
118 'updated_on': _render('pullrequest_updated_on',
118 'updated_on': _render('pullrequest_updated_on',
119 h.datetime_to_time(pr.updated_on)),
119 h.datetime_to_time(pr.updated_on)),
120 'updated_on_raw': h.datetime_to_time(pr.updated_on),
120 'updated_on_raw': h.datetime_to_time(pr.updated_on),
121 'created_on': _render('pullrequest_updated_on',
121 'created_on': _render('pullrequest_updated_on',
122 h.datetime_to_time(pr.created_on)),
122 h.datetime_to_time(pr.created_on)),
123 'created_on_raw': h.datetime_to_time(pr.created_on),
123 'created_on_raw': h.datetime_to_time(pr.created_on),
124 'state': pr.pull_request_state,
124 'state': pr.pull_request_state,
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 @LoginRequired()
141 @LoginRequired()
142 @HasRepoPermissionAnyDecorator(
142 @HasRepoPermissionAnyDecorator(
143 'repository.read', 'repository.write', 'repository.admin')
143 'repository.read', 'repository.write', 'repository.admin')
144 @view_config(
144 @view_config(
145 route_name='pullrequest_show_all', request_method='GET',
145 route_name='pullrequest_show_all', request_method='GET',
146 renderer='rhodecode:templates/pullrequests/pullrequests.mako')
146 renderer='rhodecode:templates/pullrequests/pullrequests.mako')
147 def pull_request_list(self):
147 def pull_request_list(self):
148 c = self.load_default_context()
148 c = self.load_default_context()
149
149
150 req_get = self.request.GET
150 req_get = self.request.GET
151 c.source = str2bool(req_get.get('source'))
151 c.source = str2bool(req_get.get('source'))
152 c.closed = str2bool(req_get.get('closed'))
152 c.closed = str2bool(req_get.get('closed'))
153 c.my = str2bool(req_get.get('my'))
153 c.my = str2bool(req_get.get('my'))
154 c.awaiting_review = str2bool(req_get.get('awaiting_review'))
154 c.awaiting_review = str2bool(req_get.get('awaiting_review'))
155 c.awaiting_my_review = str2bool(req_get.get('awaiting_my_review'))
155 c.awaiting_my_review = str2bool(req_get.get('awaiting_my_review'))
156
156
157 c.active = 'open'
157 c.active = 'open'
158 if c.my:
158 if c.my:
159 c.active = 'my'
159 c.active = 'my'
160 if c.closed:
160 if c.closed:
161 c.active = 'closed'
161 c.active = 'closed'
162 if c.awaiting_review and not c.source:
162 if c.awaiting_review and not c.source:
163 c.active = 'awaiting'
163 c.active = 'awaiting'
164 if c.source and not c.awaiting_review:
164 if c.source and not c.awaiting_review:
165 c.active = 'source'
165 c.active = 'source'
166 if c.awaiting_my_review:
166 if c.awaiting_my_review:
167 c.active = 'awaiting_my'
167 c.active = 'awaiting_my'
168
168
169 return self._get_template_context(c)
169 return self._get_template_context(c)
170
170
171 @LoginRequired()
171 @LoginRequired()
172 @HasRepoPermissionAnyDecorator(
172 @HasRepoPermissionAnyDecorator(
173 'repository.read', 'repository.write', 'repository.admin')
173 'repository.read', 'repository.write', 'repository.admin')
174 @view_config(
174 @view_config(
175 route_name='pullrequest_show_all_data', request_method='GET',
175 route_name='pullrequest_show_all_data', request_method='GET',
176 renderer='json_ext', xhr=True)
176 renderer='json_ext', xhr=True)
177 def pull_request_list_data(self):
177 def pull_request_list_data(self):
178 self.load_default_context()
178 self.load_default_context()
179
179
180 # additional filters
180 # additional filters
181 req_get = self.request.GET
181 req_get = self.request.GET
182 source = str2bool(req_get.get('source'))
182 source = str2bool(req_get.get('source'))
183 closed = str2bool(req_get.get('closed'))
183 closed = str2bool(req_get.get('closed'))
184 my = str2bool(req_get.get('my'))
184 my = str2bool(req_get.get('my'))
185 awaiting_review = str2bool(req_get.get('awaiting_review'))
185 awaiting_review = str2bool(req_get.get('awaiting_review'))
186 awaiting_my_review = str2bool(req_get.get('awaiting_my_review'))
186 awaiting_my_review = str2bool(req_get.get('awaiting_my_review'))
187
187
188 filter_type = 'awaiting_review' if awaiting_review \
188 filter_type = 'awaiting_review' if awaiting_review \
189 else 'awaiting_my_review' if awaiting_my_review \
189 else 'awaiting_my_review' if awaiting_my_review \
190 else None
190 else None
191
191
192 opened_by = None
192 opened_by = None
193 if my:
193 if my:
194 opened_by = [self._rhodecode_user.user_id]
194 opened_by = [self._rhodecode_user.user_id]
195
195
196 statuses = [PullRequest.STATUS_NEW, PullRequest.STATUS_OPEN]
196 statuses = [PullRequest.STATUS_NEW, PullRequest.STATUS_OPEN]
197 if closed:
197 if closed:
198 statuses = [PullRequest.STATUS_CLOSED]
198 statuses = [PullRequest.STATUS_CLOSED]
199
199
200 data = self._get_pull_requests_list(
200 data = self._get_pull_requests_list(
201 repo_name=self.db_repo_name, source=source,
201 repo_name=self.db_repo_name, source=source,
202 filter_type=filter_type, opened_by=opened_by, statuses=statuses)
202 filter_type=filter_type, opened_by=opened_by, statuses=statuses)
203
203
204 return data
204 return data
205
205
206 def _is_diff_cache_enabled(self, target_repo):
206 def _is_diff_cache_enabled(self, target_repo):
207 caching_enabled = self._get_general_setting(
207 caching_enabled = self._get_general_setting(
208 target_repo, 'rhodecode_diff_cache')
208 target_repo, 'rhodecode_diff_cache')
209 log.debug('Diff caching enabled: %s', caching_enabled)
209 log.debug('Diff caching enabled: %s', caching_enabled)
210 return caching_enabled
210 return caching_enabled
211
211
212 def _get_diffset(self, source_repo_name, source_repo,
212 def _get_diffset(self, source_repo_name, source_repo,
213 source_ref_id, target_ref_id,
213 source_ref_id, target_ref_id,
214 target_commit, source_commit, diff_limit, file_limit,
214 target_commit, source_commit, diff_limit, file_limit,
215 fulldiff, hide_whitespace_changes, diff_context):
215 fulldiff, hide_whitespace_changes, diff_context):
216
216
217 vcs_diff = PullRequestModel().get_diff(
217 vcs_diff = PullRequestModel().get_diff(
218 source_repo, source_ref_id, target_ref_id,
218 source_repo, source_ref_id, target_ref_id,
219 hide_whitespace_changes, diff_context)
219 hide_whitespace_changes, diff_context)
220
220
221 diff_processor = diffs.DiffProcessor(
221 diff_processor = diffs.DiffProcessor(
222 vcs_diff, format='newdiff', diff_limit=diff_limit,
222 vcs_diff, format='newdiff', diff_limit=diff_limit,
223 file_limit=file_limit, show_full_diff=fulldiff)
223 file_limit=file_limit, show_full_diff=fulldiff)
224
224
225 _parsed = diff_processor.prepare()
225 _parsed = diff_processor.prepare()
226
226
227 diffset = codeblocks.DiffSet(
227 diffset = codeblocks.DiffSet(
228 repo_name=self.db_repo_name,
228 repo_name=self.db_repo_name,
229 source_repo_name=source_repo_name,
229 source_repo_name=source_repo_name,
230 source_node_getter=codeblocks.diffset_node_getter(target_commit),
230 source_node_getter=codeblocks.diffset_node_getter(target_commit),
231 target_node_getter=codeblocks.diffset_node_getter(source_commit),
231 target_node_getter=codeblocks.diffset_node_getter(source_commit),
232 )
232 )
233 diffset = self.path_filter.render_patchset_filtered(
233 diffset = self.path_filter.render_patchset_filtered(
234 diffset, _parsed, target_commit.raw_id, source_commit.raw_id)
234 diffset, _parsed, target_commit.raw_id, source_commit.raw_id)
235
235
236 return diffset
236 return diffset
237
237
238 def _get_range_diffset(self, source_scm, source_repo,
238 def _get_range_diffset(self, source_scm, source_repo,
239 commit1, commit2, diff_limit, file_limit,
239 commit1, commit2, diff_limit, file_limit,
240 fulldiff, hide_whitespace_changes, diff_context):
240 fulldiff, hide_whitespace_changes, diff_context):
241 vcs_diff = source_scm.get_diff(
241 vcs_diff = source_scm.get_diff(
242 commit1, commit2,
242 commit1, commit2,
243 ignore_whitespace=hide_whitespace_changes,
243 ignore_whitespace=hide_whitespace_changes,
244 context=diff_context)
244 context=diff_context)
245
245
246 diff_processor = diffs.DiffProcessor(
246 diff_processor = diffs.DiffProcessor(
247 vcs_diff, format='newdiff', diff_limit=diff_limit,
247 vcs_diff, format='newdiff', diff_limit=diff_limit,
248 file_limit=file_limit, show_full_diff=fulldiff)
248 file_limit=file_limit, show_full_diff=fulldiff)
249
249
250 _parsed = diff_processor.prepare()
250 _parsed = diff_processor.prepare()
251
251
252 diffset = codeblocks.DiffSet(
252 diffset = codeblocks.DiffSet(
253 repo_name=source_repo.repo_name,
253 repo_name=source_repo.repo_name,
254 source_node_getter=codeblocks.diffset_node_getter(commit1),
254 source_node_getter=codeblocks.diffset_node_getter(commit1),
255 target_node_getter=codeblocks.diffset_node_getter(commit2))
255 target_node_getter=codeblocks.diffset_node_getter(commit2))
256
256
257 diffset = self.path_filter.render_patchset_filtered(
257 diffset = self.path_filter.render_patchset_filtered(
258 diffset, _parsed, commit1.raw_id, commit2.raw_id)
258 diffset, _parsed, commit1.raw_id, commit2.raw_id)
259
259
260 return diffset
260 return diffset
261
261
262 @LoginRequired()
262 @LoginRequired()
263 @HasRepoPermissionAnyDecorator(
263 @HasRepoPermissionAnyDecorator(
264 'repository.read', 'repository.write', 'repository.admin')
264 'repository.read', 'repository.write', 'repository.admin')
265 @view_config(
265 @view_config(
266 route_name='pullrequest_show', request_method='GET',
266 route_name='pullrequest_show', request_method='GET',
267 renderer='rhodecode:templates/pullrequests/pullrequest_show.mako')
267 renderer='rhodecode:templates/pullrequests/pullrequest_show.mako')
268 def pull_request_show(self):
268 def pull_request_show(self):
269 _ = self.request.translate
269 _ = self.request.translate
270 c = self.load_default_context()
270 c = self.load_default_context()
271
271
272 pull_request = PullRequest.get_or_404(
272 pull_request = PullRequest.get_or_404(
273 self.request.matchdict['pull_request_id'])
273 self.request.matchdict['pull_request_id'])
274 pull_request_id = pull_request.pull_request_id
274 pull_request_id = pull_request.pull_request_id
275
275
276 c.state_progressing = pull_request.is_state_changing()
276 c.state_progressing = pull_request.is_state_changing()
277
277
278 _new_state = {
278 _new_state = {
279 'created': PullRequest.STATE_CREATED,
279 'created': PullRequest.STATE_CREATED,
280 }.get(self.request.GET.get('force_state'))
280 }.get(self.request.GET.get('force_state'))
281 if c.is_super_admin and _new_state:
281 if c.is_super_admin and _new_state:
282 with pull_request.set_state(PullRequest.STATE_UPDATING, final_state=_new_state):
282 with pull_request.set_state(PullRequest.STATE_UPDATING, final_state=_new_state):
283 h.flash(
283 h.flash(
284 _('Pull Request state was force changed to `{}`').format(_new_state),
284 _('Pull Request state was force changed to `{}`').format(_new_state),
285 category='success')
285 category='success')
286 Session().commit()
286 Session().commit()
287
287
288 raise HTTPFound(h.route_path(
288 raise HTTPFound(h.route_path(
289 'pullrequest_show', repo_name=self.db_repo_name,
289 'pullrequest_show', repo_name=self.db_repo_name,
290 pull_request_id=pull_request_id))
290 pull_request_id=pull_request_id))
291
291
292 version = self.request.GET.get('version')
292 version = self.request.GET.get('version')
293 from_version = self.request.GET.get('from_version') or version
293 from_version = self.request.GET.get('from_version') or version
294 merge_checks = self.request.GET.get('merge_checks')
294 merge_checks = self.request.GET.get('merge_checks')
295 c.fulldiff = str2bool(self.request.GET.get('fulldiff'))
295 c.fulldiff = str2bool(self.request.GET.get('fulldiff'))
296
296
297 # fetch global flags of ignore ws or context lines
297 # fetch global flags of ignore ws or context lines
298 diff_context = diffs.get_diff_context(self.request)
298 diff_context = diffs.get_diff_context(self.request)
299 hide_whitespace_changes = diffs.get_diff_whitespace_flag(self.request)
299 hide_whitespace_changes = diffs.get_diff_whitespace_flag(self.request)
300
300
301 force_refresh = str2bool(self.request.GET.get('force_refresh'))
301 force_refresh = str2bool(self.request.GET.get('force_refresh'))
302
302
303 (pull_request_latest,
303 (pull_request_latest,
304 pull_request_at_ver,
304 pull_request_at_ver,
305 pull_request_display_obj,
305 pull_request_display_obj,
306 at_version) = PullRequestModel().get_pr_version(
306 at_version) = PullRequestModel().get_pr_version(
307 pull_request_id, version=version)
307 pull_request_id, version=version)
308 pr_closed = pull_request_latest.is_closed()
308 pr_closed = pull_request_latest.is_closed()
309
309
310 if pr_closed and (version or from_version):
310 if pr_closed and (version or from_version):
311 # not allow to browse versions
311 # not allow to browse versions
312 raise HTTPFound(h.route_path(
312 raise HTTPFound(h.route_path(
313 'pullrequest_show', repo_name=self.db_repo_name,
313 'pullrequest_show', repo_name=self.db_repo_name,
314 pull_request_id=pull_request_id))
314 pull_request_id=pull_request_id))
315
315
316 versions = pull_request_display_obj.versions()
316 versions = pull_request_display_obj.versions()
317 # used to store per-commit range diffs
317 # used to store per-commit range diffs
318 c.changes = collections.OrderedDict()
318 c.changes = collections.OrderedDict()
319 c.range_diff_on = self.request.GET.get('range-diff') == "1"
319 c.range_diff_on = self.request.GET.get('range-diff') == "1"
320
320
321 c.at_version = at_version
321 c.at_version = at_version
322 c.at_version_num = (at_version
322 c.at_version_num = (at_version
323 if at_version and at_version != 'latest'
323 if at_version and at_version != 'latest'
324 else None)
324 else None)
325 c.at_version_pos = ChangesetComment.get_index_from_version(
325 c.at_version_pos = ChangesetComment.get_index_from_version(
326 c.at_version_num, versions)
326 c.at_version_num, versions)
327
327
328 (prev_pull_request_latest,
328 (prev_pull_request_latest,
329 prev_pull_request_at_ver,
329 prev_pull_request_at_ver,
330 prev_pull_request_display_obj,
330 prev_pull_request_display_obj,
331 prev_at_version) = PullRequestModel().get_pr_version(
331 prev_at_version) = PullRequestModel().get_pr_version(
332 pull_request_id, version=from_version)
332 pull_request_id, version=from_version)
333
333
334 c.from_version = prev_at_version
334 c.from_version = prev_at_version
335 c.from_version_num = (prev_at_version
335 c.from_version_num = (prev_at_version
336 if prev_at_version and prev_at_version != 'latest'
336 if prev_at_version and prev_at_version != 'latest'
337 else None)
337 else None)
338 c.from_version_pos = ChangesetComment.get_index_from_version(
338 c.from_version_pos = ChangesetComment.get_index_from_version(
339 c.from_version_num, versions)
339 c.from_version_num, versions)
340
340
341 # define if we're in COMPARE mode or VIEW at version mode
341 # define if we're in COMPARE mode or VIEW at version mode
342 compare = at_version != prev_at_version
342 compare = at_version != prev_at_version
343
343
344 # pull_requests repo_name we opened it against
344 # pull_requests repo_name we opened it against
345 # ie. target_repo must match
345 # ie. target_repo must match
346 if self.db_repo_name != pull_request_at_ver.target_repo.repo_name:
346 if self.db_repo_name != pull_request_at_ver.target_repo.repo_name:
347 raise HTTPNotFound()
347 raise HTTPNotFound()
348
348
349 c.shadow_clone_url = PullRequestModel().get_shadow_clone_url(
349 c.shadow_clone_url = PullRequestModel().get_shadow_clone_url(
350 pull_request_at_ver)
350 pull_request_at_ver)
351
351
352 c.pull_request = pull_request_display_obj
352 c.pull_request = pull_request_display_obj
353 c.renderer = pull_request_at_ver.description_renderer or c.renderer
353 c.renderer = pull_request_at_ver.description_renderer or c.renderer
354 c.pull_request_latest = pull_request_latest
354 c.pull_request_latest = pull_request_latest
355
355
356 if compare or (at_version and not at_version == 'latest'):
356 if compare or (at_version and not at_version == 'latest'):
357 c.allowed_to_change_status = False
357 c.allowed_to_change_status = False
358 c.allowed_to_update = False
358 c.allowed_to_update = False
359 c.allowed_to_merge = False
359 c.allowed_to_merge = False
360 c.allowed_to_delete = False
360 c.allowed_to_delete = False
361 c.allowed_to_comment = False
361 c.allowed_to_comment = False
362 c.allowed_to_close = False
362 c.allowed_to_close = False
363 else:
363 else:
364 can_change_status = PullRequestModel().check_user_change_status(
364 can_change_status = PullRequestModel().check_user_change_status(
365 pull_request_at_ver, self._rhodecode_user)
365 pull_request_at_ver, self._rhodecode_user)
366 c.allowed_to_change_status = can_change_status and not pr_closed
366 c.allowed_to_change_status = can_change_status and not pr_closed
367
367
368 c.allowed_to_update = PullRequestModel().check_user_update(
368 c.allowed_to_update = PullRequestModel().check_user_update(
369 pull_request_latest, self._rhodecode_user) and not pr_closed
369 pull_request_latest, self._rhodecode_user) and not pr_closed
370 c.allowed_to_merge = PullRequestModel().check_user_merge(
370 c.allowed_to_merge = PullRequestModel().check_user_merge(
371 pull_request_latest, self._rhodecode_user) and not pr_closed
371 pull_request_latest, self._rhodecode_user) and not pr_closed
372 c.allowed_to_delete = PullRequestModel().check_user_delete(
372 c.allowed_to_delete = PullRequestModel().check_user_delete(
373 pull_request_latest, self._rhodecode_user) and not pr_closed
373 pull_request_latest, self._rhodecode_user) and not pr_closed
374 c.allowed_to_comment = not pr_closed
374 c.allowed_to_comment = not pr_closed
375 c.allowed_to_close = c.allowed_to_merge and not pr_closed
375 c.allowed_to_close = c.allowed_to_merge and not pr_closed
376
376
377 c.forbid_adding_reviewers = False
377 c.forbid_adding_reviewers = False
378 c.forbid_author_to_review = False
378 c.forbid_author_to_review = False
379 c.forbid_commit_author_to_review = False
379 c.forbid_commit_author_to_review = False
380
380
381 if pull_request_latest.reviewer_data and \
381 if pull_request_latest.reviewer_data and \
382 'rules' in pull_request_latest.reviewer_data:
382 'rules' in pull_request_latest.reviewer_data:
383 rules = pull_request_latest.reviewer_data['rules'] or {}
383 rules = pull_request_latest.reviewer_data['rules'] or {}
384 try:
384 try:
385 c.forbid_adding_reviewers = rules.get(
385 c.forbid_adding_reviewers = rules.get(
386 'forbid_adding_reviewers')
386 'forbid_adding_reviewers')
387 c.forbid_author_to_review = rules.get(
387 c.forbid_author_to_review = rules.get(
388 'forbid_author_to_review')
388 'forbid_author_to_review')
389 c.forbid_commit_author_to_review = rules.get(
389 c.forbid_commit_author_to_review = rules.get(
390 'forbid_commit_author_to_review')
390 'forbid_commit_author_to_review')
391 except Exception:
391 except Exception:
392 pass
392 pass
393
393
394 # check merge capabilities
394 # check merge capabilities
395 _merge_check = MergeCheck.validate(
395 _merge_check = MergeCheck.validate(
396 pull_request_latest, auth_user=self._rhodecode_user,
396 pull_request_latest, auth_user=self._rhodecode_user,
397 translator=self.request.translate,
397 translator=self.request.translate,
398 force_shadow_repo_refresh=force_refresh)
398 force_shadow_repo_refresh=force_refresh)
399
399
400 c.pr_merge_errors = _merge_check.error_details
400 c.pr_merge_errors = _merge_check.error_details
401 c.pr_merge_possible = not _merge_check.failed
401 c.pr_merge_possible = not _merge_check.failed
402 c.pr_merge_message = _merge_check.merge_msg
402 c.pr_merge_message = _merge_check.merge_msg
403 c.pr_merge_source_commit = _merge_check.source_commit
403 c.pr_merge_source_commit = _merge_check.source_commit
404 c.pr_merge_target_commit = _merge_check.target_commit
404 c.pr_merge_target_commit = _merge_check.target_commit
405
405
406 c.pr_merge_info = MergeCheck.get_merge_conditions(
406 c.pr_merge_info = MergeCheck.get_merge_conditions(
407 pull_request_latest, translator=self.request.translate)
407 pull_request_latest, translator=self.request.translate)
408
408
409 c.pull_request_review_status = _merge_check.review_status
409 c.pull_request_review_status = _merge_check.review_status
410 if merge_checks:
410 if merge_checks:
411 self.request.override_renderer = \
411 self.request.override_renderer = \
412 'rhodecode:templates/pullrequests/pullrequest_merge_checks.mako'
412 'rhodecode:templates/pullrequests/pullrequest_merge_checks.mako'
413 return self._get_template_context(c)
413 return self._get_template_context(c)
414
414
415 comments_model = CommentsModel()
415 comments_model = CommentsModel()
416
416
417 # reviewers and statuses
417 # reviewers and statuses
418 c.pull_request_reviewers = pull_request_at_ver.reviewers_statuses()
418 c.pull_request_reviewers = pull_request_at_ver.reviewers_statuses()
419 allowed_reviewers = [x[0].user_id for x in c.pull_request_reviewers]
419 allowed_reviewers = [x[0].user_id for x in c.pull_request_reviewers]
420
420
421 # GENERAL COMMENTS with versions #
421 # GENERAL COMMENTS with versions #
422 q = comments_model._all_general_comments_of_pull_request(pull_request_latest)
422 q = comments_model._all_general_comments_of_pull_request(pull_request_latest)
423 q = q.order_by(ChangesetComment.comment_id.asc())
423 q = q.order_by(ChangesetComment.comment_id.asc())
424 general_comments = q
424 general_comments = q
425
425
426 # pick comments we want to render at current version
426 # pick comments we want to render at current version
427 c.comment_versions = comments_model.aggregate_comments(
427 c.comment_versions = comments_model.aggregate_comments(
428 general_comments, versions, c.at_version_num)
428 general_comments, versions, c.at_version_num)
429 c.comments = c.comment_versions[c.at_version_num]['until']
429 c.comments = c.comment_versions[c.at_version_num]['until']
430
430
431 # INLINE COMMENTS with versions #
431 # INLINE COMMENTS with versions #
432 q = comments_model._all_inline_comments_of_pull_request(pull_request_latest)
432 q = comments_model._all_inline_comments_of_pull_request(pull_request_latest)
433 q = q.order_by(ChangesetComment.comment_id.asc())
433 q = q.order_by(ChangesetComment.comment_id.asc())
434 inline_comments = q
434 inline_comments = q
435
435
436 c.inline_versions = comments_model.aggregate_comments(
436 c.inline_versions = comments_model.aggregate_comments(
437 inline_comments, versions, c.at_version_num, inline=True)
437 inline_comments, versions, c.at_version_num, inline=True)
438
438
439 # TODOs
439 # TODOs
440 c.unresolved_comments = CommentsModel() \
440 c.unresolved_comments = CommentsModel() \
441 .get_pull_request_unresolved_todos(pull_request)
441 .get_pull_request_unresolved_todos(pull_request)
442 c.resolved_comments = CommentsModel() \
442 c.resolved_comments = CommentsModel() \
443 .get_pull_request_resolved_todos(pull_request)
443 .get_pull_request_resolved_todos(pull_request)
444
444
445 # inject latest version
445 # inject latest version
446 latest_ver = PullRequest.get_pr_display_object(
446 latest_ver = PullRequest.get_pr_display_object(
447 pull_request_latest, pull_request_latest)
447 pull_request_latest, pull_request_latest)
448
448
449 c.versions = versions + [latest_ver]
449 c.versions = versions + [latest_ver]
450
450
451 # if we use version, then do not show later comments
451 # if we use version, then do not show later comments
452 # than current version
452 # than current version
453 display_inline_comments = collections.defaultdict(
453 display_inline_comments = collections.defaultdict(
454 lambda: collections.defaultdict(list))
454 lambda: collections.defaultdict(list))
455 for co in inline_comments:
455 for co in inline_comments:
456 if c.at_version_num:
456 if c.at_version_num:
457 # pick comments that are at least UPTO given version, so we
457 # pick comments that are at least UPTO given version, so we
458 # don't render comments for higher version
458 # don't render comments for higher version
459 should_render = co.pull_request_version_id and \
459 should_render = co.pull_request_version_id and \
460 co.pull_request_version_id <= c.at_version_num
460 co.pull_request_version_id <= c.at_version_num
461 else:
461 else:
462 # showing all, for 'latest'
462 # showing all, for 'latest'
463 should_render = True
463 should_render = True
464
464
465 if should_render:
465 if should_render:
466 display_inline_comments[co.f_path][co.line_no].append(co)
466 display_inline_comments[co.f_path][co.line_no].append(co)
467
467
468 # load diff data into template context, if we use compare mode then
468 # load diff data into template context, if we use compare mode then
469 # diff is calculated based on changes between versions of PR
469 # diff is calculated based on changes between versions of PR
470
470
471 source_repo = pull_request_at_ver.source_repo
471 source_repo = pull_request_at_ver.source_repo
472 source_ref_id = pull_request_at_ver.source_ref_parts.commit_id
472 source_ref_id = pull_request_at_ver.source_ref_parts.commit_id
473
473
474 target_repo = pull_request_at_ver.target_repo
474 target_repo = pull_request_at_ver.target_repo
475 target_ref_id = pull_request_at_ver.target_ref_parts.commit_id
475 target_ref_id = pull_request_at_ver.target_ref_parts.commit_id
476
476
477 if compare:
477 if compare:
478 # in compare switch the diff base to latest commit from prev version
478 # in compare switch the diff base to latest commit from prev version
479 target_ref_id = prev_pull_request_display_obj.revisions[0]
479 target_ref_id = prev_pull_request_display_obj.revisions[0]
480
480
481 # despite opening commits for bookmarks/branches/tags, we always
481 # despite opening commits for bookmarks/branches/tags, we always
482 # convert this to rev to prevent changes after bookmark or branch change
482 # convert this to rev to prevent changes after bookmark or branch change
483 c.source_ref_type = 'rev'
483 c.source_ref_type = 'rev'
484 c.source_ref = source_ref_id
484 c.source_ref = source_ref_id
485
485
486 c.target_ref_type = 'rev'
486 c.target_ref_type = 'rev'
487 c.target_ref = target_ref_id
487 c.target_ref = target_ref_id
488
488
489 c.source_repo = source_repo
489 c.source_repo = source_repo
490 c.target_repo = target_repo
490 c.target_repo = target_repo
491
491
492 c.commit_ranges = []
492 c.commit_ranges = []
493 source_commit = EmptyCommit()
493 source_commit = EmptyCommit()
494 target_commit = EmptyCommit()
494 target_commit = EmptyCommit()
495 c.missing_requirements = False
495 c.missing_requirements = False
496
496
497 source_scm = source_repo.scm_instance()
497 source_scm = source_repo.scm_instance()
498 target_scm = target_repo.scm_instance()
498 target_scm = target_repo.scm_instance()
499
499
500 shadow_scm = None
500 shadow_scm = None
501 try:
501 try:
502 shadow_scm = pull_request_latest.get_shadow_repo()
502 shadow_scm = pull_request_latest.get_shadow_repo()
503 except Exception:
503 except Exception:
504 log.debug('Failed to get shadow repo', exc_info=True)
504 log.debug('Failed to get shadow repo', exc_info=True)
505 # try first the existing source_repo, and then shadow
505 # try first the existing source_repo, and then shadow
506 # repo if we can obtain one
506 # repo if we can obtain one
507 commits_source_repo = source_scm
507 commits_source_repo = source_scm
508 if shadow_scm:
508 if shadow_scm:
509 commits_source_repo = shadow_scm
509 commits_source_repo = shadow_scm
510
510
511 c.commits_source_repo = commits_source_repo
511 c.commits_source_repo = commits_source_repo
512 c.ancestor = None # set it to None, to hide it from PR view
512 c.ancestor = None # set it to None, to hide it from PR view
513
513
514 # empty version means latest, so we keep this to prevent
514 # empty version means latest, so we keep this to prevent
515 # double caching
515 # double caching
516 version_normalized = version or 'latest'
516 version_normalized = version or 'latest'
517 from_version_normalized = from_version or 'latest'
517 from_version_normalized = from_version or 'latest'
518
518
519 cache_path = self.rhodecode_vcs_repo.get_create_shadow_cache_pr_path(target_repo)
519 cache_path = self.rhodecode_vcs_repo.get_create_shadow_cache_pr_path(target_repo)
520 cache_file_path = diff_cache_exist(
520 cache_file_path = diff_cache_exist(
521 cache_path, 'pull_request', pull_request_id, version_normalized,
521 cache_path, 'pull_request', pull_request_id, version_normalized,
522 from_version_normalized, source_ref_id, target_ref_id,
522 from_version_normalized, source_ref_id, target_ref_id,
523 hide_whitespace_changes, diff_context, c.fulldiff)
523 hide_whitespace_changes, diff_context, c.fulldiff)
524
524
525 caching_enabled = self._is_diff_cache_enabled(c.target_repo)
525 caching_enabled = self._is_diff_cache_enabled(c.target_repo)
526 force_recache = self.get_recache_flag()
526 force_recache = self.get_recache_flag()
527
527
528 cached_diff = None
528 cached_diff = None
529 if caching_enabled:
529 if caching_enabled:
530 cached_diff = load_cached_diff(cache_file_path)
530 cached_diff = load_cached_diff(cache_file_path)
531
531
532 has_proper_commit_cache = (
532 has_proper_commit_cache = (
533 cached_diff and cached_diff.get('commits')
533 cached_diff and cached_diff.get('commits')
534 and len(cached_diff.get('commits', [])) == 5
534 and len(cached_diff.get('commits', [])) == 5
535 and cached_diff.get('commits')[0]
535 and cached_diff.get('commits')[0]
536 and cached_diff.get('commits')[3])
536 and cached_diff.get('commits')[3])
537
537
538 if not force_recache and not c.range_diff_on and has_proper_commit_cache:
538 if not force_recache and not c.range_diff_on and has_proper_commit_cache:
539 diff_commit_cache = \
539 diff_commit_cache = \
540 (ancestor_commit, commit_cache, missing_requirements,
540 (ancestor_commit, commit_cache, missing_requirements,
541 source_commit, target_commit) = cached_diff['commits']
541 source_commit, target_commit) = cached_diff['commits']
542 else:
542 else:
543 # NOTE(marcink): we reach potentially unreachable errors when a PR has
543 # NOTE(marcink): we reach potentially unreachable errors when a PR has
544 # merge errors resulting in potentially hidden commits in the shadow repo.
544 # merge errors resulting in potentially hidden commits in the shadow repo.
545 maybe_unreachable = _merge_check.MERGE_CHECK in _merge_check.error_details \
545 maybe_unreachable = _merge_check.MERGE_CHECK in _merge_check.error_details \
546 and _merge_check.merge_response
546 and _merge_check.merge_response
547 maybe_unreachable = maybe_unreachable \
547 maybe_unreachable = maybe_unreachable \
548 and _merge_check.merge_response.metadata.get('unresolved_files')
548 and _merge_check.merge_response.metadata.get('unresolved_files')
549 log.debug("Using unreachable commits due to MERGE_CHECK in merge simulation")
549 log.debug("Using unreachable commits due to MERGE_CHECK in merge simulation")
550 diff_commit_cache = \
550 diff_commit_cache = \
551 (ancestor_commit, commit_cache, missing_requirements,
551 (ancestor_commit, commit_cache, missing_requirements,
552 source_commit, target_commit) = self.get_commits(
552 source_commit, target_commit) = self.get_commits(
553 commits_source_repo,
553 commits_source_repo,
554 pull_request_at_ver,
554 pull_request_at_ver,
555 source_commit,
555 source_commit,
556 source_ref_id,
556 source_ref_id,
557 source_scm,
557 source_scm,
558 target_commit,
558 target_commit,
559 target_ref_id,
559 target_ref_id,
560 target_scm, maybe_unreachable=maybe_unreachable)
560 target_scm, maybe_unreachable=maybe_unreachable)
561
561
562 # register our commit range
562 # register our commit range
563 for comm in commit_cache.values():
563 for comm in commit_cache.values():
564 c.commit_ranges.append(comm)
564 c.commit_ranges.append(comm)
565
565
566 c.missing_requirements = missing_requirements
566 c.missing_requirements = missing_requirements
567 c.ancestor_commit = ancestor_commit
567 c.ancestor_commit = ancestor_commit
568 c.statuses = source_repo.statuses(
568 c.statuses = source_repo.statuses(
569 [x.raw_id for x in c.commit_ranges])
569 [x.raw_id for x in c.commit_ranges])
570
570
571 # auto collapse if we have more than limit
571 # auto collapse if we have more than limit
572 collapse_limit = diffs.DiffProcessor._collapse_commits_over
572 collapse_limit = diffs.DiffProcessor._collapse_commits_over
573 c.collapse_all_commits = len(c.commit_ranges) > collapse_limit
573 c.collapse_all_commits = len(c.commit_ranges) > collapse_limit
574 c.compare_mode = compare
574 c.compare_mode = compare
575
575
576 # diff_limit is the old behavior, will cut off the whole diff
576 # diff_limit is the old behavior, will cut off the whole diff
577 # if the limit is applied otherwise will just hide the
577 # if the limit is applied otherwise will just hide the
578 # big files from the front-end
578 # big files from the front-end
579 diff_limit = c.visual.cut_off_limit_diff
579 diff_limit = c.visual.cut_off_limit_diff
580 file_limit = c.visual.cut_off_limit_file
580 file_limit = c.visual.cut_off_limit_file
581
581
582 c.missing_commits = False
582 c.missing_commits = False
583 if (c.missing_requirements
583 if (c.missing_requirements
584 or isinstance(source_commit, EmptyCommit)
584 or isinstance(source_commit, EmptyCommit)
585 or source_commit == target_commit):
585 or source_commit == target_commit):
586
586
587 c.missing_commits = True
587 c.missing_commits = True
588 else:
588 else:
589 c.inline_comments = display_inline_comments
589 c.inline_comments = display_inline_comments
590
590
591 has_proper_diff_cache = cached_diff and cached_diff.get('commits')
591 has_proper_diff_cache = cached_diff and cached_diff.get('commits')
592 if not force_recache and has_proper_diff_cache:
592 if not force_recache and has_proper_diff_cache:
593 c.diffset = cached_diff['diff']
593 c.diffset = cached_diff['diff']
594 (ancestor_commit, commit_cache, missing_requirements,
594 (ancestor_commit, commit_cache, missing_requirements,
595 source_commit, target_commit) = cached_diff['commits']
595 source_commit, target_commit) = cached_diff['commits']
596 else:
596 else:
597 c.diffset = self._get_diffset(
597 c.diffset = self._get_diffset(
598 c.source_repo.repo_name, commits_source_repo,
598 c.source_repo.repo_name, commits_source_repo,
599 source_ref_id, target_ref_id,
599 source_ref_id, target_ref_id,
600 target_commit, source_commit,
600 target_commit, source_commit,
601 diff_limit, file_limit, c.fulldiff,
601 diff_limit, file_limit, c.fulldiff,
602 hide_whitespace_changes, diff_context)
602 hide_whitespace_changes, diff_context)
603
603
604 # save cached diff
604 # save cached diff
605 if caching_enabled:
605 if caching_enabled:
606 cache_diff(cache_file_path, c.diffset, diff_commit_cache)
606 cache_diff(cache_file_path, c.diffset, diff_commit_cache)
607
607
608 c.limited_diff = c.diffset.limited_diff
608 c.limited_diff = c.diffset.limited_diff
609
609
610 # calculate removed files that are bound to comments
610 # calculate removed files that are bound to comments
611 comment_deleted_files = [
611 comment_deleted_files = [
612 fname for fname in display_inline_comments
612 fname for fname in display_inline_comments
613 if fname not in c.diffset.file_stats]
613 if fname not in c.diffset.file_stats]
614
614
615 c.deleted_files_comments = collections.defaultdict(dict)
615 c.deleted_files_comments = collections.defaultdict(dict)
616 for fname, per_line_comments in display_inline_comments.items():
616 for fname, per_line_comments in display_inline_comments.items():
617 if fname in comment_deleted_files:
617 if fname in comment_deleted_files:
618 c.deleted_files_comments[fname]['stats'] = 0
618 c.deleted_files_comments[fname]['stats'] = 0
619 c.deleted_files_comments[fname]['comments'] = list()
619 c.deleted_files_comments[fname]['comments'] = list()
620 for lno, comments in per_line_comments.items():
620 for lno, comments in per_line_comments.items():
621 c.deleted_files_comments[fname]['comments'].extend(comments)
621 c.deleted_files_comments[fname]['comments'].extend(comments)
622
622
623 # maybe calculate the range diff
623 # maybe calculate the range diff
624 if c.range_diff_on:
624 if c.range_diff_on:
625 # TODO(marcink): set whitespace/context
625 # TODO(marcink): set whitespace/context
626 context_lcl = 3
626 context_lcl = 3
627 ign_whitespace_lcl = False
627 ign_whitespace_lcl = False
628
628
629 for commit in c.commit_ranges:
629 for commit in c.commit_ranges:
630 commit2 = commit
630 commit2 = commit
631 commit1 = commit.first_parent
631 commit1 = commit.first_parent
632
632
633 range_diff_cache_file_path = diff_cache_exist(
633 range_diff_cache_file_path = diff_cache_exist(
634 cache_path, 'diff', commit.raw_id,
634 cache_path, 'diff', commit.raw_id,
635 ign_whitespace_lcl, context_lcl, c.fulldiff)
635 ign_whitespace_lcl, context_lcl, c.fulldiff)
636
636
637 cached_diff = None
637 cached_diff = None
638 if caching_enabled:
638 if caching_enabled:
639 cached_diff = load_cached_diff(range_diff_cache_file_path)
639 cached_diff = load_cached_diff(range_diff_cache_file_path)
640
640
641 has_proper_diff_cache = cached_diff and cached_diff.get('diff')
641 has_proper_diff_cache = cached_diff and cached_diff.get('diff')
642 if not force_recache and has_proper_diff_cache:
642 if not force_recache and has_proper_diff_cache:
643 diffset = cached_diff['diff']
643 diffset = cached_diff['diff']
644 else:
644 else:
645 diffset = self._get_range_diffset(
645 diffset = self._get_range_diffset(
646 commits_source_repo, source_repo,
646 commits_source_repo, source_repo,
647 commit1, commit2, diff_limit, file_limit,
647 commit1, commit2, diff_limit, file_limit,
648 c.fulldiff, ign_whitespace_lcl, context_lcl
648 c.fulldiff, ign_whitespace_lcl, context_lcl
649 )
649 )
650
650
651 # save cached diff
651 # save cached diff
652 if caching_enabled:
652 if caching_enabled:
653 cache_diff(range_diff_cache_file_path, diffset, None)
653 cache_diff(range_diff_cache_file_path, diffset, None)
654
654
655 c.changes[commit.raw_id] = diffset
655 c.changes[commit.raw_id] = diffset
656
656
657 # this is a hack to properly display links, when creating PR, the
657 # this is a hack to properly display links, when creating PR, the
658 # compare view and others uses different notation, and
658 # compare view and others uses different notation, and
659 # compare_commits.mako renders links based on the target_repo.
659 # compare_commits.mako renders links based on the target_repo.
660 # We need to swap that here to generate it properly on the html side
660 # We need to swap that here to generate it properly on the html side
661 c.target_repo = c.source_repo
661 c.target_repo = c.source_repo
662
662
663 c.commit_statuses = ChangesetStatus.STATUSES
663 c.commit_statuses = ChangesetStatus.STATUSES
664
664
665 c.show_version_changes = not pr_closed
665 c.show_version_changes = not pr_closed
666 if c.show_version_changes:
666 if c.show_version_changes:
667 cur_obj = pull_request_at_ver
667 cur_obj = pull_request_at_ver
668 prev_obj = prev_pull_request_at_ver
668 prev_obj = prev_pull_request_at_ver
669
669
670 old_commit_ids = prev_obj.revisions
670 old_commit_ids = prev_obj.revisions
671 new_commit_ids = cur_obj.revisions
671 new_commit_ids = cur_obj.revisions
672 commit_changes = PullRequestModel()._calculate_commit_id_changes(
672 commit_changes = PullRequestModel()._calculate_commit_id_changes(
673 old_commit_ids, new_commit_ids)
673 old_commit_ids, new_commit_ids)
674 c.commit_changes_summary = commit_changes
674 c.commit_changes_summary = commit_changes
675
675
676 # calculate the diff for commits between versions
676 # calculate the diff for commits between versions
677 c.commit_changes = []
677 c.commit_changes = []
678 mark = lambda cs, fw: list(
678 mark = lambda cs, fw: list(
679 h.itertools.izip_longest([], cs, fillvalue=fw))
679 h.itertools.izip_longest([], cs, fillvalue=fw))
680 for c_type, raw_id in mark(commit_changes.added, 'a') \
680 for c_type, raw_id in mark(commit_changes.added, 'a') \
681 + mark(commit_changes.removed, 'r') \
681 + mark(commit_changes.removed, 'r') \
682 + mark(commit_changes.common, 'c'):
682 + mark(commit_changes.common, 'c'):
683
683
684 if raw_id in commit_cache:
684 if raw_id in commit_cache:
685 commit = commit_cache[raw_id]
685 commit = commit_cache[raw_id]
686 else:
686 else:
687 try:
687 try:
688 commit = commits_source_repo.get_commit(raw_id)
688 commit = commits_source_repo.get_commit(raw_id)
689 except CommitDoesNotExistError:
689 except CommitDoesNotExistError:
690 # in case we fail extracting still use "dummy" commit
690 # in case we fail extracting still use "dummy" commit
691 # for display in commit diff
691 # for display in commit diff
692 commit = h.AttributeDict(
692 commit = h.AttributeDict(
693 {'raw_id': raw_id,
693 {'raw_id': raw_id,
694 'message': 'EMPTY or MISSING COMMIT'})
694 'message': 'EMPTY or MISSING COMMIT'})
695 c.commit_changes.append([c_type, commit])
695 c.commit_changes.append([c_type, commit])
696
696
697 # current user review statuses for each version
697 # current user review statuses for each version
698 c.review_versions = {}
698 c.review_versions = {}
699 if self._rhodecode_user.user_id in allowed_reviewers:
699 if self._rhodecode_user.user_id in allowed_reviewers:
700 for co in general_comments:
700 for co in general_comments:
701 if co.author.user_id == self._rhodecode_user.user_id:
701 if co.author.user_id == self._rhodecode_user.user_id:
702 status = co.status_change
702 status = co.status_change
703 if status:
703 if status:
704 _ver_pr = status[0].comment.pull_request_version_id
704 _ver_pr = status[0].comment.pull_request_version_id
705 c.review_versions[_ver_pr] = status[0]
705 c.review_versions[_ver_pr] = status[0]
706
706
707 return self._get_template_context(c)
707 return self._get_template_context(c)
708
708
709 def get_commits(
709 def get_commits(
710 self, commits_source_repo, pull_request_at_ver, source_commit,
710 self, commits_source_repo, pull_request_at_ver, source_commit,
711 source_ref_id, source_scm, target_commit, target_ref_id, target_scm,
711 source_ref_id, source_scm, target_commit, target_ref_id, target_scm,
712 maybe_unreachable=False):
712 maybe_unreachable=False):
713
713
714 commit_cache = collections.OrderedDict()
714 commit_cache = collections.OrderedDict()
715 missing_requirements = False
715 missing_requirements = False
716
716
717 try:
717 try:
718 pre_load = ["author", "date", "message", "branch", "parents"]
718 pre_load = ["author", "date", "message", "branch", "parents"]
719
719
720 pull_request_commits = pull_request_at_ver.revisions
720 pull_request_commits = pull_request_at_ver.revisions
721 log.debug('Loading %s commits from %s',
721 log.debug('Loading %s commits from %s',
722 len(pull_request_commits), commits_source_repo)
722 len(pull_request_commits), commits_source_repo)
723
723
724 for rev in pull_request_commits:
724 for rev in pull_request_commits:
725 comm = commits_source_repo.get_commit(commit_id=rev, pre_load=pre_load,
725 comm = commits_source_repo.get_commit(commit_id=rev, pre_load=pre_load,
726 maybe_unreachable=maybe_unreachable)
726 maybe_unreachable=maybe_unreachable)
727 commit_cache[comm.raw_id] = comm
727 commit_cache[comm.raw_id] = comm
728
728
729 # Order here matters, we first need to get target, and then
729 # Order here matters, we first need to get target, and then
730 # the source
730 # the source
731 target_commit = commits_source_repo.get_commit(
731 target_commit = commits_source_repo.get_commit(
732 commit_id=safe_str(target_ref_id))
732 commit_id=safe_str(target_ref_id))
733
733
734 source_commit = commits_source_repo.get_commit(
734 source_commit = commits_source_repo.get_commit(
735 commit_id=safe_str(source_ref_id), maybe_unreachable=True)
735 commit_id=safe_str(source_ref_id), maybe_unreachable=True)
736 except CommitDoesNotExistError:
736 except CommitDoesNotExistError:
737 log.warning('Failed to get commit from `{}` repo'.format(
737 log.warning('Failed to get commit from `{}` repo'.format(
738 commits_source_repo), exc_info=True)
738 commits_source_repo), exc_info=True)
739 except RepositoryRequirementError:
739 except RepositoryRequirementError:
740 log.warning('Failed to get all required data from repo', exc_info=True)
740 log.warning('Failed to get all required data from repo', exc_info=True)
741 missing_requirements = True
741 missing_requirements = True
742 ancestor_commit = None
742 ancestor_commit = None
743 try:
743 try:
744 ancestor_id = source_scm.get_common_ancestor(
744 ancestor_id = source_scm.get_common_ancestor(
745 source_commit.raw_id, target_commit.raw_id, target_scm)
745 source_commit.raw_id, target_commit.raw_id, target_scm)
746 ancestor_commit = source_scm.get_commit(ancestor_id)
746 ancestor_commit = source_scm.get_commit(ancestor_id)
747 except Exception:
747 except Exception:
748 ancestor_commit = None
748 ancestor_commit = None
749 return ancestor_commit, commit_cache, missing_requirements, source_commit, target_commit
749 return ancestor_commit, commit_cache, missing_requirements, source_commit, target_commit
750
750
751 def assure_not_empty_repo(self):
751 def assure_not_empty_repo(self):
752 _ = self.request.translate
752 _ = self.request.translate
753
753
754 try:
754 try:
755 self.db_repo.scm_instance().get_commit()
755 self.db_repo.scm_instance().get_commit()
756 except EmptyRepositoryError:
756 except EmptyRepositoryError:
757 h.flash(h.literal(_('There are no commits yet')),
757 h.flash(h.literal(_('There are no commits yet')),
758 category='warning')
758 category='warning')
759 raise HTTPFound(
759 raise HTTPFound(
760 h.route_path('repo_summary', repo_name=self.db_repo.repo_name))
760 h.route_path('repo_summary', repo_name=self.db_repo.repo_name))
761
761
762 @LoginRequired()
762 @LoginRequired()
763 @NotAnonymous()
763 @NotAnonymous()
764 @HasRepoPermissionAnyDecorator(
764 @HasRepoPermissionAnyDecorator(
765 'repository.read', 'repository.write', 'repository.admin')
765 'repository.read', 'repository.write', 'repository.admin')
766 @view_config(
766 @view_config(
767 route_name='pullrequest_new', request_method='GET',
767 route_name='pullrequest_new', request_method='GET',
768 renderer='rhodecode:templates/pullrequests/pullrequest.mako')
768 renderer='rhodecode:templates/pullrequests/pullrequest.mako')
769 def pull_request_new(self):
769 def pull_request_new(self):
770 _ = self.request.translate
770 _ = self.request.translate
771 c = self.load_default_context()
771 c = self.load_default_context()
772
772
773 self.assure_not_empty_repo()
773 self.assure_not_empty_repo()
774 source_repo = self.db_repo
774 source_repo = self.db_repo
775
775
776 commit_id = self.request.GET.get('commit')
776 commit_id = self.request.GET.get('commit')
777 branch_ref = self.request.GET.get('branch')
777 branch_ref = self.request.GET.get('branch')
778 bookmark_ref = self.request.GET.get('bookmark')
778 bookmark_ref = self.request.GET.get('bookmark')
779
779
780 try:
780 try:
781 source_repo_data = PullRequestModel().generate_repo_data(
781 source_repo_data = PullRequestModel().generate_repo_data(
782 source_repo, commit_id=commit_id,
782 source_repo, commit_id=commit_id,
783 branch=branch_ref, bookmark=bookmark_ref,
783 branch=branch_ref, bookmark=bookmark_ref,
784 translator=self.request.translate)
784 translator=self.request.translate)
785 except CommitDoesNotExistError as e:
785 except CommitDoesNotExistError as e:
786 log.exception(e)
786 log.exception(e)
787 h.flash(_('Commit does not exist'), 'error')
787 h.flash(_('Commit does not exist'), 'error')
788 raise HTTPFound(
788 raise HTTPFound(
789 h.route_path('pullrequest_new', repo_name=source_repo.repo_name))
789 h.route_path('pullrequest_new', repo_name=source_repo.repo_name))
790
790
791 default_target_repo = source_repo
791 default_target_repo = source_repo
792
792
793 if source_repo.parent and c.has_origin_repo_read_perm:
793 if source_repo.parent and c.has_origin_repo_read_perm:
794 parent_vcs_obj = source_repo.parent.scm_instance()
794 parent_vcs_obj = source_repo.parent.scm_instance()
795 if parent_vcs_obj and not parent_vcs_obj.is_empty():
795 if parent_vcs_obj and not parent_vcs_obj.is_empty():
796 # change default if we have a parent repo
796 # change default if we have a parent repo
797 default_target_repo = source_repo.parent
797 default_target_repo = source_repo.parent
798
798
799 target_repo_data = PullRequestModel().generate_repo_data(
799 target_repo_data = PullRequestModel().generate_repo_data(
800 default_target_repo, translator=self.request.translate)
800 default_target_repo, translator=self.request.translate)
801
801
802 selected_source_ref = source_repo_data['refs']['selected_ref']
802 selected_source_ref = source_repo_data['refs']['selected_ref']
803 title_source_ref = ''
803 title_source_ref = ''
804 if selected_source_ref:
804 if selected_source_ref:
805 title_source_ref = selected_source_ref.split(':', 2)[1]
805 title_source_ref = selected_source_ref.split(':', 2)[1]
806 c.default_title = PullRequestModel().generate_pullrequest_title(
806 c.default_title = PullRequestModel().generate_pullrequest_title(
807 source=source_repo.repo_name,
807 source=source_repo.repo_name,
808 source_ref=title_source_ref,
808 source_ref=title_source_ref,
809 target=default_target_repo.repo_name
809 target=default_target_repo.repo_name
810 )
810 )
811
811
812 c.default_repo_data = {
812 c.default_repo_data = {
813 'source_repo_name': source_repo.repo_name,
813 'source_repo_name': source_repo.repo_name,
814 'source_refs_json': json.dumps(source_repo_data),
814 'source_refs_json': json.dumps(source_repo_data),
815 'target_repo_name': default_target_repo.repo_name,
815 'target_repo_name': default_target_repo.repo_name,
816 'target_refs_json': json.dumps(target_repo_data),
816 'target_refs_json': json.dumps(target_repo_data),
817 }
817 }
818 c.default_source_ref = selected_source_ref
818 c.default_source_ref = selected_source_ref
819
819
820 return self._get_template_context(c)
820 return self._get_template_context(c)
821
821
822 @LoginRequired()
822 @LoginRequired()
823 @NotAnonymous()
823 @NotAnonymous()
824 @HasRepoPermissionAnyDecorator(
824 @HasRepoPermissionAnyDecorator(
825 'repository.read', 'repository.write', 'repository.admin')
825 'repository.read', 'repository.write', 'repository.admin')
826 @view_config(
826 @view_config(
827 route_name='pullrequest_repo_refs', request_method='GET',
827 route_name='pullrequest_repo_refs', request_method='GET',
828 renderer='json_ext', xhr=True)
828 renderer='json_ext', xhr=True)
829 def pull_request_repo_refs(self):
829 def pull_request_repo_refs(self):
830 self.load_default_context()
830 self.load_default_context()
831 target_repo_name = self.request.matchdict['target_repo_name']
831 target_repo_name = self.request.matchdict['target_repo_name']
832 repo = Repository.get_by_repo_name(target_repo_name)
832 repo = Repository.get_by_repo_name(target_repo_name)
833 if not repo:
833 if not repo:
834 raise HTTPNotFound()
834 raise HTTPNotFound()
835
835
836 target_perm = HasRepoPermissionAny(
836 target_perm = HasRepoPermissionAny(
837 'repository.read', 'repository.write', 'repository.admin')(
837 'repository.read', 'repository.write', 'repository.admin')(
838 target_repo_name)
838 target_repo_name)
839 if not target_perm:
839 if not target_perm:
840 raise HTTPNotFound()
840 raise HTTPNotFound()
841
841
842 return PullRequestModel().generate_repo_data(
842 return PullRequestModel().generate_repo_data(
843 repo, translator=self.request.translate)
843 repo, translator=self.request.translate)
844
844
845 @LoginRequired()
845 @LoginRequired()
846 @NotAnonymous()
846 @NotAnonymous()
847 @HasRepoPermissionAnyDecorator(
847 @HasRepoPermissionAnyDecorator(
848 'repository.read', 'repository.write', 'repository.admin')
848 'repository.read', 'repository.write', 'repository.admin')
849 @view_config(
849 @view_config(
850 route_name='pullrequest_repo_targets', request_method='GET',
850 route_name='pullrequest_repo_targets', request_method='GET',
851 renderer='json_ext', xhr=True)
851 renderer='json_ext', xhr=True)
852 def pullrequest_repo_targets(self):
852 def pullrequest_repo_targets(self):
853 _ = self.request.translate
853 _ = self.request.translate
854 filter_query = self.request.GET.get('query')
854 filter_query = self.request.GET.get('query')
855
855
856 # get the parents
856 # get the parents
857 parent_target_repos = []
857 parent_target_repos = []
858 if self.db_repo.parent:
858 if self.db_repo.parent:
859 parents_query = Repository.query() \
859 parents_query = Repository.query() \
860 .order_by(func.length(Repository.repo_name)) \
860 .order_by(func.length(Repository.repo_name)) \
861 .filter(Repository.fork_id == self.db_repo.parent.repo_id)
861 .filter(Repository.fork_id == self.db_repo.parent.repo_id)
862
862
863 if filter_query:
863 if filter_query:
864 ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
864 ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
865 parents_query = parents_query.filter(
865 parents_query = parents_query.filter(
866 Repository.repo_name.ilike(ilike_expression))
866 Repository.repo_name.ilike(ilike_expression))
867 parents = parents_query.limit(20).all()
867 parents = parents_query.limit(20).all()
868
868
869 for parent in parents:
869 for parent in parents:
870 parent_vcs_obj = parent.scm_instance()
870 parent_vcs_obj = parent.scm_instance()
871 if parent_vcs_obj and not parent_vcs_obj.is_empty():
871 if parent_vcs_obj and not parent_vcs_obj.is_empty():
872 parent_target_repos.append(parent)
872 parent_target_repos.append(parent)
873
873
874 # get other forks, and repo itself
874 # get other forks, and repo itself
875 query = Repository.query() \
875 query = Repository.query() \
876 .order_by(func.length(Repository.repo_name)) \
876 .order_by(func.length(Repository.repo_name)) \
877 .filter(
877 .filter(
878 or_(Repository.repo_id == self.db_repo.repo_id, # repo itself
878 or_(Repository.repo_id == self.db_repo.repo_id, # repo itself
879 Repository.fork_id == self.db_repo.repo_id) # forks of this repo
879 Repository.fork_id == self.db_repo.repo_id) # forks of this repo
880 ) \
880 ) \
881 .filter(~Repository.repo_id.in_([x.repo_id for x in parent_target_repos]))
881 .filter(~Repository.repo_id.in_([x.repo_id for x in parent_target_repos]))
882
882
883 if filter_query:
883 if filter_query:
884 ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
884 ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
885 query = query.filter(Repository.repo_name.ilike(ilike_expression))
885 query = query.filter(Repository.repo_name.ilike(ilike_expression))
886
886
887 limit = max(20 - len(parent_target_repos), 5) # not less then 5
887 limit = max(20 - len(parent_target_repos), 5) # not less then 5
888 target_repos = query.limit(limit).all()
888 target_repos = query.limit(limit).all()
889
889
890 all_target_repos = target_repos + parent_target_repos
890 all_target_repos = target_repos + parent_target_repos
891
891
892 repos = []
892 repos = []
893 # This checks permissions to the repositories
893 # This checks permissions to the repositories
894 for obj in ScmModel().get_repos(all_target_repos):
894 for obj in ScmModel().get_repos(all_target_repos):
895 repos.append({
895 repos.append({
896 'id': obj['name'],
896 'id': obj['name'],
897 'text': obj['name'],
897 'text': obj['name'],
898 'type': 'repo',
898 'type': 'repo',
899 'repo_id': obj['dbrepo']['repo_id'],
899 'repo_id': obj['dbrepo']['repo_id'],
900 'repo_type': obj['dbrepo']['repo_type'],
900 'repo_type': obj['dbrepo']['repo_type'],
901 'private': obj['dbrepo']['private'],
901 'private': obj['dbrepo']['private'],
902
902
903 })
903 })
904
904
905 data = {
905 data = {
906 'more': False,
906 'more': False,
907 'results': [{
907 'results': [{
908 'text': _('Repositories'),
908 'text': _('Repositories'),
909 'children': repos
909 'children': repos
910 }] if repos else []
910 }] if repos else []
911 }
911 }
912 return data
912 return data
913
913
914 @LoginRequired()
914 @LoginRequired()
915 @NotAnonymous()
915 @NotAnonymous()
916 @HasRepoPermissionAnyDecorator(
916 @HasRepoPermissionAnyDecorator(
917 'repository.read', 'repository.write', 'repository.admin')
917 'repository.read', 'repository.write', 'repository.admin')
918 @CSRFRequired()
918 @CSRFRequired()
919 @view_config(
919 @view_config(
920 route_name='pullrequest_create', request_method='POST',
920 route_name='pullrequest_create', request_method='POST',
921 renderer=None)
921 renderer=None)
922 def pull_request_create(self):
922 def pull_request_create(self):
923 _ = self.request.translate
923 _ = self.request.translate
924 self.assure_not_empty_repo()
924 self.assure_not_empty_repo()
925 self.load_default_context()
925 self.load_default_context()
926
926
927 controls = peppercorn.parse(self.request.POST.items())
927 controls = peppercorn.parse(self.request.POST.items())
928
928
929 try:
929 try:
930 form = PullRequestForm(
930 form = PullRequestForm(
931 self.request.translate, self.db_repo.repo_id)()
931 self.request.translate, self.db_repo.repo_id)()
932 _form = form.to_python(controls)
932 _form = form.to_python(controls)
933 except formencode.Invalid as errors:
933 except formencode.Invalid as errors:
934 if errors.error_dict.get('revisions'):
934 if errors.error_dict.get('revisions'):
935 msg = 'Revisions: %s' % errors.error_dict['revisions']
935 msg = 'Revisions: %s' % errors.error_dict['revisions']
936 elif errors.error_dict.get('pullrequest_title'):
936 elif errors.error_dict.get('pullrequest_title'):
937 msg = errors.error_dict.get('pullrequest_title')
937 msg = errors.error_dict.get('pullrequest_title')
938 else:
938 else:
939 msg = _('Error creating pull request: {}').format(errors)
939 msg = _('Error creating pull request: {}').format(errors)
940 log.exception(msg)
940 log.exception(msg)
941 h.flash(msg, 'error')
941 h.flash(msg, 'error')
942
942
943 # would rather just go back to form ...
943 # would rather just go back to form ...
944 raise HTTPFound(
944 raise HTTPFound(
945 h.route_path('pullrequest_new', repo_name=self.db_repo_name))
945 h.route_path('pullrequest_new', repo_name=self.db_repo_name))
946
946
947 source_repo = _form['source_repo']
947 source_repo = _form['source_repo']
948 source_ref = _form['source_ref']
948 source_ref = _form['source_ref']
949 target_repo = _form['target_repo']
949 target_repo = _form['target_repo']
950 target_ref = _form['target_ref']
950 target_ref = _form['target_ref']
951 commit_ids = _form['revisions'][::-1]
951 commit_ids = _form['revisions'][::-1]
952
952
953 # find the ancestor for this pr
953 # find the ancestor for this pr
954 source_db_repo = Repository.get_by_repo_name(_form['source_repo'])
954 source_db_repo = Repository.get_by_repo_name(_form['source_repo'])
955 target_db_repo = Repository.get_by_repo_name(_form['target_repo'])
955 target_db_repo = Repository.get_by_repo_name(_form['target_repo'])
956
956
957 if not (source_db_repo or target_db_repo):
957 if not (source_db_repo or target_db_repo):
958 h.flash(_('source_repo or target repo not found'), category='error')
958 h.flash(_('source_repo or target repo not found'), category='error')
959 raise HTTPFound(
959 raise HTTPFound(
960 h.route_path('pullrequest_new', repo_name=self.db_repo_name))
960 h.route_path('pullrequest_new', repo_name=self.db_repo_name))
961
961
962 # re-check permissions again here
962 # re-check permissions again here
963 # source_repo we must have read permissions
963 # source_repo we must have read permissions
964
964
965 source_perm = HasRepoPermissionAny(
965 source_perm = HasRepoPermissionAny(
966 'repository.read', 'repository.write', 'repository.admin')(
966 'repository.read', 'repository.write', 'repository.admin')(
967 source_db_repo.repo_name)
967 source_db_repo.repo_name)
968 if not source_perm:
968 if not source_perm:
969 msg = _('Not Enough permissions to source repo `{}`.'.format(
969 msg = _('Not Enough permissions to source repo `{}`.'.format(
970 source_db_repo.repo_name))
970 source_db_repo.repo_name))
971 h.flash(msg, category='error')
971 h.flash(msg, category='error')
972 # copy the args back to redirect
972 # copy the args back to redirect
973 org_query = self.request.GET.mixed()
973 org_query = self.request.GET.mixed()
974 raise HTTPFound(
974 raise HTTPFound(
975 h.route_path('pullrequest_new', repo_name=self.db_repo_name,
975 h.route_path('pullrequest_new', repo_name=self.db_repo_name,
976 _query=org_query))
976 _query=org_query))
977
977
978 # target repo we must have read permissions, and also later on
978 # target repo we must have read permissions, and also later on
979 # we want to check branch permissions here
979 # we want to check branch permissions here
980 target_perm = HasRepoPermissionAny(
980 target_perm = HasRepoPermissionAny(
981 'repository.read', 'repository.write', 'repository.admin')(
981 'repository.read', 'repository.write', 'repository.admin')(
982 target_db_repo.repo_name)
982 target_db_repo.repo_name)
983 if not target_perm:
983 if not target_perm:
984 msg = _('Not Enough permissions to target repo `{}`.'.format(
984 msg = _('Not Enough permissions to target repo `{}`.'.format(
985 target_db_repo.repo_name))
985 target_db_repo.repo_name))
986 h.flash(msg, category='error')
986 h.flash(msg, category='error')
987 # copy the args back to redirect
987 # copy the args back to redirect
988 org_query = self.request.GET.mixed()
988 org_query = self.request.GET.mixed()
989 raise HTTPFound(
989 raise HTTPFound(
990 h.route_path('pullrequest_new', repo_name=self.db_repo_name,
990 h.route_path('pullrequest_new', repo_name=self.db_repo_name,
991 _query=org_query))
991 _query=org_query))
992
992
993 source_scm = source_db_repo.scm_instance()
993 source_scm = source_db_repo.scm_instance()
994 target_scm = target_db_repo.scm_instance()
994 target_scm = target_db_repo.scm_instance()
995
995
996 source_commit = source_scm.get_commit(source_ref.split(':')[-1])
996 source_commit = source_scm.get_commit(source_ref.split(':')[-1])
997 target_commit = target_scm.get_commit(target_ref.split(':')[-1])
997 target_commit = target_scm.get_commit(target_ref.split(':')[-1])
998
998
999 ancestor = source_scm.get_common_ancestor(
999 ancestor = source_scm.get_common_ancestor(
1000 source_commit.raw_id, target_commit.raw_id, target_scm)
1000 source_commit.raw_id, target_commit.raw_id, target_scm)
1001
1001
1002 # recalculate target ref based on ancestor
1002 # recalculate target ref based on ancestor
1003 target_ref_type, target_ref_name, __ = _form['target_ref'].split(':')
1003 target_ref_type, target_ref_name, __ = _form['target_ref'].split(':')
1004 target_ref = ':'.join((target_ref_type, target_ref_name, ancestor))
1004 target_ref = ':'.join((target_ref_type, target_ref_name, ancestor))
1005
1005
1006 get_default_reviewers_data, validate_default_reviewers = \
1006 get_default_reviewers_data, validate_default_reviewers = \
1007 PullRequestModel().get_reviewer_functions()
1007 PullRequestModel().get_reviewer_functions()
1008
1008
1009 # recalculate reviewers logic, to make sure we can validate this
1009 # recalculate reviewers logic, to make sure we can validate this
1010 reviewer_rules = get_default_reviewers_data(
1010 reviewer_rules = get_default_reviewers_data(
1011 self._rhodecode_db_user, source_db_repo,
1011 self._rhodecode_db_user, source_db_repo,
1012 source_commit, target_db_repo, target_commit)
1012 source_commit, target_db_repo, target_commit)
1013
1013
1014 given_reviewers = _form['review_members']
1014 given_reviewers = _form['review_members']
1015 reviewers = validate_default_reviewers(
1015 reviewers = validate_default_reviewers(
1016 given_reviewers, reviewer_rules)
1016 given_reviewers, reviewer_rules)
1017
1017
1018 pullrequest_title = _form['pullrequest_title']
1018 pullrequest_title = _form['pullrequest_title']
1019 title_source_ref = source_ref.split(':', 2)[1]
1019 title_source_ref = source_ref.split(':', 2)[1]
1020 if not pullrequest_title:
1020 if not pullrequest_title:
1021 pullrequest_title = PullRequestModel().generate_pullrequest_title(
1021 pullrequest_title = PullRequestModel().generate_pullrequest_title(
1022 source=source_repo,
1022 source=source_repo,
1023 source_ref=title_source_ref,
1023 source_ref=title_source_ref,
1024 target=target_repo
1024 target=target_repo
1025 )
1025 )
1026
1026
1027 description = _form['pullrequest_desc']
1027 description = _form['pullrequest_desc']
1028 description_renderer = _form['description_renderer']
1028 description_renderer = _form['description_renderer']
1029
1029
1030 try:
1030 try:
1031 pull_request = PullRequestModel().create(
1031 pull_request = PullRequestModel().create(
1032 created_by=self._rhodecode_user.user_id,
1032 created_by=self._rhodecode_user.user_id,
1033 source_repo=source_repo,
1033 source_repo=source_repo,
1034 source_ref=source_ref,
1034 source_ref=source_ref,
1035 target_repo=target_repo,
1035 target_repo=target_repo,
1036 target_ref=target_ref,
1036 target_ref=target_ref,
1037 revisions=commit_ids,
1037 revisions=commit_ids,
1038 reviewers=reviewers,
1038 reviewers=reviewers,
1039 title=pullrequest_title,
1039 title=pullrequest_title,
1040 description=description,
1040 description=description,
1041 description_renderer=description_renderer,
1041 description_renderer=description_renderer,
1042 reviewer_data=reviewer_rules,
1042 reviewer_data=reviewer_rules,
1043 auth_user=self._rhodecode_user
1043 auth_user=self._rhodecode_user
1044 )
1044 )
1045 Session().commit()
1045 Session().commit()
1046
1046
1047 h.flash(_('Successfully opened new pull request'),
1047 h.flash(_('Successfully opened new pull request'),
1048 category='success')
1048 category='success')
1049 except Exception:
1049 except Exception:
1050 msg = _('Error occurred during creation of this pull request.')
1050 msg = _('Error occurred during creation of this pull request.')
1051 log.exception(msg)
1051 log.exception(msg)
1052 h.flash(msg, category='error')
1052 h.flash(msg, category='error')
1053
1053
1054 # copy the args back to redirect
1054 # copy the args back to redirect
1055 org_query = self.request.GET.mixed()
1055 org_query = self.request.GET.mixed()
1056 raise HTTPFound(
1056 raise HTTPFound(
1057 h.route_path('pullrequest_new', repo_name=self.db_repo_name,
1057 h.route_path('pullrequest_new', repo_name=self.db_repo_name,
1058 _query=org_query))
1058 _query=org_query))
1059
1059
1060 raise HTTPFound(
1060 raise HTTPFound(
1061 h.route_path('pullrequest_show', repo_name=target_repo,
1061 h.route_path('pullrequest_show', repo_name=target_repo,
1062 pull_request_id=pull_request.pull_request_id))
1062 pull_request_id=pull_request.pull_request_id))
1063
1063
1064 @LoginRequired()
1064 @LoginRequired()
1065 @NotAnonymous()
1065 @NotAnonymous()
1066 @HasRepoPermissionAnyDecorator(
1066 @HasRepoPermissionAnyDecorator(
1067 'repository.read', 'repository.write', 'repository.admin')
1067 'repository.read', 'repository.write', 'repository.admin')
1068 @CSRFRequired()
1068 @CSRFRequired()
1069 @view_config(
1069 @view_config(
1070 route_name='pullrequest_update', request_method='POST',
1070 route_name='pullrequest_update', request_method='POST',
1071 renderer='json_ext')
1071 renderer='json_ext')
1072 def pull_request_update(self):
1072 def pull_request_update(self):
1073 pull_request = PullRequest.get_or_404(
1073 pull_request = PullRequest.get_or_404(
1074 self.request.matchdict['pull_request_id'])
1074 self.request.matchdict['pull_request_id'])
1075 _ = self.request.translate
1075 _ = self.request.translate
1076
1076
1077 self.load_default_context()
1077 self.load_default_context()
1078 redirect_url = None
1078 redirect_url = None
1079
1079
1080 if pull_request.is_closed():
1080 if pull_request.is_closed():
1081 log.debug('update: forbidden because pull request is closed')
1081 log.debug('update: forbidden because pull request is closed')
1082 msg = _(u'Cannot update closed pull requests.')
1082 msg = _(u'Cannot update closed pull requests.')
1083 h.flash(msg, category='error')
1083 h.flash(msg, category='error')
1084 return {'response': True,
1084 return {'response': True,
1085 'redirect_url': redirect_url}
1085 'redirect_url': redirect_url}
1086
1086
1087 is_state_changing = pull_request.is_state_changing()
1087 is_state_changing = pull_request.is_state_changing()
1088
1088
1089 # only owner or admin can update it
1089 # only owner or admin can update it
1090 allowed_to_update = PullRequestModel().check_user_update(
1090 allowed_to_update = PullRequestModel().check_user_update(
1091 pull_request, self._rhodecode_user)
1091 pull_request, self._rhodecode_user)
1092 if allowed_to_update:
1092 if allowed_to_update:
1093 controls = peppercorn.parse(self.request.POST.items())
1093 controls = peppercorn.parse(self.request.POST.items())
1094 force_refresh = str2bool(self.request.POST.get('force_refresh'))
1094 force_refresh = str2bool(self.request.POST.get('force_refresh'))
1095
1095
1096 if 'review_members' in controls:
1096 if 'review_members' in controls:
1097 self._update_reviewers(
1097 self._update_reviewers(
1098 pull_request, controls['review_members'],
1098 pull_request, controls['review_members'],
1099 pull_request.reviewer_data)
1099 pull_request.reviewer_data)
1100 elif str2bool(self.request.POST.get('update_commits', 'false')):
1100 elif str2bool(self.request.POST.get('update_commits', 'false')):
1101 if is_state_changing:
1101 if is_state_changing:
1102 log.debug('commits update: forbidden because pull request is in state %s',
1102 log.debug('commits update: forbidden because pull request is in state %s',
1103 pull_request.pull_request_state)
1103 pull_request.pull_request_state)
1104 msg = _(u'Cannot update pull requests commits in state other than `{}`. '
1104 msg = _(u'Cannot update pull requests commits in state other than `{}`. '
1105 u'Current state is: `{}`').format(
1105 u'Current state is: `{}`').format(
1106 PullRequest.STATE_CREATED, pull_request.pull_request_state)
1106 PullRequest.STATE_CREATED, pull_request.pull_request_state)
1107 h.flash(msg, category='error')
1107 h.flash(msg, category='error')
1108 return {'response': True,
1108 return {'response': True,
1109 'redirect_url': redirect_url}
1109 'redirect_url': redirect_url}
1110
1110
1111 self._update_commits(pull_request)
1111 self._update_commits(pull_request)
1112 if force_refresh:
1112 if force_refresh:
1113 redirect_url = h.route_path(
1113 redirect_url = h.route_path(
1114 'pullrequest_show', repo_name=self.db_repo_name,
1114 'pullrequest_show', repo_name=self.db_repo_name,
1115 pull_request_id=pull_request.pull_request_id,
1115 pull_request_id=pull_request.pull_request_id,
1116 _query={"force_refresh": 1})
1116 _query={"force_refresh": 1})
1117 elif str2bool(self.request.POST.get('edit_pull_request', 'false')):
1117 elif str2bool(self.request.POST.get('edit_pull_request', 'false')):
1118 self._edit_pull_request(pull_request)
1118 self._edit_pull_request(pull_request)
1119 else:
1119 else:
1120 raise HTTPBadRequest()
1120 raise HTTPBadRequest()
1121
1121
1122 return {'response': True,
1122 return {'response': True,
1123 'redirect_url': redirect_url}
1123 'redirect_url': redirect_url}
1124 raise HTTPForbidden()
1124 raise HTTPForbidden()
1125
1125
1126 def _edit_pull_request(self, pull_request):
1126 def _edit_pull_request(self, pull_request):
1127 _ = self.request.translate
1127 _ = self.request.translate
1128
1128
1129 try:
1129 try:
1130 PullRequestModel().edit(
1130 PullRequestModel().edit(
1131 pull_request,
1131 pull_request,
1132 self.request.POST.get('title'),
1132 self.request.POST.get('title'),
1133 self.request.POST.get('description'),
1133 self.request.POST.get('description'),
1134 self.request.POST.get('description_renderer'),
1134 self.request.POST.get('description_renderer'),
1135 self._rhodecode_user)
1135 self._rhodecode_user)
1136 except ValueError:
1136 except ValueError:
1137 msg = _(u'Cannot update closed pull requests.')
1137 msg = _(u'Cannot update closed pull requests.')
1138 h.flash(msg, category='error')
1138 h.flash(msg, category='error')
1139 return
1139 return
1140 else:
1140 else:
1141 Session().commit()
1141 Session().commit()
1142
1142
1143 msg = _(u'Pull request title & description updated.')
1143 msg = _(u'Pull request title & description updated.')
1144 h.flash(msg, category='success')
1144 h.flash(msg, category='success')
1145 return
1145 return
1146
1146
1147 def _update_commits(self, pull_request):
1147 def _update_commits(self, pull_request):
1148 _ = self.request.translate
1148 _ = self.request.translate
1149
1149
1150 with pull_request.set_state(PullRequest.STATE_UPDATING):
1150 with pull_request.set_state(PullRequest.STATE_UPDATING):
1151 resp = PullRequestModel().update_commits(
1151 resp = PullRequestModel().update_commits(
1152 pull_request, self._rhodecode_db_user)
1152 pull_request, self._rhodecode_db_user)
1153
1153
1154 if resp.executed:
1154 if resp.executed:
1155
1155
1156 if resp.target_changed and resp.source_changed:
1156 if resp.target_changed and resp.source_changed:
1157 changed = 'target and source repositories'
1157 changed = 'target and source repositories'
1158 elif resp.target_changed and not resp.source_changed:
1158 elif resp.target_changed and not resp.source_changed:
1159 changed = 'target repository'
1159 changed = 'target repository'
1160 elif not resp.target_changed and resp.source_changed:
1160 elif not resp.target_changed and resp.source_changed:
1161 changed = 'source repository'
1161 changed = 'source repository'
1162 else:
1162 else:
1163 changed = 'nothing'
1163 changed = 'nothing'
1164
1164
1165 msg = _(u'Pull request updated to "{source_commit_id}" with '
1165 msg = _(u'Pull request updated to "{source_commit_id}" with '
1166 u'{count_added} added, {count_removed} removed commits. '
1166 u'{count_added} added, {count_removed} removed commits. '
1167 u'Source of changes: {change_source}')
1167 u'Source of changes: {change_source}')
1168 msg = msg.format(
1168 msg = msg.format(
1169 source_commit_id=pull_request.source_ref_parts.commit_id,
1169 source_commit_id=pull_request.source_ref_parts.commit_id,
1170 count_added=len(resp.changes.added),
1170 count_added=len(resp.changes.added),
1171 count_removed=len(resp.changes.removed),
1171 count_removed=len(resp.changes.removed),
1172 change_source=changed)
1172 change_source=changed)
1173 h.flash(msg, category='success')
1173 h.flash(msg, category='success')
1174
1174
1175 channel = '/repo${}$/pr/{}'.format(
1175 channel = '/repo${}$/pr/{}'.format(
1176 pull_request.target_repo.repo_name, pull_request.pull_request_id)
1176 pull_request.target_repo.repo_name, pull_request.pull_request_id)
1177 message = msg + (
1177 message = msg + (
1178 ' - <a onclick="window.location.reload()">'
1178 ' - <a onclick="window.location.reload()">'
1179 '<strong>{}</strong></a>'.format(_('Reload page')))
1179 '<strong>{}</strong></a>'.format(_('Reload page')))
1180 channelstream.post_message(
1180 channelstream.post_message(
1181 channel, message, self._rhodecode_user.username,
1181 channel, message, self._rhodecode_user.username,
1182 registry=self.request.registry)
1182 registry=self.request.registry)
1183 else:
1183 else:
1184 msg = PullRequestModel.UPDATE_STATUS_MESSAGES[resp.reason]
1184 msg = PullRequestModel.UPDATE_STATUS_MESSAGES[resp.reason]
1185 warning_reasons = [
1185 warning_reasons = [
1186 UpdateFailureReason.NO_CHANGE,
1186 UpdateFailureReason.NO_CHANGE,
1187 UpdateFailureReason.WRONG_REF_TYPE,
1187 UpdateFailureReason.WRONG_REF_TYPE,
1188 ]
1188 ]
1189 category = 'warning' if resp.reason in warning_reasons else 'error'
1189 category = 'warning' if resp.reason in warning_reasons else 'error'
1190 h.flash(msg, category=category)
1190 h.flash(msg, category=category)
1191
1191
1192 @LoginRequired()
1192 @LoginRequired()
1193 @NotAnonymous()
1193 @NotAnonymous()
1194 @HasRepoPermissionAnyDecorator(
1194 @HasRepoPermissionAnyDecorator(
1195 'repository.read', 'repository.write', 'repository.admin')
1195 'repository.read', 'repository.write', 'repository.admin')
1196 @CSRFRequired()
1196 @CSRFRequired()
1197 @view_config(
1197 @view_config(
1198 route_name='pullrequest_merge', request_method='POST',
1198 route_name='pullrequest_merge', request_method='POST',
1199 renderer='json_ext')
1199 renderer='json_ext')
1200 def pull_request_merge(self):
1200 def pull_request_merge(self):
1201 """
1201 """
1202 Merge will perform a server-side merge of the specified
1202 Merge will perform a server-side merge of the specified
1203 pull request, if the pull request is approved and mergeable.
1203 pull request, if the pull request is approved and mergeable.
1204 After successful merging, the pull request is automatically
1204 After successful merging, the pull request is automatically
1205 closed, with a relevant comment.
1205 closed, with a relevant comment.
1206 """
1206 """
1207 pull_request = PullRequest.get_or_404(
1207 pull_request = PullRequest.get_or_404(
1208 self.request.matchdict['pull_request_id'])
1208 self.request.matchdict['pull_request_id'])
1209 _ = self.request.translate
1209 _ = self.request.translate
1210
1210
1211 if pull_request.is_state_changing():
1211 if pull_request.is_state_changing():
1212 log.debug('show: forbidden because pull request is in state %s',
1212 log.debug('show: forbidden because pull request is in state %s',
1213 pull_request.pull_request_state)
1213 pull_request.pull_request_state)
1214 msg = _(u'Cannot merge pull requests in state other than `{}`. '
1214 msg = _(u'Cannot merge pull requests in state other than `{}`. '
1215 u'Current state is: `{}`').format(PullRequest.STATE_CREATED,
1215 u'Current state is: `{}`').format(PullRequest.STATE_CREATED,
1216 pull_request.pull_request_state)
1216 pull_request.pull_request_state)
1217 h.flash(msg, category='error')
1217 h.flash(msg, category='error')
1218 raise HTTPFound(
1218 raise HTTPFound(
1219 h.route_path('pullrequest_show',
1219 h.route_path('pullrequest_show',
1220 repo_name=pull_request.target_repo.repo_name,
1220 repo_name=pull_request.target_repo.repo_name,
1221 pull_request_id=pull_request.pull_request_id))
1221 pull_request_id=pull_request.pull_request_id))
1222
1222
1223 self.load_default_context()
1223 self.load_default_context()
1224
1224
1225 with pull_request.set_state(PullRequest.STATE_UPDATING):
1225 with pull_request.set_state(PullRequest.STATE_UPDATING):
1226 check = MergeCheck.validate(
1226 check = MergeCheck.validate(
1227 pull_request, auth_user=self._rhodecode_user,
1227 pull_request, auth_user=self._rhodecode_user,
1228 translator=self.request.translate)
1228 translator=self.request.translate)
1229 merge_possible = not check.failed
1229 merge_possible = not check.failed
1230
1230
1231 for err_type, error_msg in check.errors:
1231 for err_type, error_msg in check.errors:
1232 h.flash(error_msg, category=err_type)
1232 h.flash(error_msg, category=err_type)
1233
1233
1234 if merge_possible:
1234 if merge_possible:
1235 log.debug("Pre-conditions checked, trying to merge.")
1235 log.debug("Pre-conditions checked, trying to merge.")
1236 extras = vcs_operation_context(
1236 extras = vcs_operation_context(
1237 self.request.environ, repo_name=pull_request.target_repo.repo_name,
1237 self.request.environ, repo_name=pull_request.target_repo.repo_name,
1238 username=self._rhodecode_db_user.username, action='push',
1238 username=self._rhodecode_db_user.username, action='push',
1239 scm=pull_request.target_repo.repo_type)
1239 scm=pull_request.target_repo.repo_type)
1240 with pull_request.set_state(PullRequest.STATE_UPDATING):
1240 with pull_request.set_state(PullRequest.STATE_UPDATING):
1241 self._merge_pull_request(
1241 self._merge_pull_request(
1242 pull_request, self._rhodecode_db_user, extras)
1242 pull_request, self._rhodecode_db_user, extras)
1243 else:
1243 else:
1244 log.debug("Pre-conditions failed, NOT merging.")
1244 log.debug("Pre-conditions failed, NOT merging.")
1245
1245
1246 raise HTTPFound(
1246 raise HTTPFound(
1247 h.route_path('pullrequest_show',
1247 h.route_path('pullrequest_show',
1248 repo_name=pull_request.target_repo.repo_name,
1248 repo_name=pull_request.target_repo.repo_name,
1249 pull_request_id=pull_request.pull_request_id))
1249 pull_request_id=pull_request.pull_request_id))
1250
1250
1251 def _merge_pull_request(self, pull_request, user, extras):
1251 def _merge_pull_request(self, pull_request, user, extras):
1252 _ = self.request.translate
1252 _ = self.request.translate
1253 merge_resp = PullRequestModel().merge_repo(pull_request, user, extras=extras)
1253 merge_resp = PullRequestModel().merge_repo(pull_request, user, extras=extras)
1254
1254
1255 if merge_resp.executed:
1255 if merge_resp.executed:
1256 log.debug("The merge was successful, closing the pull request.")
1256 log.debug("The merge was successful, closing the pull request.")
1257 PullRequestModel().close_pull_request(
1257 PullRequestModel().close_pull_request(
1258 pull_request.pull_request_id, user)
1258 pull_request.pull_request_id, user)
1259 Session().commit()
1259 Session().commit()
1260 msg = _('Pull request was successfully merged and closed.')
1260 msg = _('Pull request was successfully merged and closed.')
1261 h.flash(msg, category='success')
1261 h.flash(msg, category='success')
1262 else:
1262 else:
1263 log.debug(
1263 log.debug(
1264 "The merge was not successful. Merge response: %s", merge_resp)
1264 "The merge was not successful. Merge response: %s", merge_resp)
1265 msg = merge_resp.merge_status_message
1265 msg = merge_resp.merge_status_message
1266 h.flash(msg, category='error')
1266 h.flash(msg, category='error')
1267
1267
1268 def _update_reviewers(self, pull_request, review_members, reviewer_rules):
1268 def _update_reviewers(self, pull_request, review_members, reviewer_rules):
1269 _ = self.request.translate
1269 _ = self.request.translate
1270
1270
1271 get_default_reviewers_data, validate_default_reviewers = \
1271 get_default_reviewers_data, validate_default_reviewers = \
1272 PullRequestModel().get_reviewer_functions()
1272 PullRequestModel().get_reviewer_functions()
1273
1273
1274 try:
1274 try:
1275 reviewers = validate_default_reviewers(review_members, reviewer_rules)
1275 reviewers = validate_default_reviewers(review_members, reviewer_rules)
1276 except ValueError as e:
1276 except ValueError as e:
1277 log.error('Reviewers Validation: {}'.format(e))
1277 log.error('Reviewers Validation: {}'.format(e))
1278 h.flash(e, category='error')
1278 h.flash(e, category='error')
1279 return
1279 return
1280
1280
1281 old_calculated_status = pull_request.calculated_review_status()
1281 old_calculated_status = pull_request.calculated_review_status()
1282 PullRequestModel().update_reviewers(
1282 PullRequestModel().update_reviewers(
1283 pull_request, reviewers, self._rhodecode_user)
1283 pull_request, reviewers, self._rhodecode_user)
1284 h.flash(_('Pull request reviewers updated.'), category='success')
1284 h.flash(_('Pull request reviewers updated.'), category='success')
1285 Session().commit()
1285 Session().commit()
1286
1286
1287 # trigger status changed if change in reviewers changes the status
1287 # trigger status changed if change in reviewers changes the status
1288 calculated_status = pull_request.calculated_review_status()
1288 calculated_status = pull_request.calculated_review_status()
1289 if old_calculated_status != calculated_status:
1289 if old_calculated_status != calculated_status:
1290 PullRequestModel().trigger_pull_request_hook(
1290 PullRequestModel().trigger_pull_request_hook(
1291 pull_request, self._rhodecode_user, 'review_status_change',
1291 pull_request, self._rhodecode_user, 'review_status_change',
1292 data={'status': calculated_status})
1292 data={'status': calculated_status})
1293
1293
1294 @LoginRequired()
1294 @LoginRequired()
1295 @NotAnonymous()
1295 @NotAnonymous()
1296 @HasRepoPermissionAnyDecorator(
1296 @HasRepoPermissionAnyDecorator(
1297 'repository.read', 'repository.write', 'repository.admin')
1297 'repository.read', 'repository.write', 'repository.admin')
1298 @CSRFRequired()
1298 @CSRFRequired()
1299 @view_config(
1299 @view_config(
1300 route_name='pullrequest_delete', request_method='POST',
1300 route_name='pullrequest_delete', request_method='POST',
1301 renderer='json_ext')
1301 renderer='json_ext')
1302 def pull_request_delete(self):
1302 def pull_request_delete(self):
1303 _ = self.request.translate
1303 _ = self.request.translate
1304
1304
1305 pull_request = PullRequest.get_or_404(
1305 pull_request = PullRequest.get_or_404(
1306 self.request.matchdict['pull_request_id'])
1306 self.request.matchdict['pull_request_id'])
1307 self.load_default_context()
1307 self.load_default_context()
1308
1308
1309 pr_closed = pull_request.is_closed()
1309 pr_closed = pull_request.is_closed()
1310 allowed_to_delete = PullRequestModel().check_user_delete(
1310 allowed_to_delete = PullRequestModel().check_user_delete(
1311 pull_request, self._rhodecode_user) and not pr_closed
1311 pull_request, self._rhodecode_user) and not pr_closed
1312
1312
1313 # only owner can delete it !
1313 # only owner can delete it !
1314 if allowed_to_delete:
1314 if allowed_to_delete:
1315 PullRequestModel().delete(pull_request, self._rhodecode_user)
1315 PullRequestModel().delete(pull_request, self._rhodecode_user)
1316 Session().commit()
1316 Session().commit()
1317 h.flash(_('Successfully deleted pull request'),
1317 h.flash(_('Successfully deleted pull request'),
1318 category='success')
1318 category='success')
1319 raise HTTPFound(h.route_path('pullrequest_show_all',
1319 raise HTTPFound(h.route_path('pullrequest_show_all',
1320 repo_name=self.db_repo_name))
1320 repo_name=self.db_repo_name))
1321
1321
1322 log.warning('user %s tried to delete pull request without access',
1322 log.warning('user %s tried to delete pull request without access',
1323 self._rhodecode_user)
1323 self._rhodecode_user)
1324 raise HTTPNotFound()
1324 raise HTTPNotFound()
1325
1325
1326 @LoginRequired()
1326 @LoginRequired()
1327 @NotAnonymous()
1327 @NotAnonymous()
1328 @HasRepoPermissionAnyDecorator(
1328 @HasRepoPermissionAnyDecorator(
1329 'repository.read', 'repository.write', 'repository.admin')
1329 'repository.read', 'repository.write', 'repository.admin')
1330 @CSRFRequired()
1330 @CSRFRequired()
1331 @view_config(
1331 @view_config(
1332 route_name='pullrequest_comment_create', request_method='POST',
1332 route_name='pullrequest_comment_create', request_method='POST',
1333 renderer='json_ext')
1333 renderer='json_ext')
1334 def pull_request_comment_create(self):
1334 def pull_request_comment_create(self):
1335 _ = self.request.translate
1335 _ = self.request.translate
1336
1336
1337 pull_request = PullRequest.get_or_404(
1337 pull_request = PullRequest.get_or_404(
1338 self.request.matchdict['pull_request_id'])
1338 self.request.matchdict['pull_request_id'])
1339 pull_request_id = pull_request.pull_request_id
1339 pull_request_id = pull_request.pull_request_id
1340
1340
1341 if pull_request.is_closed():
1341 if pull_request.is_closed():
1342 log.debug('comment: forbidden because pull request is closed')
1342 log.debug('comment: forbidden because pull request is closed')
1343 raise HTTPForbidden()
1343 raise HTTPForbidden()
1344
1344
1345 allowed_to_comment = PullRequestModel().check_user_comment(
1345 allowed_to_comment = PullRequestModel().check_user_comment(
1346 pull_request, self._rhodecode_user)
1346 pull_request, self._rhodecode_user)
1347 if not allowed_to_comment:
1347 if not allowed_to_comment:
1348 log.debug(
1348 log.debug(
1349 'comment: forbidden because pull request is from forbidden repo')
1349 'comment: forbidden because pull request is from forbidden repo')
1350 raise HTTPForbidden()
1350 raise HTTPForbidden()
1351
1351
1352 c = self.load_default_context()
1352 c = self.load_default_context()
1353
1353
1354 status = self.request.POST.get('changeset_status', None)
1354 status = self.request.POST.get('changeset_status', None)
1355 text = self.request.POST.get('text')
1355 text = self.request.POST.get('text')
1356 comment_type = self.request.POST.get('comment_type')
1356 comment_type = self.request.POST.get('comment_type')
1357 resolves_comment_id = self.request.POST.get('resolves_comment_id', None)
1357 resolves_comment_id = self.request.POST.get('resolves_comment_id', None)
1358 close_pull_request = self.request.POST.get('close_pull_request')
1358 close_pull_request = self.request.POST.get('close_pull_request')
1359
1359
1360 # the logic here should work like following, if we submit close
1360 # the logic here should work like following, if we submit close
1361 # pr comment, use `close_pull_request_with_comment` function
1361 # pr comment, use `close_pull_request_with_comment` function
1362 # else handle regular comment logic
1362 # else handle regular comment logic
1363
1363
1364 if close_pull_request:
1364 if close_pull_request:
1365 # only owner or admin or person with write permissions
1365 # only owner or admin or person with write permissions
1366 allowed_to_close = PullRequestModel().check_user_update(
1366 allowed_to_close = PullRequestModel().check_user_update(
1367 pull_request, self._rhodecode_user)
1367 pull_request, self._rhodecode_user)
1368 if not allowed_to_close:
1368 if not allowed_to_close:
1369 log.debug('comment: forbidden because not allowed to close '
1369 log.debug('comment: forbidden because not allowed to close '
1370 'pull request %s', pull_request_id)
1370 'pull request %s', pull_request_id)
1371 raise HTTPForbidden()
1371 raise HTTPForbidden()
1372
1372
1373 # This also triggers `review_status_change`
1373 # This also triggers `review_status_change`
1374 comment, status = PullRequestModel().close_pull_request_with_comment(
1374 comment, status = PullRequestModel().close_pull_request_with_comment(
1375 pull_request, self._rhodecode_user, self.db_repo, message=text,
1375 pull_request, self._rhodecode_user, self.db_repo, message=text,
1376 auth_user=self._rhodecode_user)
1376 auth_user=self._rhodecode_user)
1377 Session().flush()
1377 Session().flush()
1378
1378
1379 PullRequestModel().trigger_pull_request_hook(
1379 PullRequestModel().trigger_pull_request_hook(
1380 pull_request, self._rhodecode_user, 'comment',
1380 pull_request, self._rhodecode_user, 'comment',
1381 data={'comment': comment})
1381 data={'comment': comment})
1382
1382
1383 else:
1383 else:
1384 # regular comment case, could be inline, or one with status.
1384 # regular comment case, could be inline, or one with status.
1385 # for that one we check also permissions
1385 # for that one we check also permissions
1386
1386
1387 allowed_to_change_status = PullRequestModel().check_user_change_status(
1387 allowed_to_change_status = PullRequestModel().check_user_change_status(
1388 pull_request, self._rhodecode_user)
1388 pull_request, self._rhodecode_user)
1389
1389
1390 if status and allowed_to_change_status:
1390 if status and allowed_to_change_status:
1391 message = (_('Status change %(transition_icon)s %(status)s')
1391 message = (_('Status change %(transition_icon)s %(status)s')
1392 % {'transition_icon': '>',
1392 % {'transition_icon': '>',
1393 'status': ChangesetStatus.get_status_lbl(status)})
1393 'status': ChangesetStatus.get_status_lbl(status)})
1394 text = text or message
1394 text = text or message
1395
1395
1396 comment = CommentsModel().create(
1396 comment = CommentsModel().create(
1397 text=text,
1397 text=text,
1398 repo=self.db_repo.repo_id,
1398 repo=self.db_repo.repo_id,
1399 user=self._rhodecode_user.user_id,
1399 user=self._rhodecode_user.user_id,
1400 pull_request=pull_request,
1400 pull_request=pull_request,
1401 f_path=self.request.POST.get('f_path'),
1401 f_path=self.request.POST.get('f_path'),
1402 line_no=self.request.POST.get('line'),
1402 line_no=self.request.POST.get('line'),
1403 status_change=(ChangesetStatus.get_status_lbl(status)
1403 status_change=(ChangesetStatus.get_status_lbl(status)
1404 if status and allowed_to_change_status else None),
1404 if status and allowed_to_change_status else None),
1405 status_change_type=(status
1405 status_change_type=(status
1406 if status and allowed_to_change_status else None),
1406 if status and allowed_to_change_status else None),
1407 comment_type=comment_type,
1407 comment_type=comment_type,
1408 resolves_comment_id=resolves_comment_id,
1408 resolves_comment_id=resolves_comment_id,
1409 auth_user=self._rhodecode_user
1409 auth_user=self._rhodecode_user
1410 )
1410 )
1411
1411
1412 if allowed_to_change_status:
1412 if allowed_to_change_status:
1413 # calculate old status before we change it
1413 # calculate old status before we change it
1414 old_calculated_status = pull_request.calculated_review_status()
1414 old_calculated_status = pull_request.calculated_review_status()
1415
1415
1416 # get status if set !
1416 # get status if set !
1417 if status:
1417 if status:
1418 ChangesetStatusModel().set_status(
1418 ChangesetStatusModel().set_status(
1419 self.db_repo.repo_id,
1419 self.db_repo.repo_id,
1420 status,
1420 status,
1421 self._rhodecode_user.user_id,
1421 self._rhodecode_user.user_id,
1422 comment,
1422 comment,
1423 pull_request=pull_request
1423 pull_request=pull_request
1424 )
1424 )
1425
1425
1426 Session().flush()
1426 Session().flush()
1427 # this is somehow required to get access to some relationship
1427 # this is somehow required to get access to some relationship
1428 # loaded on comment
1428 # loaded on comment
1429 Session().refresh(comment)
1429 Session().refresh(comment)
1430
1430
1431 PullRequestModel().trigger_pull_request_hook(
1431 PullRequestModel().trigger_pull_request_hook(
1432 pull_request, self._rhodecode_user, 'comment',
1432 pull_request, self._rhodecode_user, 'comment',
1433 data={'comment': comment})
1433 data={'comment': comment})
1434
1434
1435 # we now calculate the status of pull request, and based on that
1435 # we now calculate the status of pull request, and based on that
1436 # calculation we set the commits status
1436 # calculation we set the commits status
1437 calculated_status = pull_request.calculated_review_status()
1437 calculated_status = pull_request.calculated_review_status()
1438 if old_calculated_status != calculated_status:
1438 if old_calculated_status != calculated_status:
1439 PullRequestModel().trigger_pull_request_hook(
1439 PullRequestModel().trigger_pull_request_hook(
1440 pull_request, self._rhodecode_user, 'review_status_change',
1440 pull_request, self._rhodecode_user, 'review_status_change',
1441 data={'status': calculated_status})
1441 data={'status': calculated_status})
1442
1442
1443 Session().commit()
1443 Session().commit()
1444
1444
1445 data = {
1445 data = {
1446 'target_id': h.safeid(h.safe_unicode(
1446 'target_id': h.safeid(h.safe_unicode(
1447 self.request.POST.get('f_path'))),
1447 self.request.POST.get('f_path'))),
1448 }
1448 }
1449 if comment:
1449 if comment:
1450 c.co = comment
1450 c.co = comment
1451 rendered_comment = render(
1451 rendered_comment = render(
1452 'rhodecode:templates/changeset/changeset_comment_block.mako',
1452 'rhodecode:templates/changeset/changeset_comment_block.mako',
1453 self._get_template_context(c), self.request)
1453 self._get_template_context(c), self.request)
1454
1454
1455 data.update(comment.get_dict())
1455 data.update(comment.get_dict())
1456 data.update({'rendered_text': rendered_comment})
1456 data.update({'rendered_text': rendered_comment})
1457
1457
1458 return data
1458 return data
1459
1459
1460 @LoginRequired()
1460 @LoginRequired()
1461 @NotAnonymous()
1461 @NotAnonymous()
1462 @HasRepoPermissionAnyDecorator(
1462 @HasRepoPermissionAnyDecorator(
1463 'repository.read', 'repository.write', 'repository.admin')
1463 'repository.read', 'repository.write', 'repository.admin')
1464 @CSRFRequired()
1464 @CSRFRequired()
1465 @view_config(
1465 @view_config(
1466 route_name='pullrequest_comment_delete', request_method='POST',
1466 route_name='pullrequest_comment_delete', request_method='POST',
1467 renderer='json_ext')
1467 renderer='json_ext')
1468 def pull_request_comment_delete(self):
1468 def pull_request_comment_delete(self):
1469 pull_request = PullRequest.get_or_404(
1469 pull_request = PullRequest.get_or_404(
1470 self.request.matchdict['pull_request_id'])
1470 self.request.matchdict['pull_request_id'])
1471
1471
1472 comment = ChangesetComment.get_or_404(
1472 comment = ChangesetComment.get_or_404(
1473 self.request.matchdict['comment_id'])
1473 self.request.matchdict['comment_id'])
1474 comment_id = comment.comment_id
1474 comment_id = comment.comment_id
1475
1475
1476 if comment.immutable:
1477 # don't allow deleting comments that are immutable
1478 raise HTTPForbidden()
1479
1476 if pull_request.is_closed():
1480 if pull_request.is_closed():
1477 log.debug('comment: forbidden because pull request is closed')
1481 log.debug('comment: forbidden because pull request is closed')
1478 raise HTTPForbidden()
1482 raise HTTPForbidden()
1479
1483
1480 if not comment:
1484 if not comment:
1481 log.debug('Comment with id:%s not found, skipping', comment_id)
1485 log.debug('Comment with id:%s not found, skipping', comment_id)
1482 # comment already deleted in another call probably
1486 # comment already deleted in another call probably
1483 return True
1487 return True
1484
1488
1485 if comment.pull_request.is_closed():
1489 if comment.pull_request.is_closed():
1486 # don't allow deleting comments on closed pull request
1490 # don't allow deleting comments on closed pull request
1487 raise HTTPForbidden()
1491 raise HTTPForbidden()
1488
1492
1489 is_repo_admin = h.HasRepoPermissionAny('repository.admin')(self.db_repo_name)
1493 is_repo_admin = h.HasRepoPermissionAny('repository.admin')(self.db_repo_name)
1490 super_admin = h.HasPermissionAny('hg.admin')()
1494 super_admin = h.HasPermissionAny('hg.admin')()
1491 comment_owner = comment.author.user_id == self._rhodecode_user.user_id
1495 comment_owner = comment.author.user_id == self._rhodecode_user.user_id
1492 is_repo_comment = comment.repo.repo_name == self.db_repo_name
1496 is_repo_comment = comment.repo.repo_name == self.db_repo_name
1493 comment_repo_admin = is_repo_admin and is_repo_comment
1497 comment_repo_admin = is_repo_admin and is_repo_comment
1494
1498
1495 if super_admin or comment_owner or comment_repo_admin:
1499 if super_admin or comment_owner or comment_repo_admin:
1496 old_calculated_status = comment.pull_request.calculated_review_status()
1500 old_calculated_status = comment.pull_request.calculated_review_status()
1497 CommentsModel().delete(comment=comment, auth_user=self._rhodecode_user)
1501 CommentsModel().delete(comment=comment, auth_user=self._rhodecode_user)
1498 Session().commit()
1502 Session().commit()
1499 calculated_status = comment.pull_request.calculated_review_status()
1503 calculated_status = comment.pull_request.calculated_review_status()
1500 if old_calculated_status != calculated_status:
1504 if old_calculated_status != calculated_status:
1501 PullRequestModel().trigger_pull_request_hook(
1505 PullRequestModel().trigger_pull_request_hook(
1502 comment.pull_request, self._rhodecode_user, 'review_status_change',
1506 comment.pull_request, self._rhodecode_user, 'review_status_change',
1503 data={'status': calculated_status})
1507 data={'status': calculated_status})
1504 return True
1508 return True
1505 else:
1509 else:
1506 log.warning('No permissions for user %s to delete comment_id: %s',
1510 log.warning('No permissions for user %s to delete comment_id: %s',
1507 self._rhodecode_db_user, comment_id)
1511 self._rhodecode_db_user, comment_id)
1508 raise HTTPNotFound()
1512 raise HTTPNotFound()
@@ -1,5578 +1,5586 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2020 RhodeCode GmbH
3 # Copyright (C) 2010-2020 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 Database Models for RhodeCode Enterprise
22 Database Models for RhodeCode Enterprise
23 """
23 """
24
24
25 import re
25 import re
26 import os
26 import os
27 import time
27 import time
28 import string
28 import string
29 import hashlib
29 import hashlib
30 import logging
30 import logging
31 import datetime
31 import datetime
32 import uuid
32 import uuid
33 import warnings
33 import warnings
34 import ipaddress
34 import ipaddress
35 import functools
35 import functools
36 import traceback
36 import traceback
37 import collections
37 import collections
38
38
39 from sqlalchemy import (
39 from sqlalchemy import (
40 or_, and_, not_, func, cast, TypeDecorator, event,
40 or_, and_, not_, func, cast, TypeDecorator, event,
41 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
41 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
42 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
42 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
43 Text, Float, PickleType, BigInteger)
43 Text, Float, PickleType, BigInteger)
44 from sqlalchemy.sql.expression import true, false, case
44 from sqlalchemy.sql.expression import true, false, case
45 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
45 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
46 from sqlalchemy.orm import (
46 from sqlalchemy.orm import (
47 relationship, joinedload, class_mapper, validates, aliased)
47 relationship, joinedload, class_mapper, validates, aliased)
48 from sqlalchemy.ext.declarative import declared_attr
48 from sqlalchemy.ext.declarative import declared_attr
49 from sqlalchemy.ext.hybrid import hybrid_property
49 from sqlalchemy.ext.hybrid import hybrid_property
50 from sqlalchemy.exc import IntegrityError # pragma: no cover
50 from sqlalchemy.exc import IntegrityError # pragma: no cover
51 from sqlalchemy.dialects.mysql import LONGTEXT
51 from sqlalchemy.dialects.mysql import LONGTEXT
52 from zope.cachedescriptors.property import Lazy as LazyProperty
52 from zope.cachedescriptors.property import Lazy as LazyProperty
53 from pyramid import compat
53 from pyramid import compat
54 from pyramid.threadlocal import get_current_request
54 from pyramid.threadlocal import get_current_request
55 from webhelpers2.text import remove_formatting
55 from webhelpers2.text import remove_formatting
56
56
57 from rhodecode.translation import _
57 from rhodecode.translation import _
58 from rhodecode.lib.vcs import get_vcs_instance, VCSError
58 from rhodecode.lib.vcs import get_vcs_instance, VCSError
59 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
59 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
60 from rhodecode.lib.utils2 import (
60 from rhodecode.lib.utils2 import (
61 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
61 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
62 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
62 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
63 glob2re, StrictAttributeDict, cleaned_uri, datetime_to_time, OrderedDefaultDict)
63 glob2re, StrictAttributeDict, cleaned_uri, datetime_to_time, OrderedDefaultDict)
64 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
64 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
65 JsonRaw
65 JsonRaw
66 from rhodecode.lib.ext_json import json
66 from rhodecode.lib.ext_json import json
67 from rhodecode.lib.caching_query import FromCache
67 from rhodecode.lib.caching_query import FromCache
68 from rhodecode.lib.encrypt import AESCipher, validate_and_get_enc_data
68 from rhodecode.lib.encrypt import AESCipher, validate_and_get_enc_data
69 from rhodecode.lib.encrypt2 import Encryptor
69 from rhodecode.lib.encrypt2 import Encryptor
70 from rhodecode.lib.exceptions import (
70 from rhodecode.lib.exceptions import (
71 ArtifactMetadataDuplicate, ArtifactMetadataBadValueType)
71 ArtifactMetadataDuplicate, ArtifactMetadataBadValueType)
72 from rhodecode.model.meta import Base, Session
72 from rhodecode.model.meta import Base, Session
73
73
74 URL_SEP = '/'
74 URL_SEP = '/'
75 log = logging.getLogger(__name__)
75 log = logging.getLogger(__name__)
76
76
77 # =============================================================================
77 # =============================================================================
78 # BASE CLASSES
78 # BASE CLASSES
79 # =============================================================================
79 # =============================================================================
80
80
81 # this is propagated from .ini file rhodecode.encrypted_values.secret or
81 # this is propagated from .ini file rhodecode.encrypted_values.secret or
82 # beaker.session.secret if first is not set.
82 # beaker.session.secret if first is not set.
83 # and initialized at environment.py
83 # and initialized at environment.py
84 ENCRYPTION_KEY = None
84 ENCRYPTION_KEY = None
85
85
86 # used to sort permissions by types, '#' used here is not allowed to be in
86 # used to sort permissions by types, '#' used here is not allowed to be in
87 # usernames, and it's very early in sorted string.printable table.
87 # usernames, and it's very early in sorted string.printable table.
88 PERMISSION_TYPE_SORT = {
88 PERMISSION_TYPE_SORT = {
89 'admin': '####',
89 'admin': '####',
90 'write': '###',
90 'write': '###',
91 'read': '##',
91 'read': '##',
92 'none': '#',
92 'none': '#',
93 }
93 }
94
94
95
95
96 def display_user_sort(obj):
96 def display_user_sort(obj):
97 """
97 """
98 Sort function used to sort permissions in .permissions() function of
98 Sort function used to sort permissions in .permissions() function of
99 Repository, RepoGroup, UserGroup. Also it put the default user in front
99 Repository, RepoGroup, UserGroup. Also it put the default user in front
100 of all other resources
100 of all other resources
101 """
101 """
102
102
103 if obj.username == User.DEFAULT_USER:
103 if obj.username == User.DEFAULT_USER:
104 return '#####'
104 return '#####'
105 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
105 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
106 return prefix + obj.username
106 return prefix + obj.username
107
107
108
108
109 def display_user_group_sort(obj):
109 def display_user_group_sort(obj):
110 """
110 """
111 Sort function used to sort permissions in .permissions() function of
111 Sort function used to sort permissions in .permissions() function of
112 Repository, RepoGroup, UserGroup. Also it put the default user in front
112 Repository, RepoGroup, UserGroup. Also it put the default user in front
113 of all other resources
113 of all other resources
114 """
114 """
115
115
116 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
116 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
117 return prefix + obj.users_group_name
117 return prefix + obj.users_group_name
118
118
119
119
120 def _hash_key(k):
120 def _hash_key(k):
121 return sha1_safe(k)
121 return sha1_safe(k)
122
122
123
123
124 def in_filter_generator(qry, items, limit=500):
124 def in_filter_generator(qry, items, limit=500):
125 """
125 """
126 Splits IN() into multiple with OR
126 Splits IN() into multiple with OR
127 e.g.::
127 e.g.::
128 cnt = Repository.query().filter(
128 cnt = Repository.query().filter(
129 or_(
129 or_(
130 *in_filter_generator(Repository.repo_id, range(100000))
130 *in_filter_generator(Repository.repo_id, range(100000))
131 )).count()
131 )).count()
132 """
132 """
133 if not items:
133 if not items:
134 # empty list will cause empty query which might cause security issues
134 # empty list will cause empty query which might cause security issues
135 # this can lead to hidden unpleasant results
135 # this can lead to hidden unpleasant results
136 items = [-1]
136 items = [-1]
137
137
138 parts = []
138 parts = []
139 for chunk in xrange(0, len(items), limit):
139 for chunk in xrange(0, len(items), limit):
140 parts.append(
140 parts.append(
141 qry.in_(items[chunk: chunk + limit])
141 qry.in_(items[chunk: chunk + limit])
142 )
142 )
143
143
144 return parts
144 return parts
145
145
146
146
147 base_table_args = {
147 base_table_args = {
148 'extend_existing': True,
148 'extend_existing': True,
149 'mysql_engine': 'InnoDB',
149 'mysql_engine': 'InnoDB',
150 'mysql_charset': 'utf8',
150 'mysql_charset': 'utf8',
151 'sqlite_autoincrement': True
151 'sqlite_autoincrement': True
152 }
152 }
153
153
154
154
155 class EncryptedTextValue(TypeDecorator):
155 class EncryptedTextValue(TypeDecorator):
156 """
156 """
157 Special column for encrypted long text data, use like::
157 Special column for encrypted long text data, use like::
158
158
159 value = Column("encrypted_value", EncryptedValue(), nullable=False)
159 value = Column("encrypted_value", EncryptedValue(), nullable=False)
160
160
161 This column is intelligent so if value is in unencrypted form it return
161 This column is intelligent so if value is in unencrypted form it return
162 unencrypted form, but on save it always encrypts
162 unencrypted form, but on save it always encrypts
163 """
163 """
164 impl = Text
164 impl = Text
165
165
166 def process_bind_param(self, value, dialect):
166 def process_bind_param(self, value, dialect):
167 """
167 """
168 Setter for storing value
168 Setter for storing value
169 """
169 """
170 import rhodecode
170 import rhodecode
171 if not value:
171 if not value:
172 return value
172 return value
173
173
174 # protect against double encrypting if values is already encrypted
174 # protect against double encrypting if values is already encrypted
175 if value.startswith('enc$aes$') \
175 if value.startswith('enc$aes$') \
176 or value.startswith('enc$aes_hmac$') \
176 or value.startswith('enc$aes_hmac$') \
177 or value.startswith('enc2$'):
177 or value.startswith('enc2$'):
178 raise ValueError('value needs to be in unencrypted format, '
178 raise ValueError('value needs to be in unencrypted format, '
179 'ie. not starting with enc$ or enc2$')
179 'ie. not starting with enc$ or enc2$')
180
180
181 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
181 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
182 if algo == 'aes':
182 if algo == 'aes':
183 return 'enc$aes_hmac$%s' % AESCipher(ENCRYPTION_KEY, hmac=True).encrypt(value)
183 return 'enc$aes_hmac$%s' % AESCipher(ENCRYPTION_KEY, hmac=True).encrypt(value)
184 elif algo == 'fernet':
184 elif algo == 'fernet':
185 return Encryptor(ENCRYPTION_KEY).encrypt(value)
185 return Encryptor(ENCRYPTION_KEY).encrypt(value)
186 else:
186 else:
187 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
187 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
188
188
189 def process_result_value(self, value, dialect):
189 def process_result_value(self, value, dialect):
190 """
190 """
191 Getter for retrieving value
191 Getter for retrieving value
192 """
192 """
193
193
194 import rhodecode
194 import rhodecode
195 if not value:
195 if not value:
196 return value
196 return value
197
197
198 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
198 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
199 enc_strict_mode = str2bool(rhodecode.CONFIG.get('rhodecode.encrypted_values.strict') or True)
199 enc_strict_mode = str2bool(rhodecode.CONFIG.get('rhodecode.encrypted_values.strict') or True)
200 if algo == 'aes':
200 if algo == 'aes':
201 decrypted_data = validate_and_get_enc_data(value, ENCRYPTION_KEY, enc_strict_mode)
201 decrypted_data = validate_and_get_enc_data(value, ENCRYPTION_KEY, enc_strict_mode)
202 elif algo == 'fernet':
202 elif algo == 'fernet':
203 return Encryptor(ENCRYPTION_KEY).decrypt(value)
203 return Encryptor(ENCRYPTION_KEY).decrypt(value)
204 else:
204 else:
205 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
205 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
206 return decrypted_data
206 return decrypted_data
207
207
208
208
209 class BaseModel(object):
209 class BaseModel(object):
210 """
210 """
211 Base Model for all classes
211 Base Model for all classes
212 """
212 """
213
213
214 @classmethod
214 @classmethod
215 def _get_keys(cls):
215 def _get_keys(cls):
216 """return column names for this model """
216 """return column names for this model """
217 return class_mapper(cls).c.keys()
217 return class_mapper(cls).c.keys()
218
218
219 def get_dict(self):
219 def get_dict(self):
220 """
220 """
221 return dict with keys and values corresponding
221 return dict with keys and values corresponding
222 to this model data """
222 to this model data """
223
223
224 d = {}
224 d = {}
225 for k in self._get_keys():
225 for k in self._get_keys():
226 d[k] = getattr(self, k)
226 d[k] = getattr(self, k)
227
227
228 # also use __json__() if present to get additional fields
228 # also use __json__() if present to get additional fields
229 _json_attr = getattr(self, '__json__', None)
229 _json_attr = getattr(self, '__json__', None)
230 if _json_attr:
230 if _json_attr:
231 # update with attributes from __json__
231 # update with attributes from __json__
232 if callable(_json_attr):
232 if callable(_json_attr):
233 _json_attr = _json_attr()
233 _json_attr = _json_attr()
234 for k, val in _json_attr.iteritems():
234 for k, val in _json_attr.iteritems():
235 d[k] = val
235 d[k] = val
236 return d
236 return d
237
237
238 def get_appstruct(self):
238 def get_appstruct(self):
239 """return list with keys and values tuples corresponding
239 """return list with keys and values tuples corresponding
240 to this model data """
240 to this model data """
241
241
242 lst = []
242 lst = []
243 for k in self._get_keys():
243 for k in self._get_keys():
244 lst.append((k, getattr(self, k),))
244 lst.append((k, getattr(self, k),))
245 return lst
245 return lst
246
246
247 def populate_obj(self, populate_dict):
247 def populate_obj(self, populate_dict):
248 """populate model with data from given populate_dict"""
248 """populate model with data from given populate_dict"""
249
249
250 for k in self._get_keys():
250 for k in self._get_keys():
251 if k in populate_dict:
251 if k in populate_dict:
252 setattr(self, k, populate_dict[k])
252 setattr(self, k, populate_dict[k])
253
253
254 @classmethod
254 @classmethod
255 def query(cls):
255 def query(cls):
256 return Session().query(cls)
256 return Session().query(cls)
257
257
258 @classmethod
258 @classmethod
259 def get(cls, id_):
259 def get(cls, id_):
260 if id_:
260 if id_:
261 return cls.query().get(id_)
261 return cls.query().get(id_)
262
262
263 @classmethod
263 @classmethod
264 def get_or_404(cls, id_):
264 def get_or_404(cls, id_):
265 from pyramid.httpexceptions import HTTPNotFound
265 from pyramid.httpexceptions import HTTPNotFound
266
266
267 try:
267 try:
268 id_ = int(id_)
268 id_ = int(id_)
269 except (TypeError, ValueError):
269 except (TypeError, ValueError):
270 raise HTTPNotFound()
270 raise HTTPNotFound()
271
271
272 res = cls.query().get(id_)
272 res = cls.query().get(id_)
273 if not res:
273 if not res:
274 raise HTTPNotFound()
274 raise HTTPNotFound()
275 return res
275 return res
276
276
277 @classmethod
277 @classmethod
278 def getAll(cls):
278 def getAll(cls):
279 # deprecated and left for backward compatibility
279 # deprecated and left for backward compatibility
280 return cls.get_all()
280 return cls.get_all()
281
281
282 @classmethod
282 @classmethod
283 def get_all(cls):
283 def get_all(cls):
284 return cls.query().all()
284 return cls.query().all()
285
285
286 @classmethod
286 @classmethod
287 def delete(cls, id_):
287 def delete(cls, id_):
288 obj = cls.query().get(id_)
288 obj = cls.query().get(id_)
289 Session().delete(obj)
289 Session().delete(obj)
290
290
291 @classmethod
291 @classmethod
292 def identity_cache(cls, session, attr_name, value):
292 def identity_cache(cls, session, attr_name, value):
293 exist_in_session = []
293 exist_in_session = []
294 for (item_cls, pkey), instance in session.identity_map.items():
294 for (item_cls, pkey), instance in session.identity_map.items():
295 if cls == item_cls and getattr(instance, attr_name) == value:
295 if cls == item_cls and getattr(instance, attr_name) == value:
296 exist_in_session.append(instance)
296 exist_in_session.append(instance)
297 if exist_in_session:
297 if exist_in_session:
298 if len(exist_in_session) == 1:
298 if len(exist_in_session) == 1:
299 return exist_in_session[0]
299 return exist_in_session[0]
300 log.exception(
300 log.exception(
301 'multiple objects with attr %s and '
301 'multiple objects with attr %s and '
302 'value %s found with same name: %r',
302 'value %s found with same name: %r',
303 attr_name, value, exist_in_session)
303 attr_name, value, exist_in_session)
304
304
305 def __repr__(self):
305 def __repr__(self):
306 if hasattr(self, '__unicode__'):
306 if hasattr(self, '__unicode__'):
307 # python repr needs to return str
307 # python repr needs to return str
308 try:
308 try:
309 return safe_str(self.__unicode__())
309 return safe_str(self.__unicode__())
310 except UnicodeDecodeError:
310 except UnicodeDecodeError:
311 pass
311 pass
312 return '<DB:%s>' % (self.__class__.__name__)
312 return '<DB:%s>' % (self.__class__.__name__)
313
313
314
314
315 class RhodeCodeSetting(Base, BaseModel):
315 class RhodeCodeSetting(Base, BaseModel):
316 __tablename__ = 'rhodecode_settings'
316 __tablename__ = 'rhodecode_settings'
317 __table_args__ = (
317 __table_args__ = (
318 UniqueConstraint('app_settings_name'),
318 UniqueConstraint('app_settings_name'),
319 base_table_args
319 base_table_args
320 )
320 )
321
321
322 SETTINGS_TYPES = {
322 SETTINGS_TYPES = {
323 'str': safe_str,
323 'str': safe_str,
324 'int': safe_int,
324 'int': safe_int,
325 'unicode': safe_unicode,
325 'unicode': safe_unicode,
326 'bool': str2bool,
326 'bool': str2bool,
327 'list': functools.partial(aslist, sep=',')
327 'list': functools.partial(aslist, sep=',')
328 }
328 }
329 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
329 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
330 GLOBAL_CONF_KEY = 'app_settings'
330 GLOBAL_CONF_KEY = 'app_settings'
331
331
332 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
332 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
333 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
333 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
334 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
334 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
335 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
335 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
336
336
337 def __init__(self, key='', val='', type='unicode'):
337 def __init__(self, key='', val='', type='unicode'):
338 self.app_settings_name = key
338 self.app_settings_name = key
339 self.app_settings_type = type
339 self.app_settings_type = type
340 self.app_settings_value = val
340 self.app_settings_value = val
341
341
342 @validates('_app_settings_value')
342 @validates('_app_settings_value')
343 def validate_settings_value(self, key, val):
343 def validate_settings_value(self, key, val):
344 assert type(val) == unicode
344 assert type(val) == unicode
345 return val
345 return val
346
346
347 @hybrid_property
347 @hybrid_property
348 def app_settings_value(self):
348 def app_settings_value(self):
349 v = self._app_settings_value
349 v = self._app_settings_value
350 _type = self.app_settings_type
350 _type = self.app_settings_type
351 if _type:
351 if _type:
352 _type = self.app_settings_type.split('.')[0]
352 _type = self.app_settings_type.split('.')[0]
353 # decode the encrypted value
353 # decode the encrypted value
354 if 'encrypted' in self.app_settings_type:
354 if 'encrypted' in self.app_settings_type:
355 cipher = EncryptedTextValue()
355 cipher = EncryptedTextValue()
356 v = safe_unicode(cipher.process_result_value(v, None))
356 v = safe_unicode(cipher.process_result_value(v, None))
357
357
358 converter = self.SETTINGS_TYPES.get(_type) or \
358 converter = self.SETTINGS_TYPES.get(_type) or \
359 self.SETTINGS_TYPES['unicode']
359 self.SETTINGS_TYPES['unicode']
360 return converter(v)
360 return converter(v)
361
361
362 @app_settings_value.setter
362 @app_settings_value.setter
363 def app_settings_value(self, val):
363 def app_settings_value(self, val):
364 """
364 """
365 Setter that will always make sure we use unicode in app_settings_value
365 Setter that will always make sure we use unicode in app_settings_value
366
366
367 :param val:
367 :param val:
368 """
368 """
369 val = safe_unicode(val)
369 val = safe_unicode(val)
370 # encode the encrypted value
370 # encode the encrypted value
371 if 'encrypted' in self.app_settings_type:
371 if 'encrypted' in self.app_settings_type:
372 cipher = EncryptedTextValue()
372 cipher = EncryptedTextValue()
373 val = safe_unicode(cipher.process_bind_param(val, None))
373 val = safe_unicode(cipher.process_bind_param(val, None))
374 self._app_settings_value = val
374 self._app_settings_value = val
375
375
376 @hybrid_property
376 @hybrid_property
377 def app_settings_type(self):
377 def app_settings_type(self):
378 return self._app_settings_type
378 return self._app_settings_type
379
379
380 @app_settings_type.setter
380 @app_settings_type.setter
381 def app_settings_type(self, val):
381 def app_settings_type(self, val):
382 if val.split('.')[0] not in self.SETTINGS_TYPES:
382 if val.split('.')[0] not in self.SETTINGS_TYPES:
383 raise Exception('type must be one of %s got %s'
383 raise Exception('type must be one of %s got %s'
384 % (self.SETTINGS_TYPES.keys(), val))
384 % (self.SETTINGS_TYPES.keys(), val))
385 self._app_settings_type = val
385 self._app_settings_type = val
386
386
387 @classmethod
387 @classmethod
388 def get_by_prefix(cls, prefix):
388 def get_by_prefix(cls, prefix):
389 return RhodeCodeSetting.query()\
389 return RhodeCodeSetting.query()\
390 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
390 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
391 .all()
391 .all()
392
392
393 def __unicode__(self):
393 def __unicode__(self):
394 return u"<%s('%s:%s[%s]')>" % (
394 return u"<%s('%s:%s[%s]')>" % (
395 self.__class__.__name__,
395 self.__class__.__name__,
396 self.app_settings_name, self.app_settings_value,
396 self.app_settings_name, self.app_settings_value,
397 self.app_settings_type
397 self.app_settings_type
398 )
398 )
399
399
400
400
401 class RhodeCodeUi(Base, BaseModel):
401 class RhodeCodeUi(Base, BaseModel):
402 __tablename__ = 'rhodecode_ui'
402 __tablename__ = 'rhodecode_ui'
403 __table_args__ = (
403 __table_args__ = (
404 UniqueConstraint('ui_key'),
404 UniqueConstraint('ui_key'),
405 base_table_args
405 base_table_args
406 )
406 )
407
407
408 HOOK_REPO_SIZE = 'changegroup.repo_size'
408 HOOK_REPO_SIZE = 'changegroup.repo_size'
409 # HG
409 # HG
410 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
410 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
411 HOOK_PULL = 'outgoing.pull_logger'
411 HOOK_PULL = 'outgoing.pull_logger'
412 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
412 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
413 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
413 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
414 HOOK_PUSH = 'changegroup.push_logger'
414 HOOK_PUSH = 'changegroup.push_logger'
415 HOOK_PUSH_KEY = 'pushkey.key_push'
415 HOOK_PUSH_KEY = 'pushkey.key_push'
416
416
417 HOOKS_BUILTIN = [
417 HOOKS_BUILTIN = [
418 HOOK_PRE_PULL,
418 HOOK_PRE_PULL,
419 HOOK_PULL,
419 HOOK_PULL,
420 HOOK_PRE_PUSH,
420 HOOK_PRE_PUSH,
421 HOOK_PRETX_PUSH,
421 HOOK_PRETX_PUSH,
422 HOOK_PUSH,
422 HOOK_PUSH,
423 HOOK_PUSH_KEY,
423 HOOK_PUSH_KEY,
424 ]
424 ]
425
425
426 # TODO: johbo: Unify way how hooks are configured for git and hg,
426 # TODO: johbo: Unify way how hooks are configured for git and hg,
427 # git part is currently hardcoded.
427 # git part is currently hardcoded.
428
428
429 # SVN PATTERNS
429 # SVN PATTERNS
430 SVN_BRANCH_ID = 'vcs_svn_branch'
430 SVN_BRANCH_ID = 'vcs_svn_branch'
431 SVN_TAG_ID = 'vcs_svn_tag'
431 SVN_TAG_ID = 'vcs_svn_tag'
432
432
433 ui_id = Column(
433 ui_id = Column(
434 "ui_id", Integer(), nullable=False, unique=True, default=None,
434 "ui_id", Integer(), nullable=False, unique=True, default=None,
435 primary_key=True)
435 primary_key=True)
436 ui_section = Column(
436 ui_section = Column(
437 "ui_section", String(255), nullable=True, unique=None, default=None)
437 "ui_section", String(255), nullable=True, unique=None, default=None)
438 ui_key = Column(
438 ui_key = Column(
439 "ui_key", String(255), nullable=True, unique=None, default=None)
439 "ui_key", String(255), nullable=True, unique=None, default=None)
440 ui_value = Column(
440 ui_value = Column(
441 "ui_value", String(255), nullable=True, unique=None, default=None)
441 "ui_value", String(255), nullable=True, unique=None, default=None)
442 ui_active = Column(
442 ui_active = Column(
443 "ui_active", Boolean(), nullable=True, unique=None, default=True)
443 "ui_active", Boolean(), nullable=True, unique=None, default=True)
444
444
445 def __repr__(self):
445 def __repr__(self):
446 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
446 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
447 self.ui_key, self.ui_value)
447 self.ui_key, self.ui_value)
448
448
449
449
450 class RepoRhodeCodeSetting(Base, BaseModel):
450 class RepoRhodeCodeSetting(Base, BaseModel):
451 __tablename__ = 'repo_rhodecode_settings'
451 __tablename__ = 'repo_rhodecode_settings'
452 __table_args__ = (
452 __table_args__ = (
453 UniqueConstraint(
453 UniqueConstraint(
454 'app_settings_name', 'repository_id',
454 'app_settings_name', 'repository_id',
455 name='uq_repo_rhodecode_setting_name_repo_id'),
455 name='uq_repo_rhodecode_setting_name_repo_id'),
456 base_table_args
456 base_table_args
457 )
457 )
458
458
459 repository_id = Column(
459 repository_id = Column(
460 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
460 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
461 nullable=False)
461 nullable=False)
462 app_settings_id = Column(
462 app_settings_id = Column(
463 "app_settings_id", Integer(), nullable=False, unique=True,
463 "app_settings_id", Integer(), nullable=False, unique=True,
464 default=None, primary_key=True)
464 default=None, primary_key=True)
465 app_settings_name = Column(
465 app_settings_name = Column(
466 "app_settings_name", String(255), nullable=True, unique=None,
466 "app_settings_name", String(255), nullable=True, unique=None,
467 default=None)
467 default=None)
468 _app_settings_value = Column(
468 _app_settings_value = Column(
469 "app_settings_value", String(4096), nullable=True, unique=None,
469 "app_settings_value", String(4096), nullable=True, unique=None,
470 default=None)
470 default=None)
471 _app_settings_type = Column(
471 _app_settings_type = Column(
472 "app_settings_type", String(255), nullable=True, unique=None,
472 "app_settings_type", String(255), nullable=True, unique=None,
473 default=None)
473 default=None)
474
474
475 repository = relationship('Repository')
475 repository = relationship('Repository')
476
476
477 def __init__(self, repository_id, key='', val='', type='unicode'):
477 def __init__(self, repository_id, key='', val='', type='unicode'):
478 self.repository_id = repository_id
478 self.repository_id = repository_id
479 self.app_settings_name = key
479 self.app_settings_name = key
480 self.app_settings_type = type
480 self.app_settings_type = type
481 self.app_settings_value = val
481 self.app_settings_value = val
482
482
483 @validates('_app_settings_value')
483 @validates('_app_settings_value')
484 def validate_settings_value(self, key, val):
484 def validate_settings_value(self, key, val):
485 assert type(val) == unicode
485 assert type(val) == unicode
486 return val
486 return val
487
487
488 @hybrid_property
488 @hybrid_property
489 def app_settings_value(self):
489 def app_settings_value(self):
490 v = self._app_settings_value
490 v = self._app_settings_value
491 type_ = self.app_settings_type
491 type_ = self.app_settings_type
492 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
492 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
493 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
493 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
494 return converter(v)
494 return converter(v)
495
495
496 @app_settings_value.setter
496 @app_settings_value.setter
497 def app_settings_value(self, val):
497 def app_settings_value(self, val):
498 """
498 """
499 Setter that will always make sure we use unicode in app_settings_value
499 Setter that will always make sure we use unicode in app_settings_value
500
500
501 :param val:
501 :param val:
502 """
502 """
503 self._app_settings_value = safe_unicode(val)
503 self._app_settings_value = safe_unicode(val)
504
504
505 @hybrid_property
505 @hybrid_property
506 def app_settings_type(self):
506 def app_settings_type(self):
507 return self._app_settings_type
507 return self._app_settings_type
508
508
509 @app_settings_type.setter
509 @app_settings_type.setter
510 def app_settings_type(self, val):
510 def app_settings_type(self, val):
511 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
511 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
512 if val not in SETTINGS_TYPES:
512 if val not in SETTINGS_TYPES:
513 raise Exception('type must be one of %s got %s'
513 raise Exception('type must be one of %s got %s'
514 % (SETTINGS_TYPES.keys(), val))
514 % (SETTINGS_TYPES.keys(), val))
515 self._app_settings_type = val
515 self._app_settings_type = val
516
516
517 def __unicode__(self):
517 def __unicode__(self):
518 return u"<%s('%s:%s:%s[%s]')>" % (
518 return u"<%s('%s:%s:%s[%s]')>" % (
519 self.__class__.__name__, self.repository.repo_name,
519 self.__class__.__name__, self.repository.repo_name,
520 self.app_settings_name, self.app_settings_value,
520 self.app_settings_name, self.app_settings_value,
521 self.app_settings_type
521 self.app_settings_type
522 )
522 )
523
523
524
524
525 class RepoRhodeCodeUi(Base, BaseModel):
525 class RepoRhodeCodeUi(Base, BaseModel):
526 __tablename__ = 'repo_rhodecode_ui'
526 __tablename__ = 'repo_rhodecode_ui'
527 __table_args__ = (
527 __table_args__ = (
528 UniqueConstraint(
528 UniqueConstraint(
529 'repository_id', 'ui_section', 'ui_key',
529 'repository_id', 'ui_section', 'ui_key',
530 name='uq_repo_rhodecode_ui_repository_id_section_key'),
530 name='uq_repo_rhodecode_ui_repository_id_section_key'),
531 base_table_args
531 base_table_args
532 )
532 )
533
533
534 repository_id = Column(
534 repository_id = Column(
535 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
535 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
536 nullable=False)
536 nullable=False)
537 ui_id = Column(
537 ui_id = Column(
538 "ui_id", Integer(), nullable=False, unique=True, default=None,
538 "ui_id", Integer(), nullable=False, unique=True, default=None,
539 primary_key=True)
539 primary_key=True)
540 ui_section = Column(
540 ui_section = Column(
541 "ui_section", String(255), nullable=True, unique=None, default=None)
541 "ui_section", String(255), nullable=True, unique=None, default=None)
542 ui_key = Column(
542 ui_key = Column(
543 "ui_key", String(255), nullable=True, unique=None, default=None)
543 "ui_key", String(255), nullable=True, unique=None, default=None)
544 ui_value = Column(
544 ui_value = Column(
545 "ui_value", String(255), nullable=True, unique=None, default=None)
545 "ui_value", String(255), nullable=True, unique=None, default=None)
546 ui_active = Column(
546 ui_active = Column(
547 "ui_active", Boolean(), nullable=True, unique=None, default=True)
547 "ui_active", Boolean(), nullable=True, unique=None, default=True)
548
548
549 repository = relationship('Repository')
549 repository = relationship('Repository')
550
550
551 def __repr__(self):
551 def __repr__(self):
552 return '<%s[%s:%s]%s=>%s]>' % (
552 return '<%s[%s:%s]%s=>%s]>' % (
553 self.__class__.__name__, self.repository.repo_name,
553 self.__class__.__name__, self.repository.repo_name,
554 self.ui_section, self.ui_key, self.ui_value)
554 self.ui_section, self.ui_key, self.ui_value)
555
555
556
556
557 class User(Base, BaseModel):
557 class User(Base, BaseModel):
558 __tablename__ = 'users'
558 __tablename__ = 'users'
559 __table_args__ = (
559 __table_args__ = (
560 UniqueConstraint('username'), UniqueConstraint('email'),
560 UniqueConstraint('username'), UniqueConstraint('email'),
561 Index('u_username_idx', 'username'),
561 Index('u_username_idx', 'username'),
562 Index('u_email_idx', 'email'),
562 Index('u_email_idx', 'email'),
563 base_table_args
563 base_table_args
564 )
564 )
565
565
566 DEFAULT_USER = 'default'
566 DEFAULT_USER = 'default'
567 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
567 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
568 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
568 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
569
569
570 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
570 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
571 username = Column("username", String(255), nullable=True, unique=None, default=None)
571 username = Column("username", String(255), nullable=True, unique=None, default=None)
572 password = Column("password", String(255), nullable=True, unique=None, default=None)
572 password = Column("password", String(255), nullable=True, unique=None, default=None)
573 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
573 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
574 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
574 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
575 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
575 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
576 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
576 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
577 _email = Column("email", String(255), nullable=True, unique=None, default=None)
577 _email = Column("email", String(255), nullable=True, unique=None, default=None)
578 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
578 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
579 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
579 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
580 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
580 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
581
581
582 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
582 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
583 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
583 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
584 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
584 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
585 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
585 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
586 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
586 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
587 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
587 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
588
588
589 user_log = relationship('UserLog')
589 user_log = relationship('UserLog')
590 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all, delete-orphan')
590 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all, delete-orphan')
591
591
592 repositories = relationship('Repository')
592 repositories = relationship('Repository')
593 repository_groups = relationship('RepoGroup')
593 repository_groups = relationship('RepoGroup')
594 user_groups = relationship('UserGroup')
594 user_groups = relationship('UserGroup')
595
595
596 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
596 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
597 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
597 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
598
598
599 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all, delete-orphan')
599 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all, delete-orphan')
600 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
600 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
601 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
601 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
602
602
603 group_member = relationship('UserGroupMember', cascade='all')
603 group_member = relationship('UserGroupMember', cascade='all')
604
604
605 notifications = relationship('UserNotification', cascade='all')
605 notifications = relationship('UserNotification', cascade='all')
606 # notifications assigned to this user
606 # notifications assigned to this user
607 user_created_notifications = relationship('Notification', cascade='all')
607 user_created_notifications = relationship('Notification', cascade='all')
608 # comments created by this user
608 # comments created by this user
609 user_comments = relationship('ChangesetComment', cascade='all')
609 user_comments = relationship('ChangesetComment', cascade='all')
610 # user profile extra info
610 # user profile extra info
611 user_emails = relationship('UserEmailMap', cascade='all')
611 user_emails = relationship('UserEmailMap', cascade='all')
612 user_ip_map = relationship('UserIpMap', cascade='all')
612 user_ip_map = relationship('UserIpMap', cascade='all')
613 user_auth_tokens = relationship('UserApiKeys', cascade='all')
613 user_auth_tokens = relationship('UserApiKeys', cascade='all')
614 user_ssh_keys = relationship('UserSshKeys', cascade='all')
614 user_ssh_keys = relationship('UserSshKeys', cascade='all')
615
615
616 # gists
616 # gists
617 user_gists = relationship('Gist', cascade='all')
617 user_gists = relationship('Gist', cascade='all')
618 # user pull requests
618 # user pull requests
619 user_pull_requests = relationship('PullRequest', cascade='all')
619 user_pull_requests = relationship('PullRequest', cascade='all')
620 # external identities
620 # external identities
621 external_identities = relationship(
621 external_identities = relationship(
622 'ExternalIdentity',
622 'ExternalIdentity',
623 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
623 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
624 cascade='all')
624 cascade='all')
625 # review rules
625 # review rules
626 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
626 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
627
627
628 # artifacts owned
628 # artifacts owned
629 artifacts = relationship('FileStore', primaryjoin='FileStore.user_id==User.user_id')
629 artifacts = relationship('FileStore', primaryjoin='FileStore.user_id==User.user_id')
630
630
631 # no cascade, set NULL
631 # no cascade, set NULL
632 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_user_id==User.user_id')
632 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_user_id==User.user_id')
633
633
634 def __unicode__(self):
634 def __unicode__(self):
635 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
635 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
636 self.user_id, self.username)
636 self.user_id, self.username)
637
637
638 @hybrid_property
638 @hybrid_property
639 def email(self):
639 def email(self):
640 return self._email
640 return self._email
641
641
642 @email.setter
642 @email.setter
643 def email(self, val):
643 def email(self, val):
644 self._email = val.lower() if val else None
644 self._email = val.lower() if val else None
645
645
646 @hybrid_property
646 @hybrid_property
647 def first_name(self):
647 def first_name(self):
648 from rhodecode.lib import helpers as h
648 from rhodecode.lib import helpers as h
649 if self.name:
649 if self.name:
650 return h.escape(self.name)
650 return h.escape(self.name)
651 return self.name
651 return self.name
652
652
653 @hybrid_property
653 @hybrid_property
654 def last_name(self):
654 def last_name(self):
655 from rhodecode.lib import helpers as h
655 from rhodecode.lib import helpers as h
656 if self.lastname:
656 if self.lastname:
657 return h.escape(self.lastname)
657 return h.escape(self.lastname)
658 return self.lastname
658 return self.lastname
659
659
660 @hybrid_property
660 @hybrid_property
661 def api_key(self):
661 def api_key(self):
662 """
662 """
663 Fetch if exist an auth-token with role ALL connected to this user
663 Fetch if exist an auth-token with role ALL connected to this user
664 """
664 """
665 user_auth_token = UserApiKeys.query()\
665 user_auth_token = UserApiKeys.query()\
666 .filter(UserApiKeys.user_id == self.user_id)\
666 .filter(UserApiKeys.user_id == self.user_id)\
667 .filter(or_(UserApiKeys.expires == -1,
667 .filter(or_(UserApiKeys.expires == -1,
668 UserApiKeys.expires >= time.time()))\
668 UserApiKeys.expires >= time.time()))\
669 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
669 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
670 if user_auth_token:
670 if user_auth_token:
671 user_auth_token = user_auth_token.api_key
671 user_auth_token = user_auth_token.api_key
672
672
673 return user_auth_token
673 return user_auth_token
674
674
675 @api_key.setter
675 @api_key.setter
676 def api_key(self, val):
676 def api_key(self, val):
677 # don't allow to set API key this is deprecated for now
677 # don't allow to set API key this is deprecated for now
678 self._api_key = None
678 self._api_key = None
679
679
680 @property
680 @property
681 def reviewer_pull_requests(self):
681 def reviewer_pull_requests(self):
682 return PullRequestReviewers.query() \
682 return PullRequestReviewers.query() \
683 .options(joinedload(PullRequestReviewers.pull_request)) \
683 .options(joinedload(PullRequestReviewers.pull_request)) \
684 .filter(PullRequestReviewers.user_id == self.user_id) \
684 .filter(PullRequestReviewers.user_id == self.user_id) \
685 .all()
685 .all()
686
686
687 @property
687 @property
688 def firstname(self):
688 def firstname(self):
689 # alias for future
689 # alias for future
690 return self.name
690 return self.name
691
691
692 @property
692 @property
693 def emails(self):
693 def emails(self):
694 other = UserEmailMap.query()\
694 other = UserEmailMap.query()\
695 .filter(UserEmailMap.user == self) \
695 .filter(UserEmailMap.user == self) \
696 .order_by(UserEmailMap.email_id.asc()) \
696 .order_by(UserEmailMap.email_id.asc()) \
697 .all()
697 .all()
698 return [self.email] + [x.email for x in other]
698 return [self.email] + [x.email for x in other]
699
699
700 def emails_cached(self):
700 def emails_cached(self):
701 emails = UserEmailMap.query()\
701 emails = UserEmailMap.query()\
702 .filter(UserEmailMap.user == self) \
702 .filter(UserEmailMap.user == self) \
703 .order_by(UserEmailMap.email_id.asc())
703 .order_by(UserEmailMap.email_id.asc())
704
704
705 emails = emails.options(
705 emails = emails.options(
706 FromCache("sql_cache_short", "get_user_{}_emails".format(self.user_id))
706 FromCache("sql_cache_short", "get_user_{}_emails".format(self.user_id))
707 )
707 )
708
708
709 return [self.email] + [x.email for x in emails]
709 return [self.email] + [x.email for x in emails]
710
710
711 @property
711 @property
712 def auth_tokens(self):
712 def auth_tokens(self):
713 auth_tokens = self.get_auth_tokens()
713 auth_tokens = self.get_auth_tokens()
714 return [x.api_key for x in auth_tokens]
714 return [x.api_key for x in auth_tokens]
715
715
716 def get_auth_tokens(self):
716 def get_auth_tokens(self):
717 return UserApiKeys.query()\
717 return UserApiKeys.query()\
718 .filter(UserApiKeys.user == self)\
718 .filter(UserApiKeys.user == self)\
719 .order_by(UserApiKeys.user_api_key_id.asc())\
719 .order_by(UserApiKeys.user_api_key_id.asc())\
720 .all()
720 .all()
721
721
722 @LazyProperty
722 @LazyProperty
723 def feed_token(self):
723 def feed_token(self):
724 return self.get_feed_token()
724 return self.get_feed_token()
725
725
726 def get_feed_token(self, cache=True):
726 def get_feed_token(self, cache=True):
727 feed_tokens = UserApiKeys.query()\
727 feed_tokens = UserApiKeys.query()\
728 .filter(UserApiKeys.user == self)\
728 .filter(UserApiKeys.user == self)\
729 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
729 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
730 if cache:
730 if cache:
731 feed_tokens = feed_tokens.options(
731 feed_tokens = feed_tokens.options(
732 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
732 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
733
733
734 feed_tokens = feed_tokens.all()
734 feed_tokens = feed_tokens.all()
735 if feed_tokens:
735 if feed_tokens:
736 return feed_tokens[0].api_key
736 return feed_tokens[0].api_key
737 return 'NO_FEED_TOKEN_AVAILABLE'
737 return 'NO_FEED_TOKEN_AVAILABLE'
738
738
739 @LazyProperty
739 @LazyProperty
740 def artifact_token(self):
740 def artifact_token(self):
741 return self.get_artifact_token()
741 return self.get_artifact_token()
742
742
743 def get_artifact_token(self, cache=True):
743 def get_artifact_token(self, cache=True):
744 artifacts_tokens = UserApiKeys.query()\
744 artifacts_tokens = UserApiKeys.query()\
745 .filter(UserApiKeys.user == self)\
745 .filter(UserApiKeys.user == self)\
746 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
746 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
747 if cache:
747 if cache:
748 artifacts_tokens = artifacts_tokens.options(
748 artifacts_tokens = artifacts_tokens.options(
749 FromCache("sql_cache_short", "get_user_artifact_token_%s" % self.user_id))
749 FromCache("sql_cache_short", "get_user_artifact_token_%s" % self.user_id))
750
750
751 artifacts_tokens = artifacts_tokens.all()
751 artifacts_tokens = artifacts_tokens.all()
752 if artifacts_tokens:
752 if artifacts_tokens:
753 return artifacts_tokens[0].api_key
753 return artifacts_tokens[0].api_key
754 return 'NO_ARTIFACT_TOKEN_AVAILABLE'
754 return 'NO_ARTIFACT_TOKEN_AVAILABLE'
755
755
756 @classmethod
756 @classmethod
757 def get(cls, user_id, cache=False):
757 def get(cls, user_id, cache=False):
758 if not user_id:
758 if not user_id:
759 return
759 return
760
760
761 user = cls.query()
761 user = cls.query()
762 if cache:
762 if cache:
763 user = user.options(
763 user = user.options(
764 FromCache("sql_cache_short", "get_users_%s" % user_id))
764 FromCache("sql_cache_short", "get_users_%s" % user_id))
765 return user.get(user_id)
765 return user.get(user_id)
766
766
767 @classmethod
767 @classmethod
768 def extra_valid_auth_tokens(cls, user, role=None):
768 def extra_valid_auth_tokens(cls, user, role=None):
769 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
769 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
770 .filter(or_(UserApiKeys.expires == -1,
770 .filter(or_(UserApiKeys.expires == -1,
771 UserApiKeys.expires >= time.time()))
771 UserApiKeys.expires >= time.time()))
772 if role:
772 if role:
773 tokens = tokens.filter(or_(UserApiKeys.role == role,
773 tokens = tokens.filter(or_(UserApiKeys.role == role,
774 UserApiKeys.role == UserApiKeys.ROLE_ALL))
774 UserApiKeys.role == UserApiKeys.ROLE_ALL))
775 return tokens.all()
775 return tokens.all()
776
776
777 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
777 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
778 from rhodecode.lib import auth
778 from rhodecode.lib import auth
779
779
780 log.debug('Trying to authenticate user: %s via auth-token, '
780 log.debug('Trying to authenticate user: %s via auth-token, '
781 'and roles: %s', self, roles)
781 'and roles: %s', self, roles)
782
782
783 if not auth_token:
783 if not auth_token:
784 return False
784 return False
785
785
786 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
786 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
787 tokens_q = UserApiKeys.query()\
787 tokens_q = UserApiKeys.query()\
788 .filter(UserApiKeys.user_id == self.user_id)\
788 .filter(UserApiKeys.user_id == self.user_id)\
789 .filter(or_(UserApiKeys.expires == -1,
789 .filter(or_(UserApiKeys.expires == -1,
790 UserApiKeys.expires >= time.time()))
790 UserApiKeys.expires >= time.time()))
791
791
792 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
792 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
793
793
794 crypto_backend = auth.crypto_backend()
794 crypto_backend = auth.crypto_backend()
795 enc_token_map = {}
795 enc_token_map = {}
796 plain_token_map = {}
796 plain_token_map = {}
797 for token in tokens_q:
797 for token in tokens_q:
798 if token.api_key.startswith(crypto_backend.ENC_PREF):
798 if token.api_key.startswith(crypto_backend.ENC_PREF):
799 enc_token_map[token.api_key] = token
799 enc_token_map[token.api_key] = token
800 else:
800 else:
801 plain_token_map[token.api_key] = token
801 plain_token_map[token.api_key] = token
802 log.debug(
802 log.debug(
803 'Found %s plain and %s encrypted tokens to check for authentication for this user',
803 'Found %s plain and %s encrypted tokens to check for authentication for this user',
804 len(plain_token_map), len(enc_token_map))
804 len(plain_token_map), len(enc_token_map))
805
805
806 # plain token match comes first
806 # plain token match comes first
807 match = plain_token_map.get(auth_token)
807 match = plain_token_map.get(auth_token)
808
808
809 # check encrypted tokens now
809 # check encrypted tokens now
810 if not match:
810 if not match:
811 for token_hash, token in enc_token_map.items():
811 for token_hash, token in enc_token_map.items():
812 # NOTE(marcink): this is expensive to calculate, but most secure
812 # NOTE(marcink): this is expensive to calculate, but most secure
813 if crypto_backend.hash_check(auth_token, token_hash):
813 if crypto_backend.hash_check(auth_token, token_hash):
814 match = token
814 match = token
815 break
815 break
816
816
817 if match:
817 if match:
818 log.debug('Found matching token %s', match)
818 log.debug('Found matching token %s', match)
819 if match.repo_id:
819 if match.repo_id:
820 log.debug('Found scope, checking for scope match of token %s', match)
820 log.debug('Found scope, checking for scope match of token %s', match)
821 if match.repo_id == scope_repo_id:
821 if match.repo_id == scope_repo_id:
822 return True
822 return True
823 else:
823 else:
824 log.debug(
824 log.debug(
825 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
825 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
826 'and calling scope is:%s, skipping further checks',
826 'and calling scope is:%s, skipping further checks',
827 match.repo, scope_repo_id)
827 match.repo, scope_repo_id)
828 return False
828 return False
829 else:
829 else:
830 return True
830 return True
831
831
832 return False
832 return False
833
833
834 @property
834 @property
835 def ip_addresses(self):
835 def ip_addresses(self):
836 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
836 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
837 return [x.ip_addr for x in ret]
837 return [x.ip_addr for x in ret]
838
838
839 @property
839 @property
840 def username_and_name(self):
840 def username_and_name(self):
841 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
841 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
842
842
843 @property
843 @property
844 def username_or_name_or_email(self):
844 def username_or_name_or_email(self):
845 full_name = self.full_name if self.full_name is not ' ' else None
845 full_name = self.full_name if self.full_name is not ' ' else None
846 return self.username or full_name or self.email
846 return self.username or full_name or self.email
847
847
848 @property
848 @property
849 def full_name(self):
849 def full_name(self):
850 return '%s %s' % (self.first_name, self.last_name)
850 return '%s %s' % (self.first_name, self.last_name)
851
851
852 @property
852 @property
853 def full_name_or_username(self):
853 def full_name_or_username(self):
854 return ('%s %s' % (self.first_name, self.last_name)
854 return ('%s %s' % (self.first_name, self.last_name)
855 if (self.first_name and self.last_name) else self.username)
855 if (self.first_name and self.last_name) else self.username)
856
856
857 @property
857 @property
858 def full_contact(self):
858 def full_contact(self):
859 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
859 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
860
860
861 @property
861 @property
862 def short_contact(self):
862 def short_contact(self):
863 return '%s %s' % (self.first_name, self.last_name)
863 return '%s %s' % (self.first_name, self.last_name)
864
864
865 @property
865 @property
866 def is_admin(self):
866 def is_admin(self):
867 return self.admin
867 return self.admin
868
868
869 @property
869 @property
870 def language(self):
870 def language(self):
871 return self.user_data.get('language')
871 return self.user_data.get('language')
872
872
873 def AuthUser(self, **kwargs):
873 def AuthUser(self, **kwargs):
874 """
874 """
875 Returns instance of AuthUser for this user
875 Returns instance of AuthUser for this user
876 """
876 """
877 from rhodecode.lib.auth import AuthUser
877 from rhodecode.lib.auth import AuthUser
878 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
878 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
879
879
880 @hybrid_property
880 @hybrid_property
881 def user_data(self):
881 def user_data(self):
882 if not self._user_data:
882 if not self._user_data:
883 return {}
883 return {}
884
884
885 try:
885 try:
886 return json.loads(self._user_data)
886 return json.loads(self._user_data)
887 except TypeError:
887 except TypeError:
888 return {}
888 return {}
889
889
890 @user_data.setter
890 @user_data.setter
891 def user_data(self, val):
891 def user_data(self, val):
892 if not isinstance(val, dict):
892 if not isinstance(val, dict):
893 raise Exception('user_data must be dict, got %s' % type(val))
893 raise Exception('user_data must be dict, got %s' % type(val))
894 try:
894 try:
895 self._user_data = json.dumps(val)
895 self._user_data = json.dumps(val)
896 except Exception:
896 except Exception:
897 log.error(traceback.format_exc())
897 log.error(traceback.format_exc())
898
898
899 @classmethod
899 @classmethod
900 def get_by_username(cls, username, case_insensitive=False,
900 def get_by_username(cls, username, case_insensitive=False,
901 cache=False, identity_cache=False):
901 cache=False, identity_cache=False):
902 session = Session()
902 session = Session()
903
903
904 if case_insensitive:
904 if case_insensitive:
905 q = cls.query().filter(
905 q = cls.query().filter(
906 func.lower(cls.username) == func.lower(username))
906 func.lower(cls.username) == func.lower(username))
907 else:
907 else:
908 q = cls.query().filter(cls.username == username)
908 q = cls.query().filter(cls.username == username)
909
909
910 if cache:
910 if cache:
911 if identity_cache:
911 if identity_cache:
912 val = cls.identity_cache(session, 'username', username)
912 val = cls.identity_cache(session, 'username', username)
913 if val:
913 if val:
914 return val
914 return val
915 else:
915 else:
916 cache_key = "get_user_by_name_%s" % _hash_key(username)
916 cache_key = "get_user_by_name_%s" % _hash_key(username)
917 q = q.options(
917 q = q.options(
918 FromCache("sql_cache_short", cache_key))
918 FromCache("sql_cache_short", cache_key))
919
919
920 return q.scalar()
920 return q.scalar()
921
921
922 @classmethod
922 @classmethod
923 def get_by_auth_token(cls, auth_token, cache=False):
923 def get_by_auth_token(cls, auth_token, cache=False):
924 q = UserApiKeys.query()\
924 q = UserApiKeys.query()\
925 .filter(UserApiKeys.api_key == auth_token)\
925 .filter(UserApiKeys.api_key == auth_token)\
926 .filter(or_(UserApiKeys.expires == -1,
926 .filter(or_(UserApiKeys.expires == -1,
927 UserApiKeys.expires >= time.time()))
927 UserApiKeys.expires >= time.time()))
928 if cache:
928 if cache:
929 q = q.options(
929 q = q.options(
930 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
930 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
931
931
932 match = q.first()
932 match = q.first()
933 if match:
933 if match:
934 return match.user
934 return match.user
935
935
936 @classmethod
936 @classmethod
937 def get_by_email(cls, email, case_insensitive=False, cache=False):
937 def get_by_email(cls, email, case_insensitive=False, cache=False):
938
938
939 if case_insensitive:
939 if case_insensitive:
940 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
940 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
941
941
942 else:
942 else:
943 q = cls.query().filter(cls.email == email)
943 q = cls.query().filter(cls.email == email)
944
944
945 email_key = _hash_key(email)
945 email_key = _hash_key(email)
946 if cache:
946 if cache:
947 q = q.options(
947 q = q.options(
948 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
948 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
949
949
950 ret = q.scalar()
950 ret = q.scalar()
951 if ret is None:
951 if ret is None:
952 q = UserEmailMap.query()
952 q = UserEmailMap.query()
953 # try fetching in alternate email map
953 # try fetching in alternate email map
954 if case_insensitive:
954 if case_insensitive:
955 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
955 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
956 else:
956 else:
957 q = q.filter(UserEmailMap.email == email)
957 q = q.filter(UserEmailMap.email == email)
958 q = q.options(joinedload(UserEmailMap.user))
958 q = q.options(joinedload(UserEmailMap.user))
959 if cache:
959 if cache:
960 q = q.options(
960 q = q.options(
961 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
961 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
962 ret = getattr(q.scalar(), 'user', None)
962 ret = getattr(q.scalar(), 'user', None)
963
963
964 return ret
964 return ret
965
965
966 @classmethod
966 @classmethod
967 def get_from_cs_author(cls, author):
967 def get_from_cs_author(cls, author):
968 """
968 """
969 Tries to get User objects out of commit author string
969 Tries to get User objects out of commit author string
970
970
971 :param author:
971 :param author:
972 """
972 """
973 from rhodecode.lib.helpers import email, author_name
973 from rhodecode.lib.helpers import email, author_name
974 # Valid email in the attribute passed, see if they're in the system
974 # Valid email in the attribute passed, see if they're in the system
975 _email = email(author)
975 _email = email(author)
976 if _email:
976 if _email:
977 user = cls.get_by_email(_email, case_insensitive=True)
977 user = cls.get_by_email(_email, case_insensitive=True)
978 if user:
978 if user:
979 return user
979 return user
980 # Maybe we can match by username?
980 # Maybe we can match by username?
981 _author = author_name(author)
981 _author = author_name(author)
982 user = cls.get_by_username(_author, case_insensitive=True)
982 user = cls.get_by_username(_author, case_insensitive=True)
983 if user:
983 if user:
984 return user
984 return user
985
985
986 def update_userdata(self, **kwargs):
986 def update_userdata(self, **kwargs):
987 usr = self
987 usr = self
988 old = usr.user_data
988 old = usr.user_data
989 old.update(**kwargs)
989 old.update(**kwargs)
990 usr.user_data = old
990 usr.user_data = old
991 Session().add(usr)
991 Session().add(usr)
992 log.debug('updated userdata with %s', kwargs)
992 log.debug('updated userdata with %s', kwargs)
993
993
994 def update_lastlogin(self):
994 def update_lastlogin(self):
995 """Update user lastlogin"""
995 """Update user lastlogin"""
996 self.last_login = datetime.datetime.now()
996 self.last_login = datetime.datetime.now()
997 Session().add(self)
997 Session().add(self)
998 log.debug('updated user %s lastlogin', self.username)
998 log.debug('updated user %s lastlogin', self.username)
999
999
1000 def update_password(self, new_password):
1000 def update_password(self, new_password):
1001 from rhodecode.lib.auth import get_crypt_password
1001 from rhodecode.lib.auth import get_crypt_password
1002
1002
1003 self.password = get_crypt_password(new_password)
1003 self.password = get_crypt_password(new_password)
1004 Session().add(self)
1004 Session().add(self)
1005
1005
1006 @classmethod
1006 @classmethod
1007 def get_first_super_admin(cls):
1007 def get_first_super_admin(cls):
1008 user = User.query()\
1008 user = User.query()\
1009 .filter(User.admin == true()) \
1009 .filter(User.admin == true()) \
1010 .order_by(User.user_id.asc()) \
1010 .order_by(User.user_id.asc()) \
1011 .first()
1011 .first()
1012
1012
1013 if user is None:
1013 if user is None:
1014 raise Exception('FATAL: Missing administrative account!')
1014 raise Exception('FATAL: Missing administrative account!')
1015 return user
1015 return user
1016
1016
1017 @classmethod
1017 @classmethod
1018 def get_all_super_admins(cls, only_active=False):
1018 def get_all_super_admins(cls, only_active=False):
1019 """
1019 """
1020 Returns all admin accounts sorted by username
1020 Returns all admin accounts sorted by username
1021 """
1021 """
1022 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
1022 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
1023 if only_active:
1023 if only_active:
1024 qry = qry.filter(User.active == true())
1024 qry = qry.filter(User.active == true())
1025 return qry.all()
1025 return qry.all()
1026
1026
1027 @classmethod
1027 @classmethod
1028 def get_all_user_ids(cls, only_active=True):
1028 def get_all_user_ids(cls, only_active=True):
1029 """
1029 """
1030 Returns all users IDs
1030 Returns all users IDs
1031 """
1031 """
1032 qry = Session().query(User.user_id)
1032 qry = Session().query(User.user_id)
1033
1033
1034 if only_active:
1034 if only_active:
1035 qry = qry.filter(User.active == true())
1035 qry = qry.filter(User.active == true())
1036 return [x.user_id for x in qry]
1036 return [x.user_id for x in qry]
1037
1037
1038 @classmethod
1038 @classmethod
1039 def get_default_user(cls, cache=False, refresh=False):
1039 def get_default_user(cls, cache=False, refresh=False):
1040 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
1040 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
1041 if user is None:
1041 if user is None:
1042 raise Exception('FATAL: Missing default account!')
1042 raise Exception('FATAL: Missing default account!')
1043 if refresh:
1043 if refresh:
1044 # The default user might be based on outdated state which
1044 # The default user might be based on outdated state which
1045 # has been loaded from the cache.
1045 # has been loaded from the cache.
1046 # A call to refresh() ensures that the
1046 # A call to refresh() ensures that the
1047 # latest state from the database is used.
1047 # latest state from the database is used.
1048 Session().refresh(user)
1048 Session().refresh(user)
1049 return user
1049 return user
1050
1050
1051 def _get_default_perms(self, user, suffix=''):
1051 def _get_default_perms(self, user, suffix=''):
1052 from rhodecode.model.permission import PermissionModel
1052 from rhodecode.model.permission import PermissionModel
1053 return PermissionModel().get_default_perms(user.user_perms, suffix)
1053 return PermissionModel().get_default_perms(user.user_perms, suffix)
1054
1054
1055 def get_default_perms(self, suffix=''):
1055 def get_default_perms(self, suffix=''):
1056 return self._get_default_perms(self, suffix)
1056 return self._get_default_perms(self, suffix)
1057
1057
1058 def get_api_data(self, include_secrets=False, details='full'):
1058 def get_api_data(self, include_secrets=False, details='full'):
1059 """
1059 """
1060 Common function for generating user related data for API
1060 Common function for generating user related data for API
1061
1061
1062 :param include_secrets: By default secrets in the API data will be replaced
1062 :param include_secrets: By default secrets in the API data will be replaced
1063 by a placeholder value to prevent exposing this data by accident. In case
1063 by a placeholder value to prevent exposing this data by accident. In case
1064 this data shall be exposed, set this flag to ``True``.
1064 this data shall be exposed, set this flag to ``True``.
1065
1065
1066 :param details: details can be 'basic|full' basic gives only a subset of
1066 :param details: details can be 'basic|full' basic gives only a subset of
1067 the available user information that includes user_id, name and emails.
1067 the available user information that includes user_id, name and emails.
1068 """
1068 """
1069 user = self
1069 user = self
1070 user_data = self.user_data
1070 user_data = self.user_data
1071 data = {
1071 data = {
1072 'user_id': user.user_id,
1072 'user_id': user.user_id,
1073 'username': user.username,
1073 'username': user.username,
1074 'firstname': user.name,
1074 'firstname': user.name,
1075 'lastname': user.lastname,
1075 'lastname': user.lastname,
1076 'description': user.description,
1076 'description': user.description,
1077 'email': user.email,
1077 'email': user.email,
1078 'emails': user.emails,
1078 'emails': user.emails,
1079 }
1079 }
1080 if details == 'basic':
1080 if details == 'basic':
1081 return data
1081 return data
1082
1082
1083 auth_token_length = 40
1083 auth_token_length = 40
1084 auth_token_replacement = '*' * auth_token_length
1084 auth_token_replacement = '*' * auth_token_length
1085
1085
1086 extras = {
1086 extras = {
1087 'auth_tokens': [auth_token_replacement],
1087 'auth_tokens': [auth_token_replacement],
1088 'active': user.active,
1088 'active': user.active,
1089 'admin': user.admin,
1089 'admin': user.admin,
1090 'extern_type': user.extern_type,
1090 'extern_type': user.extern_type,
1091 'extern_name': user.extern_name,
1091 'extern_name': user.extern_name,
1092 'last_login': user.last_login,
1092 'last_login': user.last_login,
1093 'last_activity': user.last_activity,
1093 'last_activity': user.last_activity,
1094 'ip_addresses': user.ip_addresses,
1094 'ip_addresses': user.ip_addresses,
1095 'language': user_data.get('language')
1095 'language': user_data.get('language')
1096 }
1096 }
1097 data.update(extras)
1097 data.update(extras)
1098
1098
1099 if include_secrets:
1099 if include_secrets:
1100 data['auth_tokens'] = user.auth_tokens
1100 data['auth_tokens'] = user.auth_tokens
1101 return data
1101 return data
1102
1102
1103 def __json__(self):
1103 def __json__(self):
1104 data = {
1104 data = {
1105 'full_name': self.full_name,
1105 'full_name': self.full_name,
1106 'full_name_or_username': self.full_name_or_username,
1106 'full_name_or_username': self.full_name_or_username,
1107 'short_contact': self.short_contact,
1107 'short_contact': self.short_contact,
1108 'full_contact': self.full_contact,
1108 'full_contact': self.full_contact,
1109 }
1109 }
1110 data.update(self.get_api_data())
1110 data.update(self.get_api_data())
1111 return data
1111 return data
1112
1112
1113
1113
1114 class UserApiKeys(Base, BaseModel):
1114 class UserApiKeys(Base, BaseModel):
1115 __tablename__ = 'user_api_keys'
1115 __tablename__ = 'user_api_keys'
1116 __table_args__ = (
1116 __table_args__ = (
1117 Index('uak_api_key_idx', 'api_key'),
1117 Index('uak_api_key_idx', 'api_key'),
1118 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1118 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1119 base_table_args
1119 base_table_args
1120 )
1120 )
1121 __mapper_args__ = {}
1121 __mapper_args__ = {}
1122
1122
1123 # ApiKey role
1123 # ApiKey role
1124 ROLE_ALL = 'token_role_all'
1124 ROLE_ALL = 'token_role_all'
1125 ROLE_HTTP = 'token_role_http'
1125 ROLE_HTTP = 'token_role_http'
1126 ROLE_VCS = 'token_role_vcs'
1126 ROLE_VCS = 'token_role_vcs'
1127 ROLE_API = 'token_role_api'
1127 ROLE_API = 'token_role_api'
1128 ROLE_FEED = 'token_role_feed'
1128 ROLE_FEED = 'token_role_feed'
1129 ROLE_ARTIFACT_DOWNLOAD = 'role_artifact_download'
1129 ROLE_ARTIFACT_DOWNLOAD = 'role_artifact_download'
1130 ROLE_PASSWORD_RESET = 'token_password_reset'
1130 ROLE_PASSWORD_RESET = 'token_password_reset'
1131
1131
1132 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED, ROLE_ARTIFACT_DOWNLOAD]
1132 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED, ROLE_ARTIFACT_DOWNLOAD]
1133
1133
1134 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1134 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1135 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1135 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1136 api_key = Column("api_key", String(255), nullable=False, unique=True)
1136 api_key = Column("api_key", String(255), nullable=False, unique=True)
1137 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1137 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1138 expires = Column('expires', Float(53), nullable=False)
1138 expires = Column('expires', Float(53), nullable=False)
1139 role = Column('role', String(255), nullable=True)
1139 role = Column('role', String(255), nullable=True)
1140 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1140 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1141
1141
1142 # scope columns
1142 # scope columns
1143 repo_id = Column(
1143 repo_id = Column(
1144 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1144 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1145 nullable=True, unique=None, default=None)
1145 nullable=True, unique=None, default=None)
1146 repo = relationship('Repository', lazy='joined')
1146 repo = relationship('Repository', lazy='joined')
1147
1147
1148 repo_group_id = Column(
1148 repo_group_id = Column(
1149 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1149 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1150 nullable=True, unique=None, default=None)
1150 nullable=True, unique=None, default=None)
1151 repo_group = relationship('RepoGroup', lazy='joined')
1151 repo_group = relationship('RepoGroup', lazy='joined')
1152
1152
1153 user = relationship('User', lazy='joined')
1153 user = relationship('User', lazy='joined')
1154
1154
1155 def __unicode__(self):
1155 def __unicode__(self):
1156 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1156 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1157
1157
1158 def __json__(self):
1158 def __json__(self):
1159 data = {
1159 data = {
1160 'auth_token': self.api_key,
1160 'auth_token': self.api_key,
1161 'role': self.role,
1161 'role': self.role,
1162 'scope': self.scope_humanized,
1162 'scope': self.scope_humanized,
1163 'expired': self.expired
1163 'expired': self.expired
1164 }
1164 }
1165 return data
1165 return data
1166
1166
1167 def get_api_data(self, include_secrets=False):
1167 def get_api_data(self, include_secrets=False):
1168 data = self.__json__()
1168 data = self.__json__()
1169 if include_secrets:
1169 if include_secrets:
1170 return data
1170 return data
1171 else:
1171 else:
1172 data['auth_token'] = self.token_obfuscated
1172 data['auth_token'] = self.token_obfuscated
1173 return data
1173 return data
1174
1174
1175 @hybrid_property
1175 @hybrid_property
1176 def description_safe(self):
1176 def description_safe(self):
1177 from rhodecode.lib import helpers as h
1177 from rhodecode.lib import helpers as h
1178 return h.escape(self.description)
1178 return h.escape(self.description)
1179
1179
1180 @property
1180 @property
1181 def expired(self):
1181 def expired(self):
1182 if self.expires == -1:
1182 if self.expires == -1:
1183 return False
1183 return False
1184 return time.time() > self.expires
1184 return time.time() > self.expires
1185
1185
1186 @classmethod
1186 @classmethod
1187 def _get_role_name(cls, role):
1187 def _get_role_name(cls, role):
1188 return {
1188 return {
1189 cls.ROLE_ALL: _('all'),
1189 cls.ROLE_ALL: _('all'),
1190 cls.ROLE_HTTP: _('http/web interface'),
1190 cls.ROLE_HTTP: _('http/web interface'),
1191 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1191 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1192 cls.ROLE_API: _('api calls'),
1192 cls.ROLE_API: _('api calls'),
1193 cls.ROLE_FEED: _('feed access'),
1193 cls.ROLE_FEED: _('feed access'),
1194 cls.ROLE_ARTIFACT_DOWNLOAD: _('artifacts downloads'),
1194 cls.ROLE_ARTIFACT_DOWNLOAD: _('artifacts downloads'),
1195 }.get(role, role)
1195 }.get(role, role)
1196
1196
1197 @property
1197 @property
1198 def role_humanized(self):
1198 def role_humanized(self):
1199 return self._get_role_name(self.role)
1199 return self._get_role_name(self.role)
1200
1200
1201 def _get_scope(self):
1201 def _get_scope(self):
1202 if self.repo:
1202 if self.repo:
1203 return 'Repository: {}'.format(self.repo.repo_name)
1203 return 'Repository: {}'.format(self.repo.repo_name)
1204 if self.repo_group:
1204 if self.repo_group:
1205 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1205 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1206 return 'Global'
1206 return 'Global'
1207
1207
1208 @property
1208 @property
1209 def scope_humanized(self):
1209 def scope_humanized(self):
1210 return self._get_scope()
1210 return self._get_scope()
1211
1211
1212 @property
1212 @property
1213 def token_obfuscated(self):
1213 def token_obfuscated(self):
1214 if self.api_key:
1214 if self.api_key:
1215 return self.api_key[:4] + "****"
1215 return self.api_key[:4] + "****"
1216
1216
1217
1217
1218 class UserEmailMap(Base, BaseModel):
1218 class UserEmailMap(Base, BaseModel):
1219 __tablename__ = 'user_email_map'
1219 __tablename__ = 'user_email_map'
1220 __table_args__ = (
1220 __table_args__ = (
1221 Index('uem_email_idx', 'email'),
1221 Index('uem_email_idx', 'email'),
1222 UniqueConstraint('email'),
1222 UniqueConstraint('email'),
1223 base_table_args
1223 base_table_args
1224 )
1224 )
1225 __mapper_args__ = {}
1225 __mapper_args__ = {}
1226
1226
1227 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1227 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1228 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1228 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1229 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1229 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1230 user = relationship('User', lazy='joined')
1230 user = relationship('User', lazy='joined')
1231
1231
1232 @validates('_email')
1232 @validates('_email')
1233 def validate_email(self, key, email):
1233 def validate_email(self, key, email):
1234 # check if this email is not main one
1234 # check if this email is not main one
1235 main_email = Session().query(User).filter(User.email == email).scalar()
1235 main_email = Session().query(User).filter(User.email == email).scalar()
1236 if main_email is not None:
1236 if main_email is not None:
1237 raise AttributeError('email %s is present is user table' % email)
1237 raise AttributeError('email %s is present is user table' % email)
1238 return email
1238 return email
1239
1239
1240 @hybrid_property
1240 @hybrid_property
1241 def email(self):
1241 def email(self):
1242 return self._email
1242 return self._email
1243
1243
1244 @email.setter
1244 @email.setter
1245 def email(self, val):
1245 def email(self, val):
1246 self._email = val.lower() if val else None
1246 self._email = val.lower() if val else None
1247
1247
1248
1248
1249 class UserIpMap(Base, BaseModel):
1249 class UserIpMap(Base, BaseModel):
1250 __tablename__ = 'user_ip_map'
1250 __tablename__ = 'user_ip_map'
1251 __table_args__ = (
1251 __table_args__ = (
1252 UniqueConstraint('user_id', 'ip_addr'),
1252 UniqueConstraint('user_id', 'ip_addr'),
1253 base_table_args
1253 base_table_args
1254 )
1254 )
1255 __mapper_args__ = {}
1255 __mapper_args__ = {}
1256
1256
1257 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1257 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1258 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1258 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1259 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1259 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1260 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1260 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1261 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1261 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1262 user = relationship('User', lazy='joined')
1262 user = relationship('User', lazy='joined')
1263
1263
1264 @hybrid_property
1264 @hybrid_property
1265 def description_safe(self):
1265 def description_safe(self):
1266 from rhodecode.lib import helpers as h
1266 from rhodecode.lib import helpers as h
1267 return h.escape(self.description)
1267 return h.escape(self.description)
1268
1268
1269 @classmethod
1269 @classmethod
1270 def _get_ip_range(cls, ip_addr):
1270 def _get_ip_range(cls, ip_addr):
1271 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1271 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1272 return [str(net.network_address), str(net.broadcast_address)]
1272 return [str(net.network_address), str(net.broadcast_address)]
1273
1273
1274 def __json__(self):
1274 def __json__(self):
1275 return {
1275 return {
1276 'ip_addr': self.ip_addr,
1276 'ip_addr': self.ip_addr,
1277 'ip_range': self._get_ip_range(self.ip_addr),
1277 'ip_range': self._get_ip_range(self.ip_addr),
1278 }
1278 }
1279
1279
1280 def __unicode__(self):
1280 def __unicode__(self):
1281 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1281 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1282 self.user_id, self.ip_addr)
1282 self.user_id, self.ip_addr)
1283
1283
1284
1284
1285 class UserSshKeys(Base, BaseModel):
1285 class UserSshKeys(Base, BaseModel):
1286 __tablename__ = 'user_ssh_keys'
1286 __tablename__ = 'user_ssh_keys'
1287 __table_args__ = (
1287 __table_args__ = (
1288 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1288 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1289
1289
1290 UniqueConstraint('ssh_key_fingerprint'),
1290 UniqueConstraint('ssh_key_fingerprint'),
1291
1291
1292 base_table_args
1292 base_table_args
1293 )
1293 )
1294 __mapper_args__ = {}
1294 __mapper_args__ = {}
1295
1295
1296 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1296 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1297 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1297 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1298 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1298 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1299
1299
1300 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1300 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1301
1301
1302 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1302 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1303 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1303 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1304 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1304 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1305
1305
1306 user = relationship('User', lazy='joined')
1306 user = relationship('User', lazy='joined')
1307
1307
1308 def __json__(self):
1308 def __json__(self):
1309 data = {
1309 data = {
1310 'ssh_fingerprint': self.ssh_key_fingerprint,
1310 'ssh_fingerprint': self.ssh_key_fingerprint,
1311 'description': self.description,
1311 'description': self.description,
1312 'created_on': self.created_on
1312 'created_on': self.created_on
1313 }
1313 }
1314 return data
1314 return data
1315
1315
1316 def get_api_data(self):
1316 def get_api_data(self):
1317 data = self.__json__()
1317 data = self.__json__()
1318 return data
1318 return data
1319
1319
1320
1320
1321 class UserLog(Base, BaseModel):
1321 class UserLog(Base, BaseModel):
1322 __tablename__ = 'user_logs'
1322 __tablename__ = 'user_logs'
1323 __table_args__ = (
1323 __table_args__ = (
1324 base_table_args,
1324 base_table_args,
1325 )
1325 )
1326
1326
1327 VERSION_1 = 'v1'
1327 VERSION_1 = 'v1'
1328 VERSION_2 = 'v2'
1328 VERSION_2 = 'v2'
1329 VERSIONS = [VERSION_1, VERSION_2]
1329 VERSIONS = [VERSION_1, VERSION_2]
1330
1330
1331 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1331 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1332 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1332 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1333 username = Column("username", String(255), nullable=True, unique=None, default=None)
1333 username = Column("username", String(255), nullable=True, unique=None, default=None)
1334 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1334 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1335 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1335 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1336 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1336 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1337 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1337 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1338 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1338 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1339
1339
1340 version = Column("version", String(255), nullable=True, default=VERSION_1)
1340 version = Column("version", String(255), nullable=True, default=VERSION_1)
1341 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1341 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1342 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1342 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1343
1343
1344 def __unicode__(self):
1344 def __unicode__(self):
1345 return u"<%s('id:%s:%s')>" % (
1345 return u"<%s('id:%s:%s')>" % (
1346 self.__class__.__name__, self.repository_name, self.action)
1346 self.__class__.__name__, self.repository_name, self.action)
1347
1347
1348 def __json__(self):
1348 def __json__(self):
1349 return {
1349 return {
1350 'user_id': self.user_id,
1350 'user_id': self.user_id,
1351 'username': self.username,
1351 'username': self.username,
1352 'repository_id': self.repository_id,
1352 'repository_id': self.repository_id,
1353 'repository_name': self.repository_name,
1353 'repository_name': self.repository_name,
1354 'user_ip': self.user_ip,
1354 'user_ip': self.user_ip,
1355 'action_date': self.action_date,
1355 'action_date': self.action_date,
1356 'action': self.action,
1356 'action': self.action,
1357 }
1357 }
1358
1358
1359 @hybrid_property
1359 @hybrid_property
1360 def entry_id(self):
1360 def entry_id(self):
1361 return self.user_log_id
1361 return self.user_log_id
1362
1362
1363 @property
1363 @property
1364 def action_as_day(self):
1364 def action_as_day(self):
1365 return datetime.date(*self.action_date.timetuple()[:3])
1365 return datetime.date(*self.action_date.timetuple()[:3])
1366
1366
1367 user = relationship('User')
1367 user = relationship('User')
1368 repository = relationship('Repository', cascade='')
1368 repository = relationship('Repository', cascade='')
1369
1369
1370
1370
1371 class UserGroup(Base, BaseModel):
1371 class UserGroup(Base, BaseModel):
1372 __tablename__ = 'users_groups'
1372 __tablename__ = 'users_groups'
1373 __table_args__ = (
1373 __table_args__ = (
1374 base_table_args,
1374 base_table_args,
1375 )
1375 )
1376
1376
1377 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1377 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1378 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1378 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1379 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1379 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1380 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1380 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1381 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1381 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1382 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1382 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1383 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1383 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1384 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1384 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1385
1385
1386 members = relationship('UserGroupMember', cascade="all, delete-orphan", lazy="joined")
1386 members = relationship('UserGroupMember', cascade="all, delete-orphan", lazy="joined")
1387 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1387 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1388 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1388 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1389 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1389 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1390 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1390 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1391 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1391 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1392
1392
1393 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1393 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1394 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1394 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1395
1395
1396 @classmethod
1396 @classmethod
1397 def _load_group_data(cls, column):
1397 def _load_group_data(cls, column):
1398 if not column:
1398 if not column:
1399 return {}
1399 return {}
1400
1400
1401 try:
1401 try:
1402 return json.loads(column) or {}
1402 return json.loads(column) or {}
1403 except TypeError:
1403 except TypeError:
1404 return {}
1404 return {}
1405
1405
1406 @hybrid_property
1406 @hybrid_property
1407 def description_safe(self):
1407 def description_safe(self):
1408 from rhodecode.lib import helpers as h
1408 from rhodecode.lib import helpers as h
1409 return h.escape(self.user_group_description)
1409 return h.escape(self.user_group_description)
1410
1410
1411 @hybrid_property
1411 @hybrid_property
1412 def group_data(self):
1412 def group_data(self):
1413 return self._load_group_data(self._group_data)
1413 return self._load_group_data(self._group_data)
1414
1414
1415 @group_data.expression
1415 @group_data.expression
1416 def group_data(self, **kwargs):
1416 def group_data(self, **kwargs):
1417 return self._group_data
1417 return self._group_data
1418
1418
1419 @group_data.setter
1419 @group_data.setter
1420 def group_data(self, val):
1420 def group_data(self, val):
1421 try:
1421 try:
1422 self._group_data = json.dumps(val)
1422 self._group_data = json.dumps(val)
1423 except Exception:
1423 except Exception:
1424 log.error(traceback.format_exc())
1424 log.error(traceback.format_exc())
1425
1425
1426 @classmethod
1426 @classmethod
1427 def _load_sync(cls, group_data):
1427 def _load_sync(cls, group_data):
1428 if group_data:
1428 if group_data:
1429 return group_data.get('extern_type')
1429 return group_data.get('extern_type')
1430
1430
1431 @property
1431 @property
1432 def sync(self):
1432 def sync(self):
1433 return self._load_sync(self.group_data)
1433 return self._load_sync(self.group_data)
1434
1434
1435 def __unicode__(self):
1435 def __unicode__(self):
1436 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1436 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1437 self.users_group_id,
1437 self.users_group_id,
1438 self.users_group_name)
1438 self.users_group_name)
1439
1439
1440 @classmethod
1440 @classmethod
1441 def get_by_group_name(cls, group_name, cache=False,
1441 def get_by_group_name(cls, group_name, cache=False,
1442 case_insensitive=False):
1442 case_insensitive=False):
1443 if case_insensitive:
1443 if case_insensitive:
1444 q = cls.query().filter(func.lower(cls.users_group_name) ==
1444 q = cls.query().filter(func.lower(cls.users_group_name) ==
1445 func.lower(group_name))
1445 func.lower(group_name))
1446
1446
1447 else:
1447 else:
1448 q = cls.query().filter(cls.users_group_name == group_name)
1448 q = cls.query().filter(cls.users_group_name == group_name)
1449 if cache:
1449 if cache:
1450 q = q.options(
1450 q = q.options(
1451 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1451 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1452 return q.scalar()
1452 return q.scalar()
1453
1453
1454 @classmethod
1454 @classmethod
1455 def get(cls, user_group_id, cache=False):
1455 def get(cls, user_group_id, cache=False):
1456 if not user_group_id:
1456 if not user_group_id:
1457 return
1457 return
1458
1458
1459 user_group = cls.query()
1459 user_group = cls.query()
1460 if cache:
1460 if cache:
1461 user_group = user_group.options(
1461 user_group = user_group.options(
1462 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1462 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1463 return user_group.get(user_group_id)
1463 return user_group.get(user_group_id)
1464
1464
1465 def permissions(self, with_admins=True, with_owner=True,
1465 def permissions(self, with_admins=True, with_owner=True,
1466 expand_from_user_groups=False):
1466 expand_from_user_groups=False):
1467 """
1467 """
1468 Permissions for user groups
1468 Permissions for user groups
1469 """
1469 """
1470 _admin_perm = 'usergroup.admin'
1470 _admin_perm = 'usergroup.admin'
1471
1471
1472 owner_row = []
1472 owner_row = []
1473 if with_owner:
1473 if with_owner:
1474 usr = AttributeDict(self.user.get_dict())
1474 usr = AttributeDict(self.user.get_dict())
1475 usr.owner_row = True
1475 usr.owner_row = True
1476 usr.permission = _admin_perm
1476 usr.permission = _admin_perm
1477 owner_row.append(usr)
1477 owner_row.append(usr)
1478
1478
1479 super_admin_ids = []
1479 super_admin_ids = []
1480 super_admin_rows = []
1480 super_admin_rows = []
1481 if with_admins:
1481 if with_admins:
1482 for usr in User.get_all_super_admins():
1482 for usr in User.get_all_super_admins():
1483 super_admin_ids.append(usr.user_id)
1483 super_admin_ids.append(usr.user_id)
1484 # if this admin is also owner, don't double the record
1484 # if this admin is also owner, don't double the record
1485 if usr.user_id == owner_row[0].user_id:
1485 if usr.user_id == owner_row[0].user_id:
1486 owner_row[0].admin_row = True
1486 owner_row[0].admin_row = True
1487 else:
1487 else:
1488 usr = AttributeDict(usr.get_dict())
1488 usr = AttributeDict(usr.get_dict())
1489 usr.admin_row = True
1489 usr.admin_row = True
1490 usr.permission = _admin_perm
1490 usr.permission = _admin_perm
1491 super_admin_rows.append(usr)
1491 super_admin_rows.append(usr)
1492
1492
1493 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1493 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1494 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1494 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1495 joinedload(UserUserGroupToPerm.user),
1495 joinedload(UserUserGroupToPerm.user),
1496 joinedload(UserUserGroupToPerm.permission),)
1496 joinedload(UserUserGroupToPerm.permission),)
1497
1497
1498 # get owners and admins and permissions. We do a trick of re-writing
1498 # get owners and admins and permissions. We do a trick of re-writing
1499 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1499 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1500 # has a global reference and changing one object propagates to all
1500 # has a global reference and changing one object propagates to all
1501 # others. This means if admin is also an owner admin_row that change
1501 # others. This means if admin is also an owner admin_row that change
1502 # would propagate to both objects
1502 # would propagate to both objects
1503 perm_rows = []
1503 perm_rows = []
1504 for _usr in q.all():
1504 for _usr in q.all():
1505 usr = AttributeDict(_usr.user.get_dict())
1505 usr = AttributeDict(_usr.user.get_dict())
1506 # if this user is also owner/admin, mark as duplicate record
1506 # if this user is also owner/admin, mark as duplicate record
1507 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1507 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1508 usr.duplicate_perm = True
1508 usr.duplicate_perm = True
1509 usr.permission = _usr.permission.permission_name
1509 usr.permission = _usr.permission.permission_name
1510 perm_rows.append(usr)
1510 perm_rows.append(usr)
1511
1511
1512 # filter the perm rows by 'default' first and then sort them by
1512 # filter the perm rows by 'default' first and then sort them by
1513 # admin,write,read,none permissions sorted again alphabetically in
1513 # admin,write,read,none permissions sorted again alphabetically in
1514 # each group
1514 # each group
1515 perm_rows = sorted(perm_rows, key=display_user_sort)
1515 perm_rows = sorted(perm_rows, key=display_user_sort)
1516
1516
1517 user_groups_rows = []
1517 user_groups_rows = []
1518 if expand_from_user_groups:
1518 if expand_from_user_groups:
1519 for ug in self.permission_user_groups(with_members=True):
1519 for ug in self.permission_user_groups(with_members=True):
1520 for user_data in ug.members:
1520 for user_data in ug.members:
1521 user_groups_rows.append(user_data)
1521 user_groups_rows.append(user_data)
1522
1522
1523 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1523 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1524
1524
1525 def permission_user_groups(self, with_members=False):
1525 def permission_user_groups(self, with_members=False):
1526 q = UserGroupUserGroupToPerm.query()\
1526 q = UserGroupUserGroupToPerm.query()\
1527 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1527 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1528 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1528 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1529 joinedload(UserGroupUserGroupToPerm.target_user_group),
1529 joinedload(UserGroupUserGroupToPerm.target_user_group),
1530 joinedload(UserGroupUserGroupToPerm.permission),)
1530 joinedload(UserGroupUserGroupToPerm.permission),)
1531
1531
1532 perm_rows = []
1532 perm_rows = []
1533 for _user_group in q.all():
1533 for _user_group in q.all():
1534 entry = AttributeDict(_user_group.user_group.get_dict())
1534 entry = AttributeDict(_user_group.user_group.get_dict())
1535 entry.permission = _user_group.permission.permission_name
1535 entry.permission = _user_group.permission.permission_name
1536 if with_members:
1536 if with_members:
1537 entry.members = [x.user.get_dict()
1537 entry.members = [x.user.get_dict()
1538 for x in _user_group.user_group.members]
1538 for x in _user_group.user_group.members]
1539 perm_rows.append(entry)
1539 perm_rows.append(entry)
1540
1540
1541 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1541 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1542 return perm_rows
1542 return perm_rows
1543
1543
1544 def _get_default_perms(self, user_group, suffix=''):
1544 def _get_default_perms(self, user_group, suffix=''):
1545 from rhodecode.model.permission import PermissionModel
1545 from rhodecode.model.permission import PermissionModel
1546 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1546 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1547
1547
1548 def get_default_perms(self, suffix=''):
1548 def get_default_perms(self, suffix=''):
1549 return self._get_default_perms(self, suffix)
1549 return self._get_default_perms(self, suffix)
1550
1550
1551 def get_api_data(self, with_group_members=True, include_secrets=False):
1551 def get_api_data(self, with_group_members=True, include_secrets=False):
1552 """
1552 """
1553 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1553 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1554 basically forwarded.
1554 basically forwarded.
1555
1555
1556 """
1556 """
1557 user_group = self
1557 user_group = self
1558 data = {
1558 data = {
1559 'users_group_id': user_group.users_group_id,
1559 'users_group_id': user_group.users_group_id,
1560 'group_name': user_group.users_group_name,
1560 'group_name': user_group.users_group_name,
1561 'group_description': user_group.user_group_description,
1561 'group_description': user_group.user_group_description,
1562 'active': user_group.users_group_active,
1562 'active': user_group.users_group_active,
1563 'owner': user_group.user.username,
1563 'owner': user_group.user.username,
1564 'sync': user_group.sync,
1564 'sync': user_group.sync,
1565 'owner_email': user_group.user.email,
1565 'owner_email': user_group.user.email,
1566 }
1566 }
1567
1567
1568 if with_group_members:
1568 if with_group_members:
1569 users = []
1569 users = []
1570 for user in user_group.members:
1570 for user in user_group.members:
1571 user = user.user
1571 user = user.user
1572 users.append(user.get_api_data(include_secrets=include_secrets))
1572 users.append(user.get_api_data(include_secrets=include_secrets))
1573 data['users'] = users
1573 data['users'] = users
1574
1574
1575 return data
1575 return data
1576
1576
1577
1577
1578 class UserGroupMember(Base, BaseModel):
1578 class UserGroupMember(Base, BaseModel):
1579 __tablename__ = 'users_groups_members'
1579 __tablename__ = 'users_groups_members'
1580 __table_args__ = (
1580 __table_args__ = (
1581 base_table_args,
1581 base_table_args,
1582 )
1582 )
1583
1583
1584 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1584 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1585 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1585 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1586 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1586 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1587
1587
1588 user = relationship('User', lazy='joined')
1588 user = relationship('User', lazy='joined')
1589 users_group = relationship('UserGroup')
1589 users_group = relationship('UserGroup')
1590
1590
1591 def __init__(self, gr_id='', u_id=''):
1591 def __init__(self, gr_id='', u_id=''):
1592 self.users_group_id = gr_id
1592 self.users_group_id = gr_id
1593 self.user_id = u_id
1593 self.user_id = u_id
1594
1594
1595
1595
1596 class RepositoryField(Base, BaseModel):
1596 class RepositoryField(Base, BaseModel):
1597 __tablename__ = 'repositories_fields'
1597 __tablename__ = 'repositories_fields'
1598 __table_args__ = (
1598 __table_args__ = (
1599 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1599 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1600 base_table_args,
1600 base_table_args,
1601 )
1601 )
1602
1602
1603 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1603 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1604
1604
1605 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1605 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1606 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1606 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1607 field_key = Column("field_key", String(250))
1607 field_key = Column("field_key", String(250))
1608 field_label = Column("field_label", String(1024), nullable=False)
1608 field_label = Column("field_label", String(1024), nullable=False)
1609 field_value = Column("field_value", String(10000), nullable=False)
1609 field_value = Column("field_value", String(10000), nullable=False)
1610 field_desc = Column("field_desc", String(1024), nullable=False)
1610 field_desc = Column("field_desc", String(1024), nullable=False)
1611 field_type = Column("field_type", String(255), nullable=False, unique=None)
1611 field_type = Column("field_type", String(255), nullable=False, unique=None)
1612 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1612 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1613
1613
1614 repository = relationship('Repository')
1614 repository = relationship('Repository')
1615
1615
1616 @property
1616 @property
1617 def field_key_prefixed(self):
1617 def field_key_prefixed(self):
1618 return 'ex_%s' % self.field_key
1618 return 'ex_%s' % self.field_key
1619
1619
1620 @classmethod
1620 @classmethod
1621 def un_prefix_key(cls, key):
1621 def un_prefix_key(cls, key):
1622 if key.startswith(cls.PREFIX):
1622 if key.startswith(cls.PREFIX):
1623 return key[len(cls.PREFIX):]
1623 return key[len(cls.PREFIX):]
1624 return key
1624 return key
1625
1625
1626 @classmethod
1626 @classmethod
1627 def get_by_key_name(cls, key, repo):
1627 def get_by_key_name(cls, key, repo):
1628 row = cls.query()\
1628 row = cls.query()\
1629 .filter(cls.repository == repo)\
1629 .filter(cls.repository == repo)\
1630 .filter(cls.field_key == key).scalar()
1630 .filter(cls.field_key == key).scalar()
1631 return row
1631 return row
1632
1632
1633
1633
1634 class Repository(Base, BaseModel):
1634 class Repository(Base, BaseModel):
1635 __tablename__ = 'repositories'
1635 __tablename__ = 'repositories'
1636 __table_args__ = (
1636 __table_args__ = (
1637 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1637 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1638 base_table_args,
1638 base_table_args,
1639 )
1639 )
1640 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1640 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1641 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1641 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1642 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1642 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1643
1643
1644 STATE_CREATED = 'repo_state_created'
1644 STATE_CREATED = 'repo_state_created'
1645 STATE_PENDING = 'repo_state_pending'
1645 STATE_PENDING = 'repo_state_pending'
1646 STATE_ERROR = 'repo_state_error'
1646 STATE_ERROR = 'repo_state_error'
1647
1647
1648 LOCK_AUTOMATIC = 'lock_auto'
1648 LOCK_AUTOMATIC = 'lock_auto'
1649 LOCK_API = 'lock_api'
1649 LOCK_API = 'lock_api'
1650 LOCK_WEB = 'lock_web'
1650 LOCK_WEB = 'lock_web'
1651 LOCK_PULL = 'lock_pull'
1651 LOCK_PULL = 'lock_pull'
1652
1652
1653 NAME_SEP = URL_SEP
1653 NAME_SEP = URL_SEP
1654
1654
1655 repo_id = Column(
1655 repo_id = Column(
1656 "repo_id", Integer(), nullable=False, unique=True, default=None,
1656 "repo_id", Integer(), nullable=False, unique=True, default=None,
1657 primary_key=True)
1657 primary_key=True)
1658 _repo_name = Column(
1658 _repo_name = Column(
1659 "repo_name", Text(), nullable=False, default=None)
1659 "repo_name", Text(), nullable=False, default=None)
1660 repo_name_hash = Column(
1660 repo_name_hash = Column(
1661 "repo_name_hash", String(255), nullable=False, unique=True)
1661 "repo_name_hash", String(255), nullable=False, unique=True)
1662 repo_state = Column("repo_state", String(255), nullable=True)
1662 repo_state = Column("repo_state", String(255), nullable=True)
1663
1663
1664 clone_uri = Column(
1664 clone_uri = Column(
1665 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1665 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1666 default=None)
1666 default=None)
1667 push_uri = Column(
1667 push_uri = Column(
1668 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1668 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1669 default=None)
1669 default=None)
1670 repo_type = Column(
1670 repo_type = Column(
1671 "repo_type", String(255), nullable=False, unique=False, default=None)
1671 "repo_type", String(255), nullable=False, unique=False, default=None)
1672 user_id = Column(
1672 user_id = Column(
1673 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1673 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1674 unique=False, default=None)
1674 unique=False, default=None)
1675 private = Column(
1675 private = Column(
1676 "private", Boolean(), nullable=True, unique=None, default=None)
1676 "private", Boolean(), nullable=True, unique=None, default=None)
1677 archived = Column(
1677 archived = Column(
1678 "archived", Boolean(), nullable=True, unique=None, default=None)
1678 "archived", Boolean(), nullable=True, unique=None, default=None)
1679 enable_statistics = Column(
1679 enable_statistics = Column(
1680 "statistics", Boolean(), nullable=True, unique=None, default=True)
1680 "statistics", Boolean(), nullable=True, unique=None, default=True)
1681 enable_downloads = Column(
1681 enable_downloads = Column(
1682 "downloads", Boolean(), nullable=True, unique=None, default=True)
1682 "downloads", Boolean(), nullable=True, unique=None, default=True)
1683 description = Column(
1683 description = Column(
1684 "description", String(10000), nullable=True, unique=None, default=None)
1684 "description", String(10000), nullable=True, unique=None, default=None)
1685 created_on = Column(
1685 created_on = Column(
1686 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1686 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1687 default=datetime.datetime.now)
1687 default=datetime.datetime.now)
1688 updated_on = Column(
1688 updated_on = Column(
1689 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1689 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1690 default=datetime.datetime.now)
1690 default=datetime.datetime.now)
1691 _landing_revision = Column(
1691 _landing_revision = Column(
1692 "landing_revision", String(255), nullable=False, unique=False,
1692 "landing_revision", String(255), nullable=False, unique=False,
1693 default=None)
1693 default=None)
1694 enable_locking = Column(
1694 enable_locking = Column(
1695 "enable_locking", Boolean(), nullable=False, unique=None,
1695 "enable_locking", Boolean(), nullable=False, unique=None,
1696 default=False)
1696 default=False)
1697 _locked = Column(
1697 _locked = Column(
1698 "locked", String(255), nullable=True, unique=False, default=None)
1698 "locked", String(255), nullable=True, unique=False, default=None)
1699 _changeset_cache = Column(
1699 _changeset_cache = Column(
1700 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1700 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1701
1701
1702 fork_id = Column(
1702 fork_id = Column(
1703 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1703 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1704 nullable=True, unique=False, default=None)
1704 nullable=True, unique=False, default=None)
1705 group_id = Column(
1705 group_id = Column(
1706 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1706 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1707 unique=False, default=None)
1707 unique=False, default=None)
1708
1708
1709 user = relationship('User', lazy='joined')
1709 user = relationship('User', lazy='joined')
1710 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1710 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1711 group = relationship('RepoGroup', lazy='joined')
1711 group = relationship('RepoGroup', lazy='joined')
1712 repo_to_perm = relationship(
1712 repo_to_perm = relationship(
1713 'UserRepoToPerm', cascade='all',
1713 'UserRepoToPerm', cascade='all',
1714 order_by='UserRepoToPerm.repo_to_perm_id')
1714 order_by='UserRepoToPerm.repo_to_perm_id')
1715 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1715 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1716 stats = relationship('Statistics', cascade='all', uselist=False)
1716 stats = relationship('Statistics', cascade='all', uselist=False)
1717
1717
1718 followers = relationship(
1718 followers = relationship(
1719 'UserFollowing',
1719 'UserFollowing',
1720 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1720 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1721 cascade='all')
1721 cascade='all')
1722 extra_fields = relationship(
1722 extra_fields = relationship(
1723 'RepositoryField', cascade="all, delete-orphan")
1723 'RepositoryField', cascade="all, delete-orphan")
1724 logs = relationship('UserLog')
1724 logs = relationship('UserLog')
1725 comments = relationship(
1725 comments = relationship(
1726 'ChangesetComment', cascade="all, delete-orphan")
1726 'ChangesetComment', cascade="all, delete-orphan")
1727 pull_requests_source = relationship(
1727 pull_requests_source = relationship(
1728 'PullRequest',
1728 'PullRequest',
1729 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1729 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1730 cascade="all, delete-orphan")
1730 cascade="all, delete-orphan")
1731 pull_requests_target = relationship(
1731 pull_requests_target = relationship(
1732 'PullRequest',
1732 'PullRequest',
1733 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1733 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1734 cascade="all, delete-orphan")
1734 cascade="all, delete-orphan")
1735 ui = relationship('RepoRhodeCodeUi', cascade="all")
1735 ui = relationship('RepoRhodeCodeUi', cascade="all")
1736 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1736 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1737 integrations = relationship('Integration', cascade="all, delete-orphan")
1737 integrations = relationship('Integration', cascade="all, delete-orphan")
1738
1738
1739 scoped_tokens = relationship('UserApiKeys', cascade="all")
1739 scoped_tokens = relationship('UserApiKeys', cascade="all")
1740
1740
1741 # no cascade, set NULL
1741 # no cascade, set NULL
1742 artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_id==Repository.repo_id')
1742 artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_id==Repository.repo_id')
1743
1743
1744 def __unicode__(self):
1744 def __unicode__(self):
1745 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1745 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1746 safe_unicode(self.repo_name))
1746 safe_unicode(self.repo_name))
1747
1747
1748 @hybrid_property
1748 @hybrid_property
1749 def description_safe(self):
1749 def description_safe(self):
1750 from rhodecode.lib import helpers as h
1750 from rhodecode.lib import helpers as h
1751 return h.escape(self.description)
1751 return h.escape(self.description)
1752
1752
1753 @hybrid_property
1753 @hybrid_property
1754 def landing_rev(self):
1754 def landing_rev(self):
1755 # always should return [rev_type, rev]
1755 # always should return [rev_type, rev]
1756 if self._landing_revision:
1756 if self._landing_revision:
1757 _rev_info = self._landing_revision.split(':')
1757 _rev_info = self._landing_revision.split(':')
1758 if len(_rev_info) < 2:
1758 if len(_rev_info) < 2:
1759 _rev_info.insert(0, 'rev')
1759 _rev_info.insert(0, 'rev')
1760 return [_rev_info[0], _rev_info[1]]
1760 return [_rev_info[0], _rev_info[1]]
1761 return [None, None]
1761 return [None, None]
1762
1762
1763 @landing_rev.setter
1763 @landing_rev.setter
1764 def landing_rev(self, val):
1764 def landing_rev(self, val):
1765 if ':' not in val:
1765 if ':' not in val:
1766 raise ValueError('value must be delimited with `:` and consist '
1766 raise ValueError('value must be delimited with `:` and consist '
1767 'of <rev_type>:<rev>, got %s instead' % val)
1767 'of <rev_type>:<rev>, got %s instead' % val)
1768 self._landing_revision = val
1768 self._landing_revision = val
1769
1769
1770 @hybrid_property
1770 @hybrid_property
1771 def locked(self):
1771 def locked(self):
1772 if self._locked:
1772 if self._locked:
1773 user_id, timelocked, reason = self._locked.split(':')
1773 user_id, timelocked, reason = self._locked.split(':')
1774 lock_values = int(user_id), timelocked, reason
1774 lock_values = int(user_id), timelocked, reason
1775 else:
1775 else:
1776 lock_values = [None, None, None]
1776 lock_values = [None, None, None]
1777 return lock_values
1777 return lock_values
1778
1778
1779 @locked.setter
1779 @locked.setter
1780 def locked(self, val):
1780 def locked(self, val):
1781 if val and isinstance(val, (list, tuple)):
1781 if val and isinstance(val, (list, tuple)):
1782 self._locked = ':'.join(map(str, val))
1782 self._locked = ':'.join(map(str, val))
1783 else:
1783 else:
1784 self._locked = None
1784 self._locked = None
1785
1785
1786 @classmethod
1786 @classmethod
1787 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
1787 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
1788 from rhodecode.lib.vcs.backends.base import EmptyCommit
1788 from rhodecode.lib.vcs.backends.base import EmptyCommit
1789 dummy = EmptyCommit().__json__()
1789 dummy = EmptyCommit().__json__()
1790 if not changeset_cache_raw:
1790 if not changeset_cache_raw:
1791 dummy['source_repo_id'] = repo_id
1791 dummy['source_repo_id'] = repo_id
1792 return json.loads(json.dumps(dummy))
1792 return json.loads(json.dumps(dummy))
1793
1793
1794 try:
1794 try:
1795 return json.loads(changeset_cache_raw)
1795 return json.loads(changeset_cache_raw)
1796 except TypeError:
1796 except TypeError:
1797 return dummy
1797 return dummy
1798 except Exception:
1798 except Exception:
1799 log.error(traceback.format_exc())
1799 log.error(traceback.format_exc())
1800 return dummy
1800 return dummy
1801
1801
1802 @hybrid_property
1802 @hybrid_property
1803 def changeset_cache(self):
1803 def changeset_cache(self):
1804 return self._load_changeset_cache(self.repo_id, self._changeset_cache)
1804 return self._load_changeset_cache(self.repo_id, self._changeset_cache)
1805
1805
1806 @changeset_cache.setter
1806 @changeset_cache.setter
1807 def changeset_cache(self, val):
1807 def changeset_cache(self, val):
1808 try:
1808 try:
1809 self._changeset_cache = json.dumps(val)
1809 self._changeset_cache = json.dumps(val)
1810 except Exception:
1810 except Exception:
1811 log.error(traceback.format_exc())
1811 log.error(traceback.format_exc())
1812
1812
1813 @hybrid_property
1813 @hybrid_property
1814 def repo_name(self):
1814 def repo_name(self):
1815 return self._repo_name
1815 return self._repo_name
1816
1816
1817 @repo_name.setter
1817 @repo_name.setter
1818 def repo_name(self, value):
1818 def repo_name(self, value):
1819 self._repo_name = value
1819 self._repo_name = value
1820 self.repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1820 self.repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1821
1821
1822 @classmethod
1822 @classmethod
1823 def normalize_repo_name(cls, repo_name):
1823 def normalize_repo_name(cls, repo_name):
1824 """
1824 """
1825 Normalizes os specific repo_name to the format internally stored inside
1825 Normalizes os specific repo_name to the format internally stored inside
1826 database using URL_SEP
1826 database using URL_SEP
1827
1827
1828 :param cls:
1828 :param cls:
1829 :param repo_name:
1829 :param repo_name:
1830 """
1830 """
1831 return cls.NAME_SEP.join(repo_name.split(os.sep))
1831 return cls.NAME_SEP.join(repo_name.split(os.sep))
1832
1832
1833 @classmethod
1833 @classmethod
1834 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1834 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1835 session = Session()
1835 session = Session()
1836 q = session.query(cls).filter(cls.repo_name == repo_name)
1836 q = session.query(cls).filter(cls.repo_name == repo_name)
1837
1837
1838 if cache:
1838 if cache:
1839 if identity_cache:
1839 if identity_cache:
1840 val = cls.identity_cache(session, 'repo_name', repo_name)
1840 val = cls.identity_cache(session, 'repo_name', repo_name)
1841 if val:
1841 if val:
1842 return val
1842 return val
1843 else:
1843 else:
1844 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1844 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1845 q = q.options(
1845 q = q.options(
1846 FromCache("sql_cache_short", cache_key))
1846 FromCache("sql_cache_short", cache_key))
1847
1847
1848 return q.scalar()
1848 return q.scalar()
1849
1849
1850 @classmethod
1850 @classmethod
1851 def get_by_id_or_repo_name(cls, repoid):
1851 def get_by_id_or_repo_name(cls, repoid):
1852 if isinstance(repoid, (int, long)):
1852 if isinstance(repoid, (int, long)):
1853 try:
1853 try:
1854 repo = cls.get(repoid)
1854 repo = cls.get(repoid)
1855 except ValueError:
1855 except ValueError:
1856 repo = None
1856 repo = None
1857 else:
1857 else:
1858 repo = cls.get_by_repo_name(repoid)
1858 repo = cls.get_by_repo_name(repoid)
1859 return repo
1859 return repo
1860
1860
1861 @classmethod
1861 @classmethod
1862 def get_by_full_path(cls, repo_full_path):
1862 def get_by_full_path(cls, repo_full_path):
1863 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1863 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1864 repo_name = cls.normalize_repo_name(repo_name)
1864 repo_name = cls.normalize_repo_name(repo_name)
1865 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1865 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1866
1866
1867 @classmethod
1867 @classmethod
1868 def get_repo_forks(cls, repo_id):
1868 def get_repo_forks(cls, repo_id):
1869 return cls.query().filter(Repository.fork_id == repo_id)
1869 return cls.query().filter(Repository.fork_id == repo_id)
1870
1870
1871 @classmethod
1871 @classmethod
1872 def base_path(cls):
1872 def base_path(cls):
1873 """
1873 """
1874 Returns base path when all repos are stored
1874 Returns base path when all repos are stored
1875
1875
1876 :param cls:
1876 :param cls:
1877 """
1877 """
1878 q = Session().query(RhodeCodeUi)\
1878 q = Session().query(RhodeCodeUi)\
1879 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1879 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1880 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1880 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1881 return q.one().ui_value
1881 return q.one().ui_value
1882
1882
1883 @classmethod
1883 @classmethod
1884 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1884 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1885 case_insensitive=True, archived=False):
1885 case_insensitive=True, archived=False):
1886 q = Repository.query()
1886 q = Repository.query()
1887
1887
1888 if not archived:
1888 if not archived:
1889 q = q.filter(Repository.archived.isnot(true()))
1889 q = q.filter(Repository.archived.isnot(true()))
1890
1890
1891 if not isinstance(user_id, Optional):
1891 if not isinstance(user_id, Optional):
1892 q = q.filter(Repository.user_id == user_id)
1892 q = q.filter(Repository.user_id == user_id)
1893
1893
1894 if not isinstance(group_id, Optional):
1894 if not isinstance(group_id, Optional):
1895 q = q.filter(Repository.group_id == group_id)
1895 q = q.filter(Repository.group_id == group_id)
1896
1896
1897 if case_insensitive:
1897 if case_insensitive:
1898 q = q.order_by(func.lower(Repository.repo_name))
1898 q = q.order_by(func.lower(Repository.repo_name))
1899 else:
1899 else:
1900 q = q.order_by(Repository.repo_name)
1900 q = q.order_by(Repository.repo_name)
1901
1901
1902 return q.all()
1902 return q.all()
1903
1903
1904 @property
1904 @property
1905 def repo_uid(self):
1905 def repo_uid(self):
1906 return '_{}'.format(self.repo_id)
1906 return '_{}'.format(self.repo_id)
1907
1907
1908 @property
1908 @property
1909 def forks(self):
1909 def forks(self):
1910 """
1910 """
1911 Return forks of this repo
1911 Return forks of this repo
1912 """
1912 """
1913 return Repository.get_repo_forks(self.repo_id)
1913 return Repository.get_repo_forks(self.repo_id)
1914
1914
1915 @property
1915 @property
1916 def parent(self):
1916 def parent(self):
1917 """
1917 """
1918 Returns fork parent
1918 Returns fork parent
1919 """
1919 """
1920 return self.fork
1920 return self.fork
1921
1921
1922 @property
1922 @property
1923 def just_name(self):
1923 def just_name(self):
1924 return self.repo_name.split(self.NAME_SEP)[-1]
1924 return self.repo_name.split(self.NAME_SEP)[-1]
1925
1925
1926 @property
1926 @property
1927 def groups_with_parents(self):
1927 def groups_with_parents(self):
1928 groups = []
1928 groups = []
1929 if self.group is None:
1929 if self.group is None:
1930 return groups
1930 return groups
1931
1931
1932 cur_gr = self.group
1932 cur_gr = self.group
1933 groups.insert(0, cur_gr)
1933 groups.insert(0, cur_gr)
1934 while 1:
1934 while 1:
1935 gr = getattr(cur_gr, 'parent_group', None)
1935 gr = getattr(cur_gr, 'parent_group', None)
1936 cur_gr = cur_gr.parent_group
1936 cur_gr = cur_gr.parent_group
1937 if gr is None:
1937 if gr is None:
1938 break
1938 break
1939 groups.insert(0, gr)
1939 groups.insert(0, gr)
1940
1940
1941 return groups
1941 return groups
1942
1942
1943 @property
1943 @property
1944 def groups_and_repo(self):
1944 def groups_and_repo(self):
1945 return self.groups_with_parents, self
1945 return self.groups_with_parents, self
1946
1946
1947 @LazyProperty
1947 @LazyProperty
1948 def repo_path(self):
1948 def repo_path(self):
1949 """
1949 """
1950 Returns base full path for that repository means where it actually
1950 Returns base full path for that repository means where it actually
1951 exists on a filesystem
1951 exists on a filesystem
1952 """
1952 """
1953 q = Session().query(RhodeCodeUi).filter(
1953 q = Session().query(RhodeCodeUi).filter(
1954 RhodeCodeUi.ui_key == self.NAME_SEP)
1954 RhodeCodeUi.ui_key == self.NAME_SEP)
1955 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1955 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1956 return q.one().ui_value
1956 return q.one().ui_value
1957
1957
1958 @property
1958 @property
1959 def repo_full_path(self):
1959 def repo_full_path(self):
1960 p = [self.repo_path]
1960 p = [self.repo_path]
1961 # we need to split the name by / since this is how we store the
1961 # we need to split the name by / since this is how we store the
1962 # names in the database, but that eventually needs to be converted
1962 # names in the database, but that eventually needs to be converted
1963 # into a valid system path
1963 # into a valid system path
1964 p += self.repo_name.split(self.NAME_SEP)
1964 p += self.repo_name.split(self.NAME_SEP)
1965 return os.path.join(*map(safe_unicode, p))
1965 return os.path.join(*map(safe_unicode, p))
1966
1966
1967 @property
1967 @property
1968 def cache_keys(self):
1968 def cache_keys(self):
1969 """
1969 """
1970 Returns associated cache keys for that repo
1970 Returns associated cache keys for that repo
1971 """
1971 """
1972 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1972 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1973 repo_id=self.repo_id)
1973 repo_id=self.repo_id)
1974 return CacheKey.query()\
1974 return CacheKey.query()\
1975 .filter(CacheKey.cache_args == invalidation_namespace)\
1975 .filter(CacheKey.cache_args == invalidation_namespace)\
1976 .order_by(CacheKey.cache_key)\
1976 .order_by(CacheKey.cache_key)\
1977 .all()
1977 .all()
1978
1978
1979 @property
1979 @property
1980 def cached_diffs_relative_dir(self):
1980 def cached_diffs_relative_dir(self):
1981 """
1981 """
1982 Return a relative to the repository store path of cached diffs
1982 Return a relative to the repository store path of cached diffs
1983 used for safe display for users, who shouldn't know the absolute store
1983 used for safe display for users, who shouldn't know the absolute store
1984 path
1984 path
1985 """
1985 """
1986 return os.path.join(
1986 return os.path.join(
1987 os.path.dirname(self.repo_name),
1987 os.path.dirname(self.repo_name),
1988 self.cached_diffs_dir.split(os.path.sep)[-1])
1988 self.cached_diffs_dir.split(os.path.sep)[-1])
1989
1989
1990 @property
1990 @property
1991 def cached_diffs_dir(self):
1991 def cached_diffs_dir(self):
1992 path = self.repo_full_path
1992 path = self.repo_full_path
1993 return os.path.join(
1993 return os.path.join(
1994 os.path.dirname(path),
1994 os.path.dirname(path),
1995 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1995 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1996
1996
1997 def cached_diffs(self):
1997 def cached_diffs(self):
1998 diff_cache_dir = self.cached_diffs_dir
1998 diff_cache_dir = self.cached_diffs_dir
1999 if os.path.isdir(diff_cache_dir):
1999 if os.path.isdir(diff_cache_dir):
2000 return os.listdir(diff_cache_dir)
2000 return os.listdir(diff_cache_dir)
2001 return []
2001 return []
2002
2002
2003 def shadow_repos(self):
2003 def shadow_repos(self):
2004 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
2004 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
2005 return [
2005 return [
2006 x for x in os.listdir(os.path.dirname(self.repo_full_path))
2006 x for x in os.listdir(os.path.dirname(self.repo_full_path))
2007 if x.startswith(shadow_repos_pattern)]
2007 if x.startswith(shadow_repos_pattern)]
2008
2008
2009 def get_new_name(self, repo_name):
2009 def get_new_name(self, repo_name):
2010 """
2010 """
2011 returns new full repository name based on assigned group and new new
2011 returns new full repository name based on assigned group and new new
2012
2012
2013 :param group_name:
2013 :param group_name:
2014 """
2014 """
2015 path_prefix = self.group.full_path_splitted if self.group else []
2015 path_prefix = self.group.full_path_splitted if self.group else []
2016 return self.NAME_SEP.join(path_prefix + [repo_name])
2016 return self.NAME_SEP.join(path_prefix + [repo_name])
2017
2017
2018 @property
2018 @property
2019 def _config(self):
2019 def _config(self):
2020 """
2020 """
2021 Returns db based config object.
2021 Returns db based config object.
2022 """
2022 """
2023 from rhodecode.lib.utils import make_db_config
2023 from rhodecode.lib.utils import make_db_config
2024 return make_db_config(clear_session=False, repo=self)
2024 return make_db_config(clear_session=False, repo=self)
2025
2025
2026 def permissions(self, with_admins=True, with_owner=True,
2026 def permissions(self, with_admins=True, with_owner=True,
2027 expand_from_user_groups=False):
2027 expand_from_user_groups=False):
2028 """
2028 """
2029 Permissions for repositories
2029 Permissions for repositories
2030 """
2030 """
2031 _admin_perm = 'repository.admin'
2031 _admin_perm = 'repository.admin'
2032
2032
2033 owner_row = []
2033 owner_row = []
2034 if with_owner:
2034 if with_owner:
2035 usr = AttributeDict(self.user.get_dict())
2035 usr = AttributeDict(self.user.get_dict())
2036 usr.owner_row = True
2036 usr.owner_row = True
2037 usr.permission = _admin_perm
2037 usr.permission = _admin_perm
2038 usr.permission_id = None
2038 usr.permission_id = None
2039 owner_row.append(usr)
2039 owner_row.append(usr)
2040
2040
2041 super_admin_ids = []
2041 super_admin_ids = []
2042 super_admin_rows = []
2042 super_admin_rows = []
2043 if with_admins:
2043 if with_admins:
2044 for usr in User.get_all_super_admins():
2044 for usr in User.get_all_super_admins():
2045 super_admin_ids.append(usr.user_id)
2045 super_admin_ids.append(usr.user_id)
2046 # if this admin is also owner, don't double the record
2046 # if this admin is also owner, don't double the record
2047 if usr.user_id == owner_row[0].user_id:
2047 if usr.user_id == owner_row[0].user_id:
2048 owner_row[0].admin_row = True
2048 owner_row[0].admin_row = True
2049 else:
2049 else:
2050 usr = AttributeDict(usr.get_dict())
2050 usr = AttributeDict(usr.get_dict())
2051 usr.admin_row = True
2051 usr.admin_row = True
2052 usr.permission = _admin_perm
2052 usr.permission = _admin_perm
2053 usr.permission_id = None
2053 usr.permission_id = None
2054 super_admin_rows.append(usr)
2054 super_admin_rows.append(usr)
2055
2055
2056 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
2056 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
2057 q = q.options(joinedload(UserRepoToPerm.repository),
2057 q = q.options(joinedload(UserRepoToPerm.repository),
2058 joinedload(UserRepoToPerm.user),
2058 joinedload(UserRepoToPerm.user),
2059 joinedload(UserRepoToPerm.permission),)
2059 joinedload(UserRepoToPerm.permission),)
2060
2060
2061 # get owners and admins and permissions. We do a trick of re-writing
2061 # get owners and admins and permissions. We do a trick of re-writing
2062 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2062 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2063 # has a global reference and changing one object propagates to all
2063 # has a global reference and changing one object propagates to all
2064 # others. This means if admin is also an owner admin_row that change
2064 # others. This means if admin is also an owner admin_row that change
2065 # would propagate to both objects
2065 # would propagate to both objects
2066 perm_rows = []
2066 perm_rows = []
2067 for _usr in q.all():
2067 for _usr in q.all():
2068 usr = AttributeDict(_usr.user.get_dict())
2068 usr = AttributeDict(_usr.user.get_dict())
2069 # if this user is also owner/admin, mark as duplicate record
2069 # if this user is also owner/admin, mark as duplicate record
2070 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2070 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2071 usr.duplicate_perm = True
2071 usr.duplicate_perm = True
2072 # also check if this permission is maybe used by branch_permissions
2072 # also check if this permission is maybe used by branch_permissions
2073 if _usr.branch_perm_entry:
2073 if _usr.branch_perm_entry:
2074 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2074 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2075
2075
2076 usr.permission = _usr.permission.permission_name
2076 usr.permission = _usr.permission.permission_name
2077 usr.permission_id = _usr.repo_to_perm_id
2077 usr.permission_id = _usr.repo_to_perm_id
2078 perm_rows.append(usr)
2078 perm_rows.append(usr)
2079
2079
2080 # filter the perm rows by 'default' first and then sort them by
2080 # filter the perm rows by 'default' first and then sort them by
2081 # admin,write,read,none permissions sorted again alphabetically in
2081 # admin,write,read,none permissions sorted again alphabetically in
2082 # each group
2082 # each group
2083 perm_rows = sorted(perm_rows, key=display_user_sort)
2083 perm_rows = sorted(perm_rows, key=display_user_sort)
2084
2084
2085 user_groups_rows = []
2085 user_groups_rows = []
2086 if expand_from_user_groups:
2086 if expand_from_user_groups:
2087 for ug in self.permission_user_groups(with_members=True):
2087 for ug in self.permission_user_groups(with_members=True):
2088 for user_data in ug.members:
2088 for user_data in ug.members:
2089 user_groups_rows.append(user_data)
2089 user_groups_rows.append(user_data)
2090
2090
2091 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2091 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2092
2092
2093 def permission_user_groups(self, with_members=True):
2093 def permission_user_groups(self, with_members=True):
2094 q = UserGroupRepoToPerm.query()\
2094 q = UserGroupRepoToPerm.query()\
2095 .filter(UserGroupRepoToPerm.repository == self)
2095 .filter(UserGroupRepoToPerm.repository == self)
2096 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2096 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2097 joinedload(UserGroupRepoToPerm.users_group),
2097 joinedload(UserGroupRepoToPerm.users_group),
2098 joinedload(UserGroupRepoToPerm.permission),)
2098 joinedload(UserGroupRepoToPerm.permission),)
2099
2099
2100 perm_rows = []
2100 perm_rows = []
2101 for _user_group in q.all():
2101 for _user_group in q.all():
2102 entry = AttributeDict(_user_group.users_group.get_dict())
2102 entry = AttributeDict(_user_group.users_group.get_dict())
2103 entry.permission = _user_group.permission.permission_name
2103 entry.permission = _user_group.permission.permission_name
2104 if with_members:
2104 if with_members:
2105 entry.members = [x.user.get_dict()
2105 entry.members = [x.user.get_dict()
2106 for x in _user_group.users_group.members]
2106 for x in _user_group.users_group.members]
2107 perm_rows.append(entry)
2107 perm_rows.append(entry)
2108
2108
2109 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2109 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2110 return perm_rows
2110 return perm_rows
2111
2111
2112 def get_api_data(self, include_secrets=False):
2112 def get_api_data(self, include_secrets=False):
2113 """
2113 """
2114 Common function for generating repo api data
2114 Common function for generating repo api data
2115
2115
2116 :param include_secrets: See :meth:`User.get_api_data`.
2116 :param include_secrets: See :meth:`User.get_api_data`.
2117
2117
2118 """
2118 """
2119 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2119 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2120 # move this methods on models level.
2120 # move this methods on models level.
2121 from rhodecode.model.settings import SettingsModel
2121 from rhodecode.model.settings import SettingsModel
2122 from rhodecode.model.repo import RepoModel
2122 from rhodecode.model.repo import RepoModel
2123
2123
2124 repo = self
2124 repo = self
2125 _user_id, _time, _reason = self.locked
2125 _user_id, _time, _reason = self.locked
2126
2126
2127 data = {
2127 data = {
2128 'repo_id': repo.repo_id,
2128 'repo_id': repo.repo_id,
2129 'repo_name': repo.repo_name,
2129 'repo_name': repo.repo_name,
2130 'repo_type': repo.repo_type,
2130 'repo_type': repo.repo_type,
2131 'clone_uri': repo.clone_uri or '',
2131 'clone_uri': repo.clone_uri or '',
2132 'push_uri': repo.push_uri or '',
2132 'push_uri': repo.push_uri or '',
2133 'url': RepoModel().get_url(self),
2133 'url': RepoModel().get_url(self),
2134 'private': repo.private,
2134 'private': repo.private,
2135 'created_on': repo.created_on,
2135 'created_on': repo.created_on,
2136 'description': repo.description_safe,
2136 'description': repo.description_safe,
2137 'landing_rev': repo.landing_rev,
2137 'landing_rev': repo.landing_rev,
2138 'owner': repo.user.username,
2138 'owner': repo.user.username,
2139 'fork_of': repo.fork.repo_name if repo.fork else None,
2139 'fork_of': repo.fork.repo_name if repo.fork else None,
2140 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2140 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2141 'enable_statistics': repo.enable_statistics,
2141 'enable_statistics': repo.enable_statistics,
2142 'enable_locking': repo.enable_locking,
2142 'enable_locking': repo.enable_locking,
2143 'enable_downloads': repo.enable_downloads,
2143 'enable_downloads': repo.enable_downloads,
2144 'last_changeset': repo.changeset_cache,
2144 'last_changeset': repo.changeset_cache,
2145 'locked_by': User.get(_user_id).get_api_data(
2145 'locked_by': User.get(_user_id).get_api_data(
2146 include_secrets=include_secrets) if _user_id else None,
2146 include_secrets=include_secrets) if _user_id else None,
2147 'locked_date': time_to_datetime(_time) if _time else None,
2147 'locked_date': time_to_datetime(_time) if _time else None,
2148 'lock_reason': _reason if _reason else None,
2148 'lock_reason': _reason if _reason else None,
2149 }
2149 }
2150
2150
2151 # TODO: mikhail: should be per-repo settings here
2151 # TODO: mikhail: should be per-repo settings here
2152 rc_config = SettingsModel().get_all_settings()
2152 rc_config = SettingsModel().get_all_settings()
2153 repository_fields = str2bool(
2153 repository_fields = str2bool(
2154 rc_config.get('rhodecode_repository_fields'))
2154 rc_config.get('rhodecode_repository_fields'))
2155 if repository_fields:
2155 if repository_fields:
2156 for f in self.extra_fields:
2156 for f in self.extra_fields:
2157 data[f.field_key_prefixed] = f.field_value
2157 data[f.field_key_prefixed] = f.field_value
2158
2158
2159 return data
2159 return data
2160
2160
2161 @classmethod
2161 @classmethod
2162 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2162 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2163 if not lock_time:
2163 if not lock_time:
2164 lock_time = time.time()
2164 lock_time = time.time()
2165 if not lock_reason:
2165 if not lock_reason:
2166 lock_reason = cls.LOCK_AUTOMATIC
2166 lock_reason = cls.LOCK_AUTOMATIC
2167 repo.locked = [user_id, lock_time, lock_reason]
2167 repo.locked = [user_id, lock_time, lock_reason]
2168 Session().add(repo)
2168 Session().add(repo)
2169 Session().commit()
2169 Session().commit()
2170
2170
2171 @classmethod
2171 @classmethod
2172 def unlock(cls, repo):
2172 def unlock(cls, repo):
2173 repo.locked = None
2173 repo.locked = None
2174 Session().add(repo)
2174 Session().add(repo)
2175 Session().commit()
2175 Session().commit()
2176
2176
2177 @classmethod
2177 @classmethod
2178 def getlock(cls, repo):
2178 def getlock(cls, repo):
2179 return repo.locked
2179 return repo.locked
2180
2180
2181 def is_user_lock(self, user_id):
2181 def is_user_lock(self, user_id):
2182 if self.lock[0]:
2182 if self.lock[0]:
2183 lock_user_id = safe_int(self.lock[0])
2183 lock_user_id = safe_int(self.lock[0])
2184 user_id = safe_int(user_id)
2184 user_id = safe_int(user_id)
2185 # both are ints, and they are equal
2185 # both are ints, and they are equal
2186 return all([lock_user_id, user_id]) and lock_user_id == user_id
2186 return all([lock_user_id, user_id]) and lock_user_id == user_id
2187
2187
2188 return False
2188 return False
2189
2189
2190 def get_locking_state(self, action, user_id, only_when_enabled=True):
2190 def get_locking_state(self, action, user_id, only_when_enabled=True):
2191 """
2191 """
2192 Checks locking on this repository, if locking is enabled and lock is
2192 Checks locking on this repository, if locking is enabled and lock is
2193 present returns a tuple of make_lock, locked, locked_by.
2193 present returns a tuple of make_lock, locked, locked_by.
2194 make_lock can have 3 states None (do nothing) True, make lock
2194 make_lock can have 3 states None (do nothing) True, make lock
2195 False release lock, This value is later propagated to hooks, which
2195 False release lock, This value is later propagated to hooks, which
2196 do the locking. Think about this as signals passed to hooks what to do.
2196 do the locking. Think about this as signals passed to hooks what to do.
2197
2197
2198 """
2198 """
2199 # TODO: johbo: This is part of the business logic and should be moved
2199 # TODO: johbo: This is part of the business logic and should be moved
2200 # into the RepositoryModel.
2200 # into the RepositoryModel.
2201
2201
2202 if action not in ('push', 'pull'):
2202 if action not in ('push', 'pull'):
2203 raise ValueError("Invalid action value: %s" % repr(action))
2203 raise ValueError("Invalid action value: %s" % repr(action))
2204
2204
2205 # defines if locked error should be thrown to user
2205 # defines if locked error should be thrown to user
2206 currently_locked = False
2206 currently_locked = False
2207 # defines if new lock should be made, tri-state
2207 # defines if new lock should be made, tri-state
2208 make_lock = None
2208 make_lock = None
2209 repo = self
2209 repo = self
2210 user = User.get(user_id)
2210 user = User.get(user_id)
2211
2211
2212 lock_info = repo.locked
2212 lock_info = repo.locked
2213
2213
2214 if repo and (repo.enable_locking or not only_when_enabled):
2214 if repo and (repo.enable_locking or not only_when_enabled):
2215 if action == 'push':
2215 if action == 'push':
2216 # check if it's already locked !, if it is compare users
2216 # check if it's already locked !, if it is compare users
2217 locked_by_user_id = lock_info[0]
2217 locked_by_user_id = lock_info[0]
2218 if user.user_id == locked_by_user_id:
2218 if user.user_id == locked_by_user_id:
2219 log.debug(
2219 log.debug(
2220 'Got `push` action from user %s, now unlocking', user)
2220 'Got `push` action from user %s, now unlocking', user)
2221 # unlock if we have push from user who locked
2221 # unlock if we have push from user who locked
2222 make_lock = False
2222 make_lock = False
2223 else:
2223 else:
2224 # we're not the same user who locked, ban with
2224 # we're not the same user who locked, ban with
2225 # code defined in settings (default is 423 HTTP Locked) !
2225 # code defined in settings (default is 423 HTTP Locked) !
2226 log.debug('Repo %s is currently locked by %s', repo, user)
2226 log.debug('Repo %s is currently locked by %s', repo, user)
2227 currently_locked = True
2227 currently_locked = True
2228 elif action == 'pull':
2228 elif action == 'pull':
2229 # [0] user [1] date
2229 # [0] user [1] date
2230 if lock_info[0] and lock_info[1]:
2230 if lock_info[0] and lock_info[1]:
2231 log.debug('Repo %s is currently locked by %s', repo, user)
2231 log.debug('Repo %s is currently locked by %s', repo, user)
2232 currently_locked = True
2232 currently_locked = True
2233 else:
2233 else:
2234 log.debug('Setting lock on repo %s by %s', repo, user)
2234 log.debug('Setting lock on repo %s by %s', repo, user)
2235 make_lock = True
2235 make_lock = True
2236
2236
2237 else:
2237 else:
2238 log.debug('Repository %s do not have locking enabled', repo)
2238 log.debug('Repository %s do not have locking enabled', repo)
2239
2239
2240 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2240 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2241 make_lock, currently_locked, lock_info)
2241 make_lock, currently_locked, lock_info)
2242
2242
2243 from rhodecode.lib.auth import HasRepoPermissionAny
2243 from rhodecode.lib.auth import HasRepoPermissionAny
2244 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2244 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2245 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2245 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2246 # if we don't have at least write permission we cannot make a lock
2246 # if we don't have at least write permission we cannot make a lock
2247 log.debug('lock state reset back to FALSE due to lack '
2247 log.debug('lock state reset back to FALSE due to lack '
2248 'of at least read permission')
2248 'of at least read permission')
2249 make_lock = False
2249 make_lock = False
2250
2250
2251 return make_lock, currently_locked, lock_info
2251 return make_lock, currently_locked, lock_info
2252
2252
2253 @property
2253 @property
2254 def last_commit_cache_update_diff(self):
2254 def last_commit_cache_update_diff(self):
2255 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2255 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2256
2256
2257 @classmethod
2257 @classmethod
2258 def _load_commit_change(cls, last_commit_cache):
2258 def _load_commit_change(cls, last_commit_cache):
2259 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2259 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2260 empty_date = datetime.datetime.fromtimestamp(0)
2260 empty_date = datetime.datetime.fromtimestamp(0)
2261 date_latest = last_commit_cache.get('date', empty_date)
2261 date_latest = last_commit_cache.get('date', empty_date)
2262 try:
2262 try:
2263 return parse_datetime(date_latest)
2263 return parse_datetime(date_latest)
2264 except Exception:
2264 except Exception:
2265 return empty_date
2265 return empty_date
2266
2266
2267 @property
2267 @property
2268 def last_commit_change(self):
2268 def last_commit_change(self):
2269 return self._load_commit_change(self.changeset_cache)
2269 return self._load_commit_change(self.changeset_cache)
2270
2270
2271 @property
2271 @property
2272 def last_db_change(self):
2272 def last_db_change(self):
2273 return self.updated_on
2273 return self.updated_on
2274
2274
2275 @property
2275 @property
2276 def clone_uri_hidden(self):
2276 def clone_uri_hidden(self):
2277 clone_uri = self.clone_uri
2277 clone_uri = self.clone_uri
2278 if clone_uri:
2278 if clone_uri:
2279 import urlobject
2279 import urlobject
2280 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2280 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2281 if url_obj.password:
2281 if url_obj.password:
2282 clone_uri = url_obj.with_password('*****')
2282 clone_uri = url_obj.with_password('*****')
2283 return clone_uri
2283 return clone_uri
2284
2284
2285 @property
2285 @property
2286 def push_uri_hidden(self):
2286 def push_uri_hidden(self):
2287 push_uri = self.push_uri
2287 push_uri = self.push_uri
2288 if push_uri:
2288 if push_uri:
2289 import urlobject
2289 import urlobject
2290 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2290 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2291 if url_obj.password:
2291 if url_obj.password:
2292 push_uri = url_obj.with_password('*****')
2292 push_uri = url_obj.with_password('*****')
2293 return push_uri
2293 return push_uri
2294
2294
2295 def clone_url(self, **override):
2295 def clone_url(self, **override):
2296 from rhodecode.model.settings import SettingsModel
2296 from rhodecode.model.settings import SettingsModel
2297
2297
2298 uri_tmpl = None
2298 uri_tmpl = None
2299 if 'with_id' in override:
2299 if 'with_id' in override:
2300 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2300 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2301 del override['with_id']
2301 del override['with_id']
2302
2302
2303 if 'uri_tmpl' in override:
2303 if 'uri_tmpl' in override:
2304 uri_tmpl = override['uri_tmpl']
2304 uri_tmpl = override['uri_tmpl']
2305 del override['uri_tmpl']
2305 del override['uri_tmpl']
2306
2306
2307 ssh = False
2307 ssh = False
2308 if 'ssh' in override:
2308 if 'ssh' in override:
2309 ssh = True
2309 ssh = True
2310 del override['ssh']
2310 del override['ssh']
2311
2311
2312 # we didn't override our tmpl from **overrides
2312 # we didn't override our tmpl from **overrides
2313 request = get_current_request()
2313 request = get_current_request()
2314 if not uri_tmpl:
2314 if not uri_tmpl:
2315 if hasattr(request, 'call_context') and hasattr(request.call_context, 'rc_config'):
2315 if hasattr(request, 'call_context') and hasattr(request.call_context, 'rc_config'):
2316 rc_config = request.call_context.rc_config
2316 rc_config = request.call_context.rc_config
2317 else:
2317 else:
2318 rc_config = SettingsModel().get_all_settings(cache=True)
2318 rc_config = SettingsModel().get_all_settings(cache=True)
2319
2319
2320 if ssh:
2320 if ssh:
2321 uri_tmpl = rc_config.get(
2321 uri_tmpl = rc_config.get(
2322 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2322 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2323
2323
2324 else:
2324 else:
2325 uri_tmpl = rc_config.get(
2325 uri_tmpl = rc_config.get(
2326 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2326 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2327
2327
2328 return get_clone_url(request=request,
2328 return get_clone_url(request=request,
2329 uri_tmpl=uri_tmpl,
2329 uri_tmpl=uri_tmpl,
2330 repo_name=self.repo_name,
2330 repo_name=self.repo_name,
2331 repo_id=self.repo_id,
2331 repo_id=self.repo_id,
2332 repo_type=self.repo_type,
2332 repo_type=self.repo_type,
2333 **override)
2333 **override)
2334
2334
2335 def set_state(self, state):
2335 def set_state(self, state):
2336 self.repo_state = state
2336 self.repo_state = state
2337 Session().add(self)
2337 Session().add(self)
2338 #==========================================================================
2338 #==========================================================================
2339 # SCM PROPERTIES
2339 # SCM PROPERTIES
2340 #==========================================================================
2340 #==========================================================================
2341
2341
2342 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None, maybe_unreachable=False):
2342 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None, maybe_unreachable=False):
2343 return get_commit_safe(
2343 return get_commit_safe(
2344 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load,
2344 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load,
2345 maybe_unreachable=maybe_unreachable)
2345 maybe_unreachable=maybe_unreachable)
2346
2346
2347 def get_changeset(self, rev=None, pre_load=None):
2347 def get_changeset(self, rev=None, pre_load=None):
2348 warnings.warn("Use get_commit", DeprecationWarning)
2348 warnings.warn("Use get_commit", DeprecationWarning)
2349 commit_id = None
2349 commit_id = None
2350 commit_idx = None
2350 commit_idx = None
2351 if isinstance(rev, compat.string_types):
2351 if isinstance(rev, compat.string_types):
2352 commit_id = rev
2352 commit_id = rev
2353 else:
2353 else:
2354 commit_idx = rev
2354 commit_idx = rev
2355 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2355 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2356 pre_load=pre_load)
2356 pre_load=pre_load)
2357
2357
2358 def get_landing_commit(self):
2358 def get_landing_commit(self):
2359 """
2359 """
2360 Returns landing commit, or if that doesn't exist returns the tip
2360 Returns landing commit, or if that doesn't exist returns the tip
2361 """
2361 """
2362 _rev_type, _rev = self.landing_rev
2362 _rev_type, _rev = self.landing_rev
2363 commit = self.get_commit(_rev)
2363 commit = self.get_commit(_rev)
2364 if isinstance(commit, EmptyCommit):
2364 if isinstance(commit, EmptyCommit):
2365 return self.get_commit()
2365 return self.get_commit()
2366 return commit
2366 return commit
2367
2367
2368 def flush_commit_cache(self):
2368 def flush_commit_cache(self):
2369 self.update_commit_cache(cs_cache={'raw_id':'0'})
2369 self.update_commit_cache(cs_cache={'raw_id':'0'})
2370 self.update_commit_cache()
2370 self.update_commit_cache()
2371
2371
2372 def update_commit_cache(self, cs_cache=None, config=None):
2372 def update_commit_cache(self, cs_cache=None, config=None):
2373 """
2373 """
2374 Update cache of last commit for repository
2374 Update cache of last commit for repository
2375 cache_keys should be::
2375 cache_keys should be::
2376
2376
2377 source_repo_id
2377 source_repo_id
2378 short_id
2378 short_id
2379 raw_id
2379 raw_id
2380 revision
2380 revision
2381 parents
2381 parents
2382 message
2382 message
2383 date
2383 date
2384 author
2384 author
2385 updated_on
2385 updated_on
2386
2386
2387 """
2387 """
2388 from rhodecode.lib.vcs.backends.base import BaseChangeset
2388 from rhodecode.lib.vcs.backends.base import BaseChangeset
2389 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2389 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2390 empty_date = datetime.datetime.fromtimestamp(0)
2390 empty_date = datetime.datetime.fromtimestamp(0)
2391
2391
2392 if cs_cache is None:
2392 if cs_cache is None:
2393 # use no-cache version here
2393 # use no-cache version here
2394 try:
2394 try:
2395 scm_repo = self.scm_instance(cache=False, config=config)
2395 scm_repo = self.scm_instance(cache=False, config=config)
2396 except VCSError:
2396 except VCSError:
2397 scm_repo = None
2397 scm_repo = None
2398 empty = scm_repo is None or scm_repo.is_empty()
2398 empty = scm_repo is None or scm_repo.is_empty()
2399
2399
2400 if not empty:
2400 if not empty:
2401 cs_cache = scm_repo.get_commit(
2401 cs_cache = scm_repo.get_commit(
2402 pre_load=["author", "date", "message", "parents", "branch"])
2402 pre_load=["author", "date", "message", "parents", "branch"])
2403 else:
2403 else:
2404 cs_cache = EmptyCommit()
2404 cs_cache = EmptyCommit()
2405
2405
2406 if isinstance(cs_cache, BaseChangeset):
2406 if isinstance(cs_cache, BaseChangeset):
2407 cs_cache = cs_cache.__json__()
2407 cs_cache = cs_cache.__json__()
2408
2408
2409 def is_outdated(new_cs_cache):
2409 def is_outdated(new_cs_cache):
2410 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2410 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2411 new_cs_cache['revision'] != self.changeset_cache['revision']):
2411 new_cs_cache['revision'] != self.changeset_cache['revision']):
2412 return True
2412 return True
2413 return False
2413 return False
2414
2414
2415 # check if we have maybe already latest cached revision
2415 # check if we have maybe already latest cached revision
2416 if is_outdated(cs_cache) or not self.changeset_cache:
2416 if is_outdated(cs_cache) or not self.changeset_cache:
2417 _current_datetime = datetime.datetime.utcnow()
2417 _current_datetime = datetime.datetime.utcnow()
2418 last_change = cs_cache.get('date') or _current_datetime
2418 last_change = cs_cache.get('date') or _current_datetime
2419 # we check if last update is newer than the new value
2419 # we check if last update is newer than the new value
2420 # if yes, we use the current timestamp instead. Imagine you get
2420 # if yes, we use the current timestamp instead. Imagine you get
2421 # old commit pushed 1y ago, we'd set last update 1y to ago.
2421 # old commit pushed 1y ago, we'd set last update 1y to ago.
2422 last_change_timestamp = datetime_to_time(last_change)
2422 last_change_timestamp = datetime_to_time(last_change)
2423 current_timestamp = datetime_to_time(last_change)
2423 current_timestamp = datetime_to_time(last_change)
2424 if last_change_timestamp > current_timestamp and not empty:
2424 if last_change_timestamp > current_timestamp and not empty:
2425 cs_cache['date'] = _current_datetime
2425 cs_cache['date'] = _current_datetime
2426
2426
2427 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2427 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2428 cs_cache['updated_on'] = time.time()
2428 cs_cache['updated_on'] = time.time()
2429 self.changeset_cache = cs_cache
2429 self.changeset_cache = cs_cache
2430 self.updated_on = last_change
2430 self.updated_on = last_change
2431 Session().add(self)
2431 Session().add(self)
2432 Session().commit()
2432 Session().commit()
2433
2433
2434 else:
2434 else:
2435 if empty:
2435 if empty:
2436 cs_cache = EmptyCommit().__json__()
2436 cs_cache = EmptyCommit().__json__()
2437 else:
2437 else:
2438 cs_cache = self.changeset_cache
2438 cs_cache = self.changeset_cache
2439
2439
2440 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2440 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2441
2441
2442 cs_cache['updated_on'] = time.time()
2442 cs_cache['updated_on'] = time.time()
2443 self.changeset_cache = cs_cache
2443 self.changeset_cache = cs_cache
2444 self.updated_on = _date_latest
2444 self.updated_on = _date_latest
2445 Session().add(self)
2445 Session().add(self)
2446 Session().commit()
2446 Session().commit()
2447
2447
2448 log.debug('updated repo `%s` with new commit cache %s, and last update_date: %s',
2448 log.debug('updated repo `%s` with new commit cache %s, and last update_date: %s',
2449 self.repo_name, cs_cache, _date_latest)
2449 self.repo_name, cs_cache, _date_latest)
2450
2450
2451 @property
2451 @property
2452 def tip(self):
2452 def tip(self):
2453 return self.get_commit('tip')
2453 return self.get_commit('tip')
2454
2454
2455 @property
2455 @property
2456 def author(self):
2456 def author(self):
2457 return self.tip.author
2457 return self.tip.author
2458
2458
2459 @property
2459 @property
2460 def last_change(self):
2460 def last_change(self):
2461 return self.scm_instance().last_change
2461 return self.scm_instance().last_change
2462
2462
2463 def get_comments(self, revisions=None):
2463 def get_comments(self, revisions=None):
2464 """
2464 """
2465 Returns comments for this repository grouped by revisions
2465 Returns comments for this repository grouped by revisions
2466
2466
2467 :param revisions: filter query by revisions only
2467 :param revisions: filter query by revisions only
2468 """
2468 """
2469 cmts = ChangesetComment.query()\
2469 cmts = ChangesetComment.query()\
2470 .filter(ChangesetComment.repo == self)
2470 .filter(ChangesetComment.repo == self)
2471 if revisions:
2471 if revisions:
2472 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2472 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2473 grouped = collections.defaultdict(list)
2473 grouped = collections.defaultdict(list)
2474 for cmt in cmts.all():
2474 for cmt in cmts.all():
2475 grouped[cmt.revision].append(cmt)
2475 grouped[cmt.revision].append(cmt)
2476 return grouped
2476 return grouped
2477
2477
2478 def statuses(self, revisions=None):
2478 def statuses(self, revisions=None):
2479 """
2479 """
2480 Returns statuses for this repository
2480 Returns statuses for this repository
2481
2481
2482 :param revisions: list of revisions to get statuses for
2482 :param revisions: list of revisions to get statuses for
2483 """
2483 """
2484 statuses = ChangesetStatus.query()\
2484 statuses = ChangesetStatus.query()\
2485 .filter(ChangesetStatus.repo == self)\
2485 .filter(ChangesetStatus.repo == self)\
2486 .filter(ChangesetStatus.version == 0)
2486 .filter(ChangesetStatus.version == 0)
2487
2487
2488 if revisions:
2488 if revisions:
2489 # Try doing the filtering in chunks to avoid hitting limits
2489 # Try doing the filtering in chunks to avoid hitting limits
2490 size = 500
2490 size = 500
2491 status_results = []
2491 status_results = []
2492 for chunk in xrange(0, len(revisions), size):
2492 for chunk in xrange(0, len(revisions), size):
2493 status_results += statuses.filter(
2493 status_results += statuses.filter(
2494 ChangesetStatus.revision.in_(
2494 ChangesetStatus.revision.in_(
2495 revisions[chunk: chunk+size])
2495 revisions[chunk: chunk+size])
2496 ).all()
2496 ).all()
2497 else:
2497 else:
2498 status_results = statuses.all()
2498 status_results = statuses.all()
2499
2499
2500 grouped = {}
2500 grouped = {}
2501
2501
2502 # maybe we have open new pullrequest without a status?
2502 # maybe we have open new pullrequest without a status?
2503 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2503 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2504 status_lbl = ChangesetStatus.get_status_lbl(stat)
2504 status_lbl = ChangesetStatus.get_status_lbl(stat)
2505 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2505 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2506 for rev in pr.revisions:
2506 for rev in pr.revisions:
2507 pr_id = pr.pull_request_id
2507 pr_id = pr.pull_request_id
2508 pr_repo = pr.target_repo.repo_name
2508 pr_repo = pr.target_repo.repo_name
2509 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2509 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2510
2510
2511 for stat in status_results:
2511 for stat in status_results:
2512 pr_id = pr_repo = None
2512 pr_id = pr_repo = None
2513 if stat.pull_request:
2513 if stat.pull_request:
2514 pr_id = stat.pull_request.pull_request_id
2514 pr_id = stat.pull_request.pull_request_id
2515 pr_repo = stat.pull_request.target_repo.repo_name
2515 pr_repo = stat.pull_request.target_repo.repo_name
2516 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2516 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2517 pr_id, pr_repo]
2517 pr_id, pr_repo]
2518 return grouped
2518 return grouped
2519
2519
2520 # ==========================================================================
2520 # ==========================================================================
2521 # SCM CACHE INSTANCE
2521 # SCM CACHE INSTANCE
2522 # ==========================================================================
2522 # ==========================================================================
2523
2523
2524 def scm_instance(self, **kwargs):
2524 def scm_instance(self, **kwargs):
2525 import rhodecode
2525 import rhodecode
2526
2526
2527 # Passing a config will not hit the cache currently only used
2527 # Passing a config will not hit the cache currently only used
2528 # for repo2dbmapper
2528 # for repo2dbmapper
2529 config = kwargs.pop('config', None)
2529 config = kwargs.pop('config', None)
2530 cache = kwargs.pop('cache', None)
2530 cache = kwargs.pop('cache', None)
2531 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2531 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2532 if vcs_full_cache is not None:
2532 if vcs_full_cache is not None:
2533 # allows override global config
2533 # allows override global config
2534 full_cache = vcs_full_cache
2534 full_cache = vcs_full_cache
2535 else:
2535 else:
2536 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2536 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2537 # if cache is NOT defined use default global, else we have a full
2537 # if cache is NOT defined use default global, else we have a full
2538 # control over cache behaviour
2538 # control over cache behaviour
2539 if cache is None and full_cache and not config:
2539 if cache is None and full_cache and not config:
2540 log.debug('Initializing pure cached instance for %s', self.repo_path)
2540 log.debug('Initializing pure cached instance for %s', self.repo_path)
2541 return self._get_instance_cached()
2541 return self._get_instance_cached()
2542
2542
2543 # cache here is sent to the "vcs server"
2543 # cache here is sent to the "vcs server"
2544 return self._get_instance(cache=bool(cache), config=config)
2544 return self._get_instance(cache=bool(cache), config=config)
2545
2545
2546 def _get_instance_cached(self):
2546 def _get_instance_cached(self):
2547 from rhodecode.lib import rc_cache
2547 from rhodecode.lib import rc_cache
2548
2548
2549 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2549 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2550 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2550 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2551 repo_id=self.repo_id)
2551 repo_id=self.repo_id)
2552 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2552 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2553
2553
2554 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2554 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2555 def get_instance_cached(repo_id, context_id, _cache_state_uid):
2555 def get_instance_cached(repo_id, context_id, _cache_state_uid):
2556 return self._get_instance(repo_state_uid=_cache_state_uid)
2556 return self._get_instance(repo_state_uid=_cache_state_uid)
2557
2557
2558 # we must use thread scoped cache here,
2558 # we must use thread scoped cache here,
2559 # because each thread of gevent needs it's own not shared connection and cache
2559 # because each thread of gevent needs it's own not shared connection and cache
2560 # we also alter `args` so the cache key is individual for every green thread.
2560 # we also alter `args` so the cache key is individual for every green thread.
2561 inv_context_manager = rc_cache.InvalidationContext(
2561 inv_context_manager = rc_cache.InvalidationContext(
2562 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2562 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2563 thread_scoped=True)
2563 thread_scoped=True)
2564 with inv_context_manager as invalidation_context:
2564 with inv_context_manager as invalidation_context:
2565 cache_state_uid = invalidation_context.cache_data['cache_state_uid']
2565 cache_state_uid = invalidation_context.cache_data['cache_state_uid']
2566 args = (self.repo_id, inv_context_manager.cache_key, cache_state_uid)
2566 args = (self.repo_id, inv_context_manager.cache_key, cache_state_uid)
2567
2567
2568 # re-compute and store cache if we get invalidate signal
2568 # re-compute and store cache if we get invalidate signal
2569 if invalidation_context.should_invalidate():
2569 if invalidation_context.should_invalidate():
2570 instance = get_instance_cached.refresh(*args)
2570 instance = get_instance_cached.refresh(*args)
2571 else:
2571 else:
2572 instance = get_instance_cached(*args)
2572 instance = get_instance_cached(*args)
2573
2573
2574 log.debug('Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2574 log.debug('Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2575 return instance
2575 return instance
2576
2576
2577 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2577 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2578 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2578 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2579 self.repo_type, self.repo_path, cache)
2579 self.repo_type, self.repo_path, cache)
2580 config = config or self._config
2580 config = config or self._config
2581 custom_wire = {
2581 custom_wire = {
2582 'cache': cache, # controls the vcs.remote cache
2582 'cache': cache, # controls the vcs.remote cache
2583 'repo_state_uid': repo_state_uid
2583 'repo_state_uid': repo_state_uid
2584 }
2584 }
2585 repo = get_vcs_instance(
2585 repo = get_vcs_instance(
2586 repo_path=safe_str(self.repo_full_path),
2586 repo_path=safe_str(self.repo_full_path),
2587 config=config,
2587 config=config,
2588 with_wire=custom_wire,
2588 with_wire=custom_wire,
2589 create=False,
2589 create=False,
2590 _vcs_alias=self.repo_type)
2590 _vcs_alias=self.repo_type)
2591 if repo is not None:
2591 if repo is not None:
2592 repo.count() # cache rebuild
2592 repo.count() # cache rebuild
2593 return repo
2593 return repo
2594
2594
2595 def get_shadow_repository_path(self, workspace_id):
2595 def get_shadow_repository_path(self, workspace_id):
2596 from rhodecode.lib.vcs.backends.base import BaseRepository
2596 from rhodecode.lib.vcs.backends.base import BaseRepository
2597 shadow_repo_path = BaseRepository._get_shadow_repository_path(
2597 shadow_repo_path = BaseRepository._get_shadow_repository_path(
2598 self.repo_full_path, self.repo_id, workspace_id)
2598 self.repo_full_path, self.repo_id, workspace_id)
2599 return shadow_repo_path
2599 return shadow_repo_path
2600
2600
2601 def __json__(self):
2601 def __json__(self):
2602 return {'landing_rev': self.landing_rev}
2602 return {'landing_rev': self.landing_rev}
2603
2603
2604 def get_dict(self):
2604 def get_dict(self):
2605
2605
2606 # Since we transformed `repo_name` to a hybrid property, we need to
2606 # Since we transformed `repo_name` to a hybrid property, we need to
2607 # keep compatibility with the code which uses `repo_name` field.
2607 # keep compatibility with the code which uses `repo_name` field.
2608
2608
2609 result = super(Repository, self).get_dict()
2609 result = super(Repository, self).get_dict()
2610 result['repo_name'] = result.pop('_repo_name', None)
2610 result['repo_name'] = result.pop('_repo_name', None)
2611 return result
2611 return result
2612
2612
2613
2613
2614 class RepoGroup(Base, BaseModel):
2614 class RepoGroup(Base, BaseModel):
2615 __tablename__ = 'groups'
2615 __tablename__ = 'groups'
2616 __table_args__ = (
2616 __table_args__ = (
2617 UniqueConstraint('group_name', 'group_parent_id'),
2617 UniqueConstraint('group_name', 'group_parent_id'),
2618 base_table_args,
2618 base_table_args,
2619 )
2619 )
2620 __mapper_args__ = {'order_by': 'group_name'}
2620 __mapper_args__ = {'order_by': 'group_name'}
2621
2621
2622 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2622 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2623
2623
2624 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2624 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2625 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2625 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2626 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2626 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2627 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2627 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2628 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2628 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2629 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2629 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2630 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2630 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2631 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2631 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2632 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2632 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2633 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2633 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2634 _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) # JSON data
2634 _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) # JSON data
2635
2635
2636 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2636 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2637 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2637 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2638 parent_group = relationship('RepoGroup', remote_side=group_id)
2638 parent_group = relationship('RepoGroup', remote_side=group_id)
2639 user = relationship('User')
2639 user = relationship('User')
2640 integrations = relationship('Integration', cascade="all, delete-orphan")
2640 integrations = relationship('Integration', cascade="all, delete-orphan")
2641
2641
2642 # no cascade, set NULL
2642 # no cascade, set NULL
2643 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_group_id==RepoGroup.group_id')
2643 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_group_id==RepoGroup.group_id')
2644
2644
2645 def __init__(self, group_name='', parent_group=None):
2645 def __init__(self, group_name='', parent_group=None):
2646 self.group_name = group_name
2646 self.group_name = group_name
2647 self.parent_group = parent_group
2647 self.parent_group = parent_group
2648
2648
2649 def __unicode__(self):
2649 def __unicode__(self):
2650 return u"<%s('id:%s:%s')>" % (
2650 return u"<%s('id:%s:%s')>" % (
2651 self.__class__.__name__, self.group_id, self.group_name)
2651 self.__class__.__name__, self.group_id, self.group_name)
2652
2652
2653 @hybrid_property
2653 @hybrid_property
2654 def group_name(self):
2654 def group_name(self):
2655 return self._group_name
2655 return self._group_name
2656
2656
2657 @group_name.setter
2657 @group_name.setter
2658 def group_name(self, value):
2658 def group_name(self, value):
2659 self._group_name = value
2659 self._group_name = value
2660 self.group_name_hash = self.hash_repo_group_name(value)
2660 self.group_name_hash = self.hash_repo_group_name(value)
2661
2661
2662 @classmethod
2662 @classmethod
2663 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
2663 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
2664 from rhodecode.lib.vcs.backends.base import EmptyCommit
2664 from rhodecode.lib.vcs.backends.base import EmptyCommit
2665 dummy = EmptyCommit().__json__()
2665 dummy = EmptyCommit().__json__()
2666 if not changeset_cache_raw:
2666 if not changeset_cache_raw:
2667 dummy['source_repo_id'] = repo_id
2667 dummy['source_repo_id'] = repo_id
2668 return json.loads(json.dumps(dummy))
2668 return json.loads(json.dumps(dummy))
2669
2669
2670 try:
2670 try:
2671 return json.loads(changeset_cache_raw)
2671 return json.loads(changeset_cache_raw)
2672 except TypeError:
2672 except TypeError:
2673 return dummy
2673 return dummy
2674 except Exception:
2674 except Exception:
2675 log.error(traceback.format_exc())
2675 log.error(traceback.format_exc())
2676 return dummy
2676 return dummy
2677
2677
2678 @hybrid_property
2678 @hybrid_property
2679 def changeset_cache(self):
2679 def changeset_cache(self):
2680 return self._load_changeset_cache('', self._changeset_cache)
2680 return self._load_changeset_cache('', self._changeset_cache)
2681
2681
2682 @changeset_cache.setter
2682 @changeset_cache.setter
2683 def changeset_cache(self, val):
2683 def changeset_cache(self, val):
2684 try:
2684 try:
2685 self._changeset_cache = json.dumps(val)
2685 self._changeset_cache = json.dumps(val)
2686 except Exception:
2686 except Exception:
2687 log.error(traceback.format_exc())
2687 log.error(traceback.format_exc())
2688
2688
2689 @validates('group_parent_id')
2689 @validates('group_parent_id')
2690 def validate_group_parent_id(self, key, val):
2690 def validate_group_parent_id(self, key, val):
2691 """
2691 """
2692 Check cycle references for a parent group to self
2692 Check cycle references for a parent group to self
2693 """
2693 """
2694 if self.group_id and val:
2694 if self.group_id and val:
2695 assert val != self.group_id
2695 assert val != self.group_id
2696
2696
2697 return val
2697 return val
2698
2698
2699 @hybrid_property
2699 @hybrid_property
2700 def description_safe(self):
2700 def description_safe(self):
2701 from rhodecode.lib import helpers as h
2701 from rhodecode.lib import helpers as h
2702 return h.escape(self.group_description)
2702 return h.escape(self.group_description)
2703
2703
2704 @classmethod
2704 @classmethod
2705 def hash_repo_group_name(cls, repo_group_name):
2705 def hash_repo_group_name(cls, repo_group_name):
2706 val = remove_formatting(repo_group_name)
2706 val = remove_formatting(repo_group_name)
2707 val = safe_str(val).lower()
2707 val = safe_str(val).lower()
2708 chars = []
2708 chars = []
2709 for c in val:
2709 for c in val:
2710 if c not in string.ascii_letters:
2710 if c not in string.ascii_letters:
2711 c = str(ord(c))
2711 c = str(ord(c))
2712 chars.append(c)
2712 chars.append(c)
2713
2713
2714 return ''.join(chars)
2714 return ''.join(chars)
2715
2715
2716 @classmethod
2716 @classmethod
2717 def _generate_choice(cls, repo_group):
2717 def _generate_choice(cls, repo_group):
2718 from webhelpers2.html import literal as _literal
2718 from webhelpers2.html import literal as _literal
2719 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2719 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2720 return repo_group.group_id, _name(repo_group.full_path_splitted)
2720 return repo_group.group_id, _name(repo_group.full_path_splitted)
2721
2721
2722 @classmethod
2722 @classmethod
2723 def groups_choices(cls, groups=None, show_empty_group=True):
2723 def groups_choices(cls, groups=None, show_empty_group=True):
2724 if not groups:
2724 if not groups:
2725 groups = cls.query().all()
2725 groups = cls.query().all()
2726
2726
2727 repo_groups = []
2727 repo_groups = []
2728 if show_empty_group:
2728 if show_empty_group:
2729 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2729 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2730
2730
2731 repo_groups.extend([cls._generate_choice(x) for x in groups])
2731 repo_groups.extend([cls._generate_choice(x) for x in groups])
2732
2732
2733 repo_groups = sorted(
2733 repo_groups = sorted(
2734 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2734 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2735 return repo_groups
2735 return repo_groups
2736
2736
2737 @classmethod
2737 @classmethod
2738 def url_sep(cls):
2738 def url_sep(cls):
2739 return URL_SEP
2739 return URL_SEP
2740
2740
2741 @classmethod
2741 @classmethod
2742 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2742 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2743 if case_insensitive:
2743 if case_insensitive:
2744 gr = cls.query().filter(func.lower(cls.group_name)
2744 gr = cls.query().filter(func.lower(cls.group_name)
2745 == func.lower(group_name))
2745 == func.lower(group_name))
2746 else:
2746 else:
2747 gr = cls.query().filter(cls.group_name == group_name)
2747 gr = cls.query().filter(cls.group_name == group_name)
2748 if cache:
2748 if cache:
2749 name_key = _hash_key(group_name)
2749 name_key = _hash_key(group_name)
2750 gr = gr.options(
2750 gr = gr.options(
2751 FromCache("sql_cache_short", "get_group_%s" % name_key))
2751 FromCache("sql_cache_short", "get_group_%s" % name_key))
2752 return gr.scalar()
2752 return gr.scalar()
2753
2753
2754 @classmethod
2754 @classmethod
2755 def get_user_personal_repo_group(cls, user_id):
2755 def get_user_personal_repo_group(cls, user_id):
2756 user = User.get(user_id)
2756 user = User.get(user_id)
2757 if user.username == User.DEFAULT_USER:
2757 if user.username == User.DEFAULT_USER:
2758 return None
2758 return None
2759
2759
2760 return cls.query()\
2760 return cls.query()\
2761 .filter(cls.personal == true()) \
2761 .filter(cls.personal == true()) \
2762 .filter(cls.user == user) \
2762 .filter(cls.user == user) \
2763 .order_by(cls.group_id.asc()) \
2763 .order_by(cls.group_id.asc()) \
2764 .first()
2764 .first()
2765
2765
2766 @classmethod
2766 @classmethod
2767 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2767 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2768 case_insensitive=True):
2768 case_insensitive=True):
2769 q = RepoGroup.query()
2769 q = RepoGroup.query()
2770
2770
2771 if not isinstance(user_id, Optional):
2771 if not isinstance(user_id, Optional):
2772 q = q.filter(RepoGroup.user_id == user_id)
2772 q = q.filter(RepoGroup.user_id == user_id)
2773
2773
2774 if not isinstance(group_id, Optional):
2774 if not isinstance(group_id, Optional):
2775 q = q.filter(RepoGroup.group_parent_id == group_id)
2775 q = q.filter(RepoGroup.group_parent_id == group_id)
2776
2776
2777 if case_insensitive:
2777 if case_insensitive:
2778 q = q.order_by(func.lower(RepoGroup.group_name))
2778 q = q.order_by(func.lower(RepoGroup.group_name))
2779 else:
2779 else:
2780 q = q.order_by(RepoGroup.group_name)
2780 q = q.order_by(RepoGroup.group_name)
2781 return q.all()
2781 return q.all()
2782
2782
2783 @property
2783 @property
2784 def parents(self, parents_recursion_limit=10):
2784 def parents(self, parents_recursion_limit=10):
2785 groups = []
2785 groups = []
2786 if self.parent_group is None:
2786 if self.parent_group is None:
2787 return groups
2787 return groups
2788 cur_gr = self.parent_group
2788 cur_gr = self.parent_group
2789 groups.insert(0, cur_gr)
2789 groups.insert(0, cur_gr)
2790 cnt = 0
2790 cnt = 0
2791 while 1:
2791 while 1:
2792 cnt += 1
2792 cnt += 1
2793 gr = getattr(cur_gr, 'parent_group', None)
2793 gr = getattr(cur_gr, 'parent_group', None)
2794 cur_gr = cur_gr.parent_group
2794 cur_gr = cur_gr.parent_group
2795 if gr is None:
2795 if gr is None:
2796 break
2796 break
2797 if cnt == parents_recursion_limit:
2797 if cnt == parents_recursion_limit:
2798 # this will prevent accidental infinit loops
2798 # this will prevent accidental infinit loops
2799 log.error('more than %s parents found for group %s, stopping '
2799 log.error('more than %s parents found for group %s, stopping '
2800 'recursive parent fetching', parents_recursion_limit, self)
2800 'recursive parent fetching', parents_recursion_limit, self)
2801 break
2801 break
2802
2802
2803 groups.insert(0, gr)
2803 groups.insert(0, gr)
2804 return groups
2804 return groups
2805
2805
2806 @property
2806 @property
2807 def last_commit_cache_update_diff(self):
2807 def last_commit_cache_update_diff(self):
2808 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2808 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2809
2809
2810 @classmethod
2810 @classmethod
2811 def _load_commit_change(cls, last_commit_cache):
2811 def _load_commit_change(cls, last_commit_cache):
2812 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2812 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2813 empty_date = datetime.datetime.fromtimestamp(0)
2813 empty_date = datetime.datetime.fromtimestamp(0)
2814 date_latest = last_commit_cache.get('date', empty_date)
2814 date_latest = last_commit_cache.get('date', empty_date)
2815 try:
2815 try:
2816 return parse_datetime(date_latest)
2816 return parse_datetime(date_latest)
2817 except Exception:
2817 except Exception:
2818 return empty_date
2818 return empty_date
2819
2819
2820 @property
2820 @property
2821 def last_commit_change(self):
2821 def last_commit_change(self):
2822 return self._load_commit_change(self.changeset_cache)
2822 return self._load_commit_change(self.changeset_cache)
2823
2823
2824 @property
2824 @property
2825 def last_db_change(self):
2825 def last_db_change(self):
2826 return self.updated_on
2826 return self.updated_on
2827
2827
2828 @property
2828 @property
2829 def children(self):
2829 def children(self):
2830 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2830 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2831
2831
2832 @property
2832 @property
2833 def name(self):
2833 def name(self):
2834 return self.group_name.split(RepoGroup.url_sep())[-1]
2834 return self.group_name.split(RepoGroup.url_sep())[-1]
2835
2835
2836 @property
2836 @property
2837 def full_path(self):
2837 def full_path(self):
2838 return self.group_name
2838 return self.group_name
2839
2839
2840 @property
2840 @property
2841 def full_path_splitted(self):
2841 def full_path_splitted(self):
2842 return self.group_name.split(RepoGroup.url_sep())
2842 return self.group_name.split(RepoGroup.url_sep())
2843
2843
2844 @property
2844 @property
2845 def repositories(self):
2845 def repositories(self):
2846 return Repository.query()\
2846 return Repository.query()\
2847 .filter(Repository.group == self)\
2847 .filter(Repository.group == self)\
2848 .order_by(Repository.repo_name)
2848 .order_by(Repository.repo_name)
2849
2849
2850 @property
2850 @property
2851 def repositories_recursive_count(self):
2851 def repositories_recursive_count(self):
2852 cnt = self.repositories.count()
2852 cnt = self.repositories.count()
2853
2853
2854 def children_count(group):
2854 def children_count(group):
2855 cnt = 0
2855 cnt = 0
2856 for child in group.children:
2856 for child in group.children:
2857 cnt += child.repositories.count()
2857 cnt += child.repositories.count()
2858 cnt += children_count(child)
2858 cnt += children_count(child)
2859 return cnt
2859 return cnt
2860
2860
2861 return cnt + children_count(self)
2861 return cnt + children_count(self)
2862
2862
2863 def _recursive_objects(self, include_repos=True, include_groups=True):
2863 def _recursive_objects(self, include_repos=True, include_groups=True):
2864 all_ = []
2864 all_ = []
2865
2865
2866 def _get_members(root_gr):
2866 def _get_members(root_gr):
2867 if include_repos:
2867 if include_repos:
2868 for r in root_gr.repositories:
2868 for r in root_gr.repositories:
2869 all_.append(r)
2869 all_.append(r)
2870 childs = root_gr.children.all()
2870 childs = root_gr.children.all()
2871 if childs:
2871 if childs:
2872 for gr in childs:
2872 for gr in childs:
2873 if include_groups:
2873 if include_groups:
2874 all_.append(gr)
2874 all_.append(gr)
2875 _get_members(gr)
2875 _get_members(gr)
2876
2876
2877 root_group = []
2877 root_group = []
2878 if include_groups:
2878 if include_groups:
2879 root_group = [self]
2879 root_group = [self]
2880
2880
2881 _get_members(self)
2881 _get_members(self)
2882 return root_group + all_
2882 return root_group + all_
2883
2883
2884 def recursive_groups_and_repos(self):
2884 def recursive_groups_and_repos(self):
2885 """
2885 """
2886 Recursive return all groups, with repositories in those groups
2886 Recursive return all groups, with repositories in those groups
2887 """
2887 """
2888 return self._recursive_objects()
2888 return self._recursive_objects()
2889
2889
2890 def recursive_groups(self):
2890 def recursive_groups(self):
2891 """
2891 """
2892 Returns all children groups for this group including children of children
2892 Returns all children groups for this group including children of children
2893 """
2893 """
2894 return self._recursive_objects(include_repos=False)
2894 return self._recursive_objects(include_repos=False)
2895
2895
2896 def recursive_repos(self):
2896 def recursive_repos(self):
2897 """
2897 """
2898 Returns all children repositories for this group
2898 Returns all children repositories for this group
2899 """
2899 """
2900 return self._recursive_objects(include_groups=False)
2900 return self._recursive_objects(include_groups=False)
2901
2901
2902 def get_new_name(self, group_name):
2902 def get_new_name(self, group_name):
2903 """
2903 """
2904 returns new full group name based on parent and new name
2904 returns new full group name based on parent and new name
2905
2905
2906 :param group_name:
2906 :param group_name:
2907 """
2907 """
2908 path_prefix = (self.parent_group.full_path_splitted if
2908 path_prefix = (self.parent_group.full_path_splitted if
2909 self.parent_group else [])
2909 self.parent_group else [])
2910 return RepoGroup.url_sep().join(path_prefix + [group_name])
2910 return RepoGroup.url_sep().join(path_prefix + [group_name])
2911
2911
2912 def update_commit_cache(self, config=None):
2912 def update_commit_cache(self, config=None):
2913 """
2913 """
2914 Update cache of last commit for newest repository inside this repository group.
2914 Update cache of last commit for newest repository inside this repository group.
2915 cache_keys should be::
2915 cache_keys should be::
2916
2916
2917 source_repo_id
2917 source_repo_id
2918 short_id
2918 short_id
2919 raw_id
2919 raw_id
2920 revision
2920 revision
2921 parents
2921 parents
2922 message
2922 message
2923 date
2923 date
2924 author
2924 author
2925
2925
2926 """
2926 """
2927 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2927 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2928 empty_date = datetime.datetime.fromtimestamp(0)
2928 empty_date = datetime.datetime.fromtimestamp(0)
2929
2929
2930 def repo_groups_and_repos(root_gr):
2930 def repo_groups_and_repos(root_gr):
2931 for _repo in root_gr.repositories:
2931 for _repo in root_gr.repositories:
2932 yield _repo
2932 yield _repo
2933 for child_group in root_gr.children.all():
2933 for child_group in root_gr.children.all():
2934 yield child_group
2934 yield child_group
2935
2935
2936 latest_repo_cs_cache = {}
2936 latest_repo_cs_cache = {}
2937 for obj in repo_groups_and_repos(self):
2937 for obj in repo_groups_and_repos(self):
2938 repo_cs_cache = obj.changeset_cache
2938 repo_cs_cache = obj.changeset_cache
2939 date_latest = latest_repo_cs_cache.get('date', empty_date)
2939 date_latest = latest_repo_cs_cache.get('date', empty_date)
2940 date_current = repo_cs_cache.get('date', empty_date)
2940 date_current = repo_cs_cache.get('date', empty_date)
2941 current_timestamp = datetime_to_time(parse_datetime(date_latest))
2941 current_timestamp = datetime_to_time(parse_datetime(date_latest))
2942 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
2942 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
2943 latest_repo_cs_cache = repo_cs_cache
2943 latest_repo_cs_cache = repo_cs_cache
2944 if hasattr(obj, 'repo_id'):
2944 if hasattr(obj, 'repo_id'):
2945 latest_repo_cs_cache['source_repo_id'] = obj.repo_id
2945 latest_repo_cs_cache['source_repo_id'] = obj.repo_id
2946 else:
2946 else:
2947 latest_repo_cs_cache['source_repo_id'] = repo_cs_cache.get('source_repo_id')
2947 latest_repo_cs_cache['source_repo_id'] = repo_cs_cache.get('source_repo_id')
2948
2948
2949 _date_latest = parse_datetime(latest_repo_cs_cache.get('date') or empty_date)
2949 _date_latest = parse_datetime(latest_repo_cs_cache.get('date') or empty_date)
2950
2950
2951 latest_repo_cs_cache['updated_on'] = time.time()
2951 latest_repo_cs_cache['updated_on'] = time.time()
2952 self.changeset_cache = latest_repo_cs_cache
2952 self.changeset_cache = latest_repo_cs_cache
2953 self.updated_on = _date_latest
2953 self.updated_on = _date_latest
2954 Session().add(self)
2954 Session().add(self)
2955 Session().commit()
2955 Session().commit()
2956
2956
2957 log.debug('updated repo group `%s` with new commit cache %s, and last update_date: %s',
2957 log.debug('updated repo group `%s` with new commit cache %s, and last update_date: %s',
2958 self.group_name, latest_repo_cs_cache, _date_latest)
2958 self.group_name, latest_repo_cs_cache, _date_latest)
2959
2959
2960 def permissions(self, with_admins=True, with_owner=True,
2960 def permissions(self, with_admins=True, with_owner=True,
2961 expand_from_user_groups=False):
2961 expand_from_user_groups=False):
2962 """
2962 """
2963 Permissions for repository groups
2963 Permissions for repository groups
2964 """
2964 """
2965 _admin_perm = 'group.admin'
2965 _admin_perm = 'group.admin'
2966
2966
2967 owner_row = []
2967 owner_row = []
2968 if with_owner:
2968 if with_owner:
2969 usr = AttributeDict(self.user.get_dict())
2969 usr = AttributeDict(self.user.get_dict())
2970 usr.owner_row = True
2970 usr.owner_row = True
2971 usr.permission = _admin_perm
2971 usr.permission = _admin_perm
2972 owner_row.append(usr)
2972 owner_row.append(usr)
2973
2973
2974 super_admin_ids = []
2974 super_admin_ids = []
2975 super_admin_rows = []
2975 super_admin_rows = []
2976 if with_admins:
2976 if with_admins:
2977 for usr in User.get_all_super_admins():
2977 for usr in User.get_all_super_admins():
2978 super_admin_ids.append(usr.user_id)
2978 super_admin_ids.append(usr.user_id)
2979 # if this admin is also owner, don't double the record
2979 # if this admin is also owner, don't double the record
2980 if usr.user_id == owner_row[0].user_id:
2980 if usr.user_id == owner_row[0].user_id:
2981 owner_row[0].admin_row = True
2981 owner_row[0].admin_row = True
2982 else:
2982 else:
2983 usr = AttributeDict(usr.get_dict())
2983 usr = AttributeDict(usr.get_dict())
2984 usr.admin_row = True
2984 usr.admin_row = True
2985 usr.permission = _admin_perm
2985 usr.permission = _admin_perm
2986 super_admin_rows.append(usr)
2986 super_admin_rows.append(usr)
2987
2987
2988 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2988 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2989 q = q.options(joinedload(UserRepoGroupToPerm.group),
2989 q = q.options(joinedload(UserRepoGroupToPerm.group),
2990 joinedload(UserRepoGroupToPerm.user),
2990 joinedload(UserRepoGroupToPerm.user),
2991 joinedload(UserRepoGroupToPerm.permission),)
2991 joinedload(UserRepoGroupToPerm.permission),)
2992
2992
2993 # get owners and admins and permissions. We do a trick of re-writing
2993 # get owners and admins and permissions. We do a trick of re-writing
2994 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2994 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2995 # has a global reference and changing one object propagates to all
2995 # has a global reference and changing one object propagates to all
2996 # others. This means if admin is also an owner admin_row that change
2996 # others. This means if admin is also an owner admin_row that change
2997 # would propagate to both objects
2997 # would propagate to both objects
2998 perm_rows = []
2998 perm_rows = []
2999 for _usr in q.all():
2999 for _usr in q.all():
3000 usr = AttributeDict(_usr.user.get_dict())
3000 usr = AttributeDict(_usr.user.get_dict())
3001 # if this user is also owner/admin, mark as duplicate record
3001 # if this user is also owner/admin, mark as duplicate record
3002 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
3002 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
3003 usr.duplicate_perm = True
3003 usr.duplicate_perm = True
3004 usr.permission = _usr.permission.permission_name
3004 usr.permission = _usr.permission.permission_name
3005 perm_rows.append(usr)
3005 perm_rows.append(usr)
3006
3006
3007 # filter the perm rows by 'default' first and then sort them by
3007 # filter the perm rows by 'default' first and then sort them by
3008 # admin,write,read,none permissions sorted again alphabetically in
3008 # admin,write,read,none permissions sorted again alphabetically in
3009 # each group
3009 # each group
3010 perm_rows = sorted(perm_rows, key=display_user_sort)
3010 perm_rows = sorted(perm_rows, key=display_user_sort)
3011
3011
3012 user_groups_rows = []
3012 user_groups_rows = []
3013 if expand_from_user_groups:
3013 if expand_from_user_groups:
3014 for ug in self.permission_user_groups(with_members=True):
3014 for ug in self.permission_user_groups(with_members=True):
3015 for user_data in ug.members:
3015 for user_data in ug.members:
3016 user_groups_rows.append(user_data)
3016 user_groups_rows.append(user_data)
3017
3017
3018 return super_admin_rows + owner_row + perm_rows + user_groups_rows
3018 return super_admin_rows + owner_row + perm_rows + user_groups_rows
3019
3019
3020 def permission_user_groups(self, with_members=False):
3020 def permission_user_groups(self, with_members=False):
3021 q = UserGroupRepoGroupToPerm.query()\
3021 q = UserGroupRepoGroupToPerm.query()\
3022 .filter(UserGroupRepoGroupToPerm.group == self)
3022 .filter(UserGroupRepoGroupToPerm.group == self)
3023 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
3023 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
3024 joinedload(UserGroupRepoGroupToPerm.users_group),
3024 joinedload(UserGroupRepoGroupToPerm.users_group),
3025 joinedload(UserGroupRepoGroupToPerm.permission),)
3025 joinedload(UserGroupRepoGroupToPerm.permission),)
3026
3026
3027 perm_rows = []
3027 perm_rows = []
3028 for _user_group in q.all():
3028 for _user_group in q.all():
3029 entry = AttributeDict(_user_group.users_group.get_dict())
3029 entry = AttributeDict(_user_group.users_group.get_dict())
3030 entry.permission = _user_group.permission.permission_name
3030 entry.permission = _user_group.permission.permission_name
3031 if with_members:
3031 if with_members:
3032 entry.members = [x.user.get_dict()
3032 entry.members = [x.user.get_dict()
3033 for x in _user_group.users_group.members]
3033 for x in _user_group.users_group.members]
3034 perm_rows.append(entry)
3034 perm_rows.append(entry)
3035
3035
3036 perm_rows = sorted(perm_rows, key=display_user_group_sort)
3036 perm_rows = sorted(perm_rows, key=display_user_group_sort)
3037 return perm_rows
3037 return perm_rows
3038
3038
3039 def get_api_data(self):
3039 def get_api_data(self):
3040 """
3040 """
3041 Common function for generating api data
3041 Common function for generating api data
3042
3042
3043 """
3043 """
3044 group = self
3044 group = self
3045 data = {
3045 data = {
3046 'group_id': group.group_id,
3046 'group_id': group.group_id,
3047 'group_name': group.group_name,
3047 'group_name': group.group_name,
3048 'group_description': group.description_safe,
3048 'group_description': group.description_safe,
3049 'parent_group': group.parent_group.group_name if group.parent_group else None,
3049 'parent_group': group.parent_group.group_name if group.parent_group else None,
3050 'repositories': [x.repo_name for x in group.repositories],
3050 'repositories': [x.repo_name for x in group.repositories],
3051 'owner': group.user.username,
3051 'owner': group.user.username,
3052 }
3052 }
3053 return data
3053 return data
3054
3054
3055 def get_dict(self):
3055 def get_dict(self):
3056 # Since we transformed `group_name` to a hybrid property, we need to
3056 # Since we transformed `group_name` to a hybrid property, we need to
3057 # keep compatibility with the code which uses `group_name` field.
3057 # keep compatibility with the code which uses `group_name` field.
3058 result = super(RepoGroup, self).get_dict()
3058 result = super(RepoGroup, self).get_dict()
3059 result['group_name'] = result.pop('_group_name', None)
3059 result['group_name'] = result.pop('_group_name', None)
3060 return result
3060 return result
3061
3061
3062
3062
3063 class Permission(Base, BaseModel):
3063 class Permission(Base, BaseModel):
3064 __tablename__ = 'permissions'
3064 __tablename__ = 'permissions'
3065 __table_args__ = (
3065 __table_args__ = (
3066 Index('p_perm_name_idx', 'permission_name'),
3066 Index('p_perm_name_idx', 'permission_name'),
3067 base_table_args,
3067 base_table_args,
3068 )
3068 )
3069
3069
3070 PERMS = [
3070 PERMS = [
3071 ('hg.admin', _('RhodeCode Super Administrator')),
3071 ('hg.admin', _('RhodeCode Super Administrator')),
3072
3072
3073 ('repository.none', _('Repository no access')),
3073 ('repository.none', _('Repository no access')),
3074 ('repository.read', _('Repository read access')),
3074 ('repository.read', _('Repository read access')),
3075 ('repository.write', _('Repository write access')),
3075 ('repository.write', _('Repository write access')),
3076 ('repository.admin', _('Repository admin access')),
3076 ('repository.admin', _('Repository admin access')),
3077
3077
3078 ('group.none', _('Repository group no access')),
3078 ('group.none', _('Repository group no access')),
3079 ('group.read', _('Repository group read access')),
3079 ('group.read', _('Repository group read access')),
3080 ('group.write', _('Repository group write access')),
3080 ('group.write', _('Repository group write access')),
3081 ('group.admin', _('Repository group admin access')),
3081 ('group.admin', _('Repository group admin access')),
3082
3082
3083 ('usergroup.none', _('User group no access')),
3083 ('usergroup.none', _('User group no access')),
3084 ('usergroup.read', _('User group read access')),
3084 ('usergroup.read', _('User group read access')),
3085 ('usergroup.write', _('User group write access')),
3085 ('usergroup.write', _('User group write access')),
3086 ('usergroup.admin', _('User group admin access')),
3086 ('usergroup.admin', _('User group admin access')),
3087
3087
3088 ('branch.none', _('Branch no permissions')),
3088 ('branch.none', _('Branch no permissions')),
3089 ('branch.merge', _('Branch access by web merge')),
3089 ('branch.merge', _('Branch access by web merge')),
3090 ('branch.push', _('Branch access by push')),
3090 ('branch.push', _('Branch access by push')),
3091 ('branch.push_force', _('Branch access by push with force')),
3091 ('branch.push_force', _('Branch access by push with force')),
3092
3092
3093 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
3093 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
3094 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
3094 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
3095
3095
3096 ('hg.usergroup.create.false', _('User Group creation disabled')),
3096 ('hg.usergroup.create.false', _('User Group creation disabled')),
3097 ('hg.usergroup.create.true', _('User Group creation enabled')),
3097 ('hg.usergroup.create.true', _('User Group creation enabled')),
3098
3098
3099 ('hg.create.none', _('Repository creation disabled')),
3099 ('hg.create.none', _('Repository creation disabled')),
3100 ('hg.create.repository', _('Repository creation enabled')),
3100 ('hg.create.repository', _('Repository creation enabled')),
3101 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3101 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3102 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3102 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3103
3103
3104 ('hg.fork.none', _('Repository forking disabled')),
3104 ('hg.fork.none', _('Repository forking disabled')),
3105 ('hg.fork.repository', _('Repository forking enabled')),
3105 ('hg.fork.repository', _('Repository forking enabled')),
3106
3106
3107 ('hg.register.none', _('Registration disabled')),
3107 ('hg.register.none', _('Registration disabled')),
3108 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3108 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3109 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3109 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3110
3110
3111 ('hg.password_reset.enabled', _('Password reset enabled')),
3111 ('hg.password_reset.enabled', _('Password reset enabled')),
3112 ('hg.password_reset.hidden', _('Password reset hidden')),
3112 ('hg.password_reset.hidden', _('Password reset hidden')),
3113 ('hg.password_reset.disabled', _('Password reset disabled')),
3113 ('hg.password_reset.disabled', _('Password reset disabled')),
3114
3114
3115 ('hg.extern_activate.manual', _('Manual activation of external account')),
3115 ('hg.extern_activate.manual', _('Manual activation of external account')),
3116 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3116 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3117
3117
3118 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3118 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3119 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3119 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3120 ]
3120 ]
3121
3121
3122 # definition of system default permissions for DEFAULT user, created on
3122 # definition of system default permissions for DEFAULT user, created on
3123 # system setup
3123 # system setup
3124 DEFAULT_USER_PERMISSIONS = [
3124 DEFAULT_USER_PERMISSIONS = [
3125 # object perms
3125 # object perms
3126 'repository.read',
3126 'repository.read',
3127 'group.read',
3127 'group.read',
3128 'usergroup.read',
3128 'usergroup.read',
3129 # branch, for backward compat we need same value as before so forced pushed
3129 # branch, for backward compat we need same value as before so forced pushed
3130 'branch.push_force',
3130 'branch.push_force',
3131 # global
3131 # global
3132 'hg.create.repository',
3132 'hg.create.repository',
3133 'hg.repogroup.create.false',
3133 'hg.repogroup.create.false',
3134 'hg.usergroup.create.false',
3134 'hg.usergroup.create.false',
3135 'hg.create.write_on_repogroup.true',
3135 'hg.create.write_on_repogroup.true',
3136 'hg.fork.repository',
3136 'hg.fork.repository',
3137 'hg.register.manual_activate',
3137 'hg.register.manual_activate',
3138 'hg.password_reset.enabled',
3138 'hg.password_reset.enabled',
3139 'hg.extern_activate.auto',
3139 'hg.extern_activate.auto',
3140 'hg.inherit_default_perms.true',
3140 'hg.inherit_default_perms.true',
3141 ]
3141 ]
3142
3142
3143 # defines which permissions are more important higher the more important
3143 # defines which permissions are more important higher the more important
3144 # Weight defines which permissions are more important.
3144 # Weight defines which permissions are more important.
3145 # The higher number the more important.
3145 # The higher number the more important.
3146 PERM_WEIGHTS = {
3146 PERM_WEIGHTS = {
3147 'repository.none': 0,
3147 'repository.none': 0,
3148 'repository.read': 1,
3148 'repository.read': 1,
3149 'repository.write': 3,
3149 'repository.write': 3,
3150 'repository.admin': 4,
3150 'repository.admin': 4,
3151
3151
3152 'group.none': 0,
3152 'group.none': 0,
3153 'group.read': 1,
3153 'group.read': 1,
3154 'group.write': 3,
3154 'group.write': 3,
3155 'group.admin': 4,
3155 'group.admin': 4,
3156
3156
3157 'usergroup.none': 0,
3157 'usergroup.none': 0,
3158 'usergroup.read': 1,
3158 'usergroup.read': 1,
3159 'usergroup.write': 3,
3159 'usergroup.write': 3,
3160 'usergroup.admin': 4,
3160 'usergroup.admin': 4,
3161
3161
3162 'branch.none': 0,
3162 'branch.none': 0,
3163 'branch.merge': 1,
3163 'branch.merge': 1,
3164 'branch.push': 3,
3164 'branch.push': 3,
3165 'branch.push_force': 4,
3165 'branch.push_force': 4,
3166
3166
3167 'hg.repogroup.create.false': 0,
3167 'hg.repogroup.create.false': 0,
3168 'hg.repogroup.create.true': 1,
3168 'hg.repogroup.create.true': 1,
3169
3169
3170 'hg.usergroup.create.false': 0,
3170 'hg.usergroup.create.false': 0,
3171 'hg.usergroup.create.true': 1,
3171 'hg.usergroup.create.true': 1,
3172
3172
3173 'hg.fork.none': 0,
3173 'hg.fork.none': 0,
3174 'hg.fork.repository': 1,
3174 'hg.fork.repository': 1,
3175 'hg.create.none': 0,
3175 'hg.create.none': 0,
3176 'hg.create.repository': 1
3176 'hg.create.repository': 1
3177 }
3177 }
3178
3178
3179 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3179 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3180 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3180 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3181 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3181 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3182
3182
3183 def __unicode__(self):
3183 def __unicode__(self):
3184 return u"<%s('%s:%s')>" % (
3184 return u"<%s('%s:%s')>" % (
3185 self.__class__.__name__, self.permission_id, self.permission_name
3185 self.__class__.__name__, self.permission_id, self.permission_name
3186 )
3186 )
3187
3187
3188 @classmethod
3188 @classmethod
3189 def get_by_key(cls, key):
3189 def get_by_key(cls, key):
3190 return cls.query().filter(cls.permission_name == key).scalar()
3190 return cls.query().filter(cls.permission_name == key).scalar()
3191
3191
3192 @classmethod
3192 @classmethod
3193 def get_default_repo_perms(cls, user_id, repo_id=None):
3193 def get_default_repo_perms(cls, user_id, repo_id=None):
3194 q = Session().query(UserRepoToPerm, Repository, Permission)\
3194 q = Session().query(UserRepoToPerm, Repository, Permission)\
3195 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3195 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3196 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3196 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3197 .filter(UserRepoToPerm.user_id == user_id)
3197 .filter(UserRepoToPerm.user_id == user_id)
3198 if repo_id:
3198 if repo_id:
3199 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3199 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3200 return q.all()
3200 return q.all()
3201
3201
3202 @classmethod
3202 @classmethod
3203 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3203 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3204 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3204 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3205 .join(
3205 .join(
3206 Permission,
3206 Permission,
3207 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3207 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3208 .join(
3208 .join(
3209 UserRepoToPerm,
3209 UserRepoToPerm,
3210 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3210 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3211 .filter(UserRepoToPerm.user_id == user_id)
3211 .filter(UserRepoToPerm.user_id == user_id)
3212
3212
3213 if repo_id:
3213 if repo_id:
3214 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3214 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3215 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3215 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3216
3216
3217 @classmethod
3217 @classmethod
3218 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3218 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3219 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3219 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3220 .join(
3220 .join(
3221 Permission,
3221 Permission,
3222 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3222 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3223 .join(
3223 .join(
3224 Repository,
3224 Repository,
3225 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3225 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3226 .join(
3226 .join(
3227 UserGroup,
3227 UserGroup,
3228 UserGroupRepoToPerm.users_group_id ==
3228 UserGroupRepoToPerm.users_group_id ==
3229 UserGroup.users_group_id)\
3229 UserGroup.users_group_id)\
3230 .join(
3230 .join(
3231 UserGroupMember,
3231 UserGroupMember,
3232 UserGroupRepoToPerm.users_group_id ==
3232 UserGroupRepoToPerm.users_group_id ==
3233 UserGroupMember.users_group_id)\
3233 UserGroupMember.users_group_id)\
3234 .filter(
3234 .filter(
3235 UserGroupMember.user_id == user_id,
3235 UserGroupMember.user_id == user_id,
3236 UserGroup.users_group_active == true())
3236 UserGroup.users_group_active == true())
3237 if repo_id:
3237 if repo_id:
3238 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3238 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3239 return q.all()
3239 return q.all()
3240
3240
3241 @classmethod
3241 @classmethod
3242 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3242 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3243 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3243 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3244 .join(
3244 .join(
3245 Permission,
3245 Permission,
3246 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3246 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3247 .join(
3247 .join(
3248 UserGroupRepoToPerm,
3248 UserGroupRepoToPerm,
3249 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3249 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3250 .join(
3250 .join(
3251 UserGroup,
3251 UserGroup,
3252 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3252 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3253 .join(
3253 .join(
3254 UserGroupMember,
3254 UserGroupMember,
3255 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3255 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3256 .filter(
3256 .filter(
3257 UserGroupMember.user_id == user_id,
3257 UserGroupMember.user_id == user_id,
3258 UserGroup.users_group_active == true())
3258 UserGroup.users_group_active == true())
3259
3259
3260 if repo_id:
3260 if repo_id:
3261 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3261 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3262 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3262 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3263
3263
3264 @classmethod
3264 @classmethod
3265 def get_default_group_perms(cls, user_id, repo_group_id=None):
3265 def get_default_group_perms(cls, user_id, repo_group_id=None):
3266 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3266 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3267 .join(
3267 .join(
3268 Permission,
3268 Permission,
3269 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3269 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3270 .join(
3270 .join(
3271 RepoGroup,
3271 RepoGroup,
3272 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3272 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3273 .filter(UserRepoGroupToPerm.user_id == user_id)
3273 .filter(UserRepoGroupToPerm.user_id == user_id)
3274 if repo_group_id:
3274 if repo_group_id:
3275 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3275 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3276 return q.all()
3276 return q.all()
3277
3277
3278 @classmethod
3278 @classmethod
3279 def get_default_group_perms_from_user_group(
3279 def get_default_group_perms_from_user_group(
3280 cls, user_id, repo_group_id=None):
3280 cls, user_id, repo_group_id=None):
3281 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3281 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3282 .join(
3282 .join(
3283 Permission,
3283 Permission,
3284 UserGroupRepoGroupToPerm.permission_id ==
3284 UserGroupRepoGroupToPerm.permission_id ==
3285 Permission.permission_id)\
3285 Permission.permission_id)\
3286 .join(
3286 .join(
3287 RepoGroup,
3287 RepoGroup,
3288 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3288 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3289 .join(
3289 .join(
3290 UserGroup,
3290 UserGroup,
3291 UserGroupRepoGroupToPerm.users_group_id ==
3291 UserGroupRepoGroupToPerm.users_group_id ==
3292 UserGroup.users_group_id)\
3292 UserGroup.users_group_id)\
3293 .join(
3293 .join(
3294 UserGroupMember,
3294 UserGroupMember,
3295 UserGroupRepoGroupToPerm.users_group_id ==
3295 UserGroupRepoGroupToPerm.users_group_id ==
3296 UserGroupMember.users_group_id)\
3296 UserGroupMember.users_group_id)\
3297 .filter(
3297 .filter(
3298 UserGroupMember.user_id == user_id,
3298 UserGroupMember.user_id == user_id,
3299 UserGroup.users_group_active == true())
3299 UserGroup.users_group_active == true())
3300 if repo_group_id:
3300 if repo_group_id:
3301 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3301 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3302 return q.all()
3302 return q.all()
3303
3303
3304 @classmethod
3304 @classmethod
3305 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3305 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3306 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3306 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3307 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3307 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3308 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3308 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3309 .filter(UserUserGroupToPerm.user_id == user_id)
3309 .filter(UserUserGroupToPerm.user_id == user_id)
3310 if user_group_id:
3310 if user_group_id:
3311 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3311 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3312 return q.all()
3312 return q.all()
3313
3313
3314 @classmethod
3314 @classmethod
3315 def get_default_user_group_perms_from_user_group(
3315 def get_default_user_group_perms_from_user_group(
3316 cls, user_id, user_group_id=None):
3316 cls, user_id, user_group_id=None):
3317 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3317 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3318 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3318 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3319 .join(
3319 .join(
3320 Permission,
3320 Permission,
3321 UserGroupUserGroupToPerm.permission_id ==
3321 UserGroupUserGroupToPerm.permission_id ==
3322 Permission.permission_id)\
3322 Permission.permission_id)\
3323 .join(
3323 .join(
3324 TargetUserGroup,
3324 TargetUserGroup,
3325 UserGroupUserGroupToPerm.target_user_group_id ==
3325 UserGroupUserGroupToPerm.target_user_group_id ==
3326 TargetUserGroup.users_group_id)\
3326 TargetUserGroup.users_group_id)\
3327 .join(
3327 .join(
3328 UserGroup,
3328 UserGroup,
3329 UserGroupUserGroupToPerm.user_group_id ==
3329 UserGroupUserGroupToPerm.user_group_id ==
3330 UserGroup.users_group_id)\
3330 UserGroup.users_group_id)\
3331 .join(
3331 .join(
3332 UserGroupMember,
3332 UserGroupMember,
3333 UserGroupUserGroupToPerm.user_group_id ==
3333 UserGroupUserGroupToPerm.user_group_id ==
3334 UserGroupMember.users_group_id)\
3334 UserGroupMember.users_group_id)\
3335 .filter(
3335 .filter(
3336 UserGroupMember.user_id == user_id,
3336 UserGroupMember.user_id == user_id,
3337 UserGroup.users_group_active == true())
3337 UserGroup.users_group_active == true())
3338 if user_group_id:
3338 if user_group_id:
3339 q = q.filter(
3339 q = q.filter(
3340 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3340 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3341
3341
3342 return q.all()
3342 return q.all()
3343
3343
3344
3344
3345 class UserRepoToPerm(Base, BaseModel):
3345 class UserRepoToPerm(Base, BaseModel):
3346 __tablename__ = 'repo_to_perm'
3346 __tablename__ = 'repo_to_perm'
3347 __table_args__ = (
3347 __table_args__ = (
3348 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3348 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3349 base_table_args
3349 base_table_args
3350 )
3350 )
3351
3351
3352 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3352 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3353 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3353 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3354 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3354 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3355 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3355 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3356
3356
3357 user = relationship('User')
3357 user = relationship('User')
3358 repository = relationship('Repository')
3358 repository = relationship('Repository')
3359 permission = relationship('Permission')
3359 permission = relationship('Permission')
3360
3360
3361 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete-orphan", lazy='joined')
3361 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete-orphan", lazy='joined')
3362
3362
3363 @classmethod
3363 @classmethod
3364 def create(cls, user, repository, permission):
3364 def create(cls, user, repository, permission):
3365 n = cls()
3365 n = cls()
3366 n.user = user
3366 n.user = user
3367 n.repository = repository
3367 n.repository = repository
3368 n.permission = permission
3368 n.permission = permission
3369 Session().add(n)
3369 Session().add(n)
3370 return n
3370 return n
3371
3371
3372 def __unicode__(self):
3372 def __unicode__(self):
3373 return u'<%s => %s >' % (self.user, self.repository)
3373 return u'<%s => %s >' % (self.user, self.repository)
3374
3374
3375
3375
3376 class UserUserGroupToPerm(Base, BaseModel):
3376 class UserUserGroupToPerm(Base, BaseModel):
3377 __tablename__ = 'user_user_group_to_perm'
3377 __tablename__ = 'user_user_group_to_perm'
3378 __table_args__ = (
3378 __table_args__ = (
3379 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3379 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3380 base_table_args
3380 base_table_args
3381 )
3381 )
3382
3382
3383 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3383 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3384 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3384 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3385 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3385 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3386 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3386 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3387
3387
3388 user = relationship('User')
3388 user = relationship('User')
3389 user_group = relationship('UserGroup')
3389 user_group = relationship('UserGroup')
3390 permission = relationship('Permission')
3390 permission = relationship('Permission')
3391
3391
3392 @classmethod
3392 @classmethod
3393 def create(cls, user, user_group, permission):
3393 def create(cls, user, user_group, permission):
3394 n = cls()
3394 n = cls()
3395 n.user = user
3395 n.user = user
3396 n.user_group = user_group
3396 n.user_group = user_group
3397 n.permission = permission
3397 n.permission = permission
3398 Session().add(n)
3398 Session().add(n)
3399 return n
3399 return n
3400
3400
3401 def __unicode__(self):
3401 def __unicode__(self):
3402 return u'<%s => %s >' % (self.user, self.user_group)
3402 return u'<%s => %s >' % (self.user, self.user_group)
3403
3403
3404
3404
3405 class UserToPerm(Base, BaseModel):
3405 class UserToPerm(Base, BaseModel):
3406 __tablename__ = 'user_to_perm'
3406 __tablename__ = 'user_to_perm'
3407 __table_args__ = (
3407 __table_args__ = (
3408 UniqueConstraint('user_id', 'permission_id'),
3408 UniqueConstraint('user_id', 'permission_id'),
3409 base_table_args
3409 base_table_args
3410 )
3410 )
3411
3411
3412 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3412 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3413 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3413 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3414 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3414 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3415
3415
3416 user = relationship('User')
3416 user = relationship('User')
3417 permission = relationship('Permission', lazy='joined')
3417 permission = relationship('Permission', lazy='joined')
3418
3418
3419 def __unicode__(self):
3419 def __unicode__(self):
3420 return u'<%s => %s >' % (self.user, self.permission)
3420 return u'<%s => %s >' % (self.user, self.permission)
3421
3421
3422
3422
3423 class UserGroupRepoToPerm(Base, BaseModel):
3423 class UserGroupRepoToPerm(Base, BaseModel):
3424 __tablename__ = 'users_group_repo_to_perm'
3424 __tablename__ = 'users_group_repo_to_perm'
3425 __table_args__ = (
3425 __table_args__ = (
3426 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3426 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3427 base_table_args
3427 base_table_args
3428 )
3428 )
3429
3429
3430 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3430 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3431 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3431 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3432 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3432 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3433 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3433 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3434
3434
3435 users_group = relationship('UserGroup')
3435 users_group = relationship('UserGroup')
3436 permission = relationship('Permission')
3436 permission = relationship('Permission')
3437 repository = relationship('Repository')
3437 repository = relationship('Repository')
3438 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3438 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3439
3439
3440 @classmethod
3440 @classmethod
3441 def create(cls, users_group, repository, permission):
3441 def create(cls, users_group, repository, permission):
3442 n = cls()
3442 n = cls()
3443 n.users_group = users_group
3443 n.users_group = users_group
3444 n.repository = repository
3444 n.repository = repository
3445 n.permission = permission
3445 n.permission = permission
3446 Session().add(n)
3446 Session().add(n)
3447 return n
3447 return n
3448
3448
3449 def __unicode__(self):
3449 def __unicode__(self):
3450 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3450 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3451
3451
3452
3452
3453 class UserGroupUserGroupToPerm(Base, BaseModel):
3453 class UserGroupUserGroupToPerm(Base, BaseModel):
3454 __tablename__ = 'user_group_user_group_to_perm'
3454 __tablename__ = 'user_group_user_group_to_perm'
3455 __table_args__ = (
3455 __table_args__ = (
3456 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3456 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3457 CheckConstraint('target_user_group_id != user_group_id'),
3457 CheckConstraint('target_user_group_id != user_group_id'),
3458 base_table_args
3458 base_table_args
3459 )
3459 )
3460
3460
3461 user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3461 user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3462 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3462 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3463 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3463 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3464 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3464 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3465
3465
3466 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3466 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3467 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3467 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3468 permission = relationship('Permission')
3468 permission = relationship('Permission')
3469
3469
3470 @classmethod
3470 @classmethod
3471 def create(cls, target_user_group, user_group, permission):
3471 def create(cls, target_user_group, user_group, permission):
3472 n = cls()
3472 n = cls()
3473 n.target_user_group = target_user_group
3473 n.target_user_group = target_user_group
3474 n.user_group = user_group
3474 n.user_group = user_group
3475 n.permission = permission
3475 n.permission = permission
3476 Session().add(n)
3476 Session().add(n)
3477 return n
3477 return n
3478
3478
3479 def __unicode__(self):
3479 def __unicode__(self):
3480 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3480 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3481
3481
3482
3482
3483 class UserGroupToPerm(Base, BaseModel):
3483 class UserGroupToPerm(Base, BaseModel):
3484 __tablename__ = 'users_group_to_perm'
3484 __tablename__ = 'users_group_to_perm'
3485 __table_args__ = (
3485 __table_args__ = (
3486 UniqueConstraint('users_group_id', 'permission_id',),
3486 UniqueConstraint('users_group_id', 'permission_id',),
3487 base_table_args
3487 base_table_args
3488 )
3488 )
3489
3489
3490 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3490 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3491 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3491 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3492 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3492 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3493
3493
3494 users_group = relationship('UserGroup')
3494 users_group = relationship('UserGroup')
3495 permission = relationship('Permission')
3495 permission = relationship('Permission')
3496
3496
3497
3497
3498 class UserRepoGroupToPerm(Base, BaseModel):
3498 class UserRepoGroupToPerm(Base, BaseModel):
3499 __tablename__ = 'user_repo_group_to_perm'
3499 __tablename__ = 'user_repo_group_to_perm'
3500 __table_args__ = (
3500 __table_args__ = (
3501 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3501 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3502 base_table_args
3502 base_table_args
3503 )
3503 )
3504
3504
3505 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3505 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3506 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3506 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3507 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3507 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3508 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3508 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3509
3509
3510 user = relationship('User')
3510 user = relationship('User')
3511 group = relationship('RepoGroup')
3511 group = relationship('RepoGroup')
3512 permission = relationship('Permission')
3512 permission = relationship('Permission')
3513
3513
3514 @classmethod
3514 @classmethod
3515 def create(cls, user, repository_group, permission):
3515 def create(cls, user, repository_group, permission):
3516 n = cls()
3516 n = cls()
3517 n.user = user
3517 n.user = user
3518 n.group = repository_group
3518 n.group = repository_group
3519 n.permission = permission
3519 n.permission = permission
3520 Session().add(n)
3520 Session().add(n)
3521 return n
3521 return n
3522
3522
3523
3523
3524 class UserGroupRepoGroupToPerm(Base, BaseModel):
3524 class UserGroupRepoGroupToPerm(Base, BaseModel):
3525 __tablename__ = 'users_group_repo_group_to_perm'
3525 __tablename__ = 'users_group_repo_group_to_perm'
3526 __table_args__ = (
3526 __table_args__ = (
3527 UniqueConstraint('users_group_id', 'group_id'),
3527 UniqueConstraint('users_group_id', 'group_id'),
3528 base_table_args
3528 base_table_args
3529 )
3529 )
3530
3530
3531 users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3531 users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3532 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3532 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3533 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3533 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3534 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3534 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3535
3535
3536 users_group = relationship('UserGroup')
3536 users_group = relationship('UserGroup')
3537 permission = relationship('Permission')
3537 permission = relationship('Permission')
3538 group = relationship('RepoGroup')
3538 group = relationship('RepoGroup')
3539
3539
3540 @classmethod
3540 @classmethod
3541 def create(cls, user_group, repository_group, permission):
3541 def create(cls, user_group, repository_group, permission):
3542 n = cls()
3542 n = cls()
3543 n.users_group = user_group
3543 n.users_group = user_group
3544 n.group = repository_group
3544 n.group = repository_group
3545 n.permission = permission
3545 n.permission = permission
3546 Session().add(n)
3546 Session().add(n)
3547 return n
3547 return n
3548
3548
3549 def __unicode__(self):
3549 def __unicode__(self):
3550 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3550 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3551
3551
3552
3552
3553 class Statistics(Base, BaseModel):
3553 class Statistics(Base, BaseModel):
3554 __tablename__ = 'statistics'
3554 __tablename__ = 'statistics'
3555 __table_args__ = (
3555 __table_args__ = (
3556 base_table_args
3556 base_table_args
3557 )
3557 )
3558
3558
3559 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3559 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3560 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3560 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3561 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3561 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3562 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3562 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3563 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3563 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3564 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3564 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3565
3565
3566 repository = relationship('Repository', single_parent=True)
3566 repository = relationship('Repository', single_parent=True)
3567
3567
3568
3568
3569 class UserFollowing(Base, BaseModel):
3569 class UserFollowing(Base, BaseModel):
3570 __tablename__ = 'user_followings'
3570 __tablename__ = 'user_followings'
3571 __table_args__ = (
3571 __table_args__ = (
3572 UniqueConstraint('user_id', 'follows_repository_id'),
3572 UniqueConstraint('user_id', 'follows_repository_id'),
3573 UniqueConstraint('user_id', 'follows_user_id'),
3573 UniqueConstraint('user_id', 'follows_user_id'),
3574 base_table_args
3574 base_table_args
3575 )
3575 )
3576
3576
3577 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3577 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3578 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3578 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3579 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3579 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3580 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3580 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3581 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3581 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3582
3582
3583 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3583 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3584
3584
3585 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3585 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3586 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3586 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3587
3587
3588 @classmethod
3588 @classmethod
3589 def get_repo_followers(cls, repo_id):
3589 def get_repo_followers(cls, repo_id):
3590 return cls.query().filter(cls.follows_repo_id == repo_id)
3590 return cls.query().filter(cls.follows_repo_id == repo_id)
3591
3591
3592
3592
3593 class CacheKey(Base, BaseModel):
3593 class CacheKey(Base, BaseModel):
3594 __tablename__ = 'cache_invalidation'
3594 __tablename__ = 'cache_invalidation'
3595 __table_args__ = (
3595 __table_args__ = (
3596 UniqueConstraint('cache_key'),
3596 UniqueConstraint('cache_key'),
3597 Index('key_idx', 'cache_key'),
3597 Index('key_idx', 'cache_key'),
3598 base_table_args,
3598 base_table_args,
3599 )
3599 )
3600
3600
3601 CACHE_TYPE_FEED = 'FEED'
3601 CACHE_TYPE_FEED = 'FEED'
3602
3602
3603 # namespaces used to register process/thread aware caches
3603 # namespaces used to register process/thread aware caches
3604 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3604 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3605 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3605 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3606
3606
3607 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3607 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3608 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3608 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3609 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3609 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3610 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3610 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3611 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3611 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3612
3612
3613 def __init__(self, cache_key, cache_args='', cache_state_uid=None):
3613 def __init__(self, cache_key, cache_args='', cache_state_uid=None):
3614 self.cache_key = cache_key
3614 self.cache_key = cache_key
3615 self.cache_args = cache_args
3615 self.cache_args = cache_args
3616 self.cache_active = False
3616 self.cache_active = False
3617 # first key should be same for all entries, since all workers should share it
3617 # first key should be same for all entries, since all workers should share it
3618 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid()
3618 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid()
3619
3619
3620 def __unicode__(self):
3620 def __unicode__(self):
3621 return u"<%s('%s:%s[%s]')>" % (
3621 return u"<%s('%s:%s[%s]')>" % (
3622 self.__class__.__name__,
3622 self.__class__.__name__,
3623 self.cache_id, self.cache_key, self.cache_active)
3623 self.cache_id, self.cache_key, self.cache_active)
3624
3624
3625 def _cache_key_partition(self):
3625 def _cache_key_partition(self):
3626 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3626 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3627 return prefix, repo_name, suffix
3627 return prefix, repo_name, suffix
3628
3628
3629 def get_prefix(self):
3629 def get_prefix(self):
3630 """
3630 """
3631 Try to extract prefix from existing cache key. The key could consist
3631 Try to extract prefix from existing cache key. The key could consist
3632 of prefix, repo_name, suffix
3632 of prefix, repo_name, suffix
3633 """
3633 """
3634 # this returns prefix, repo_name, suffix
3634 # this returns prefix, repo_name, suffix
3635 return self._cache_key_partition()[0]
3635 return self._cache_key_partition()[0]
3636
3636
3637 def get_suffix(self):
3637 def get_suffix(self):
3638 """
3638 """
3639 get suffix that might have been used in _get_cache_key to
3639 get suffix that might have been used in _get_cache_key to
3640 generate self.cache_key. Only used for informational purposes
3640 generate self.cache_key. Only used for informational purposes
3641 in repo_edit.mako.
3641 in repo_edit.mako.
3642 """
3642 """
3643 # prefix, repo_name, suffix
3643 # prefix, repo_name, suffix
3644 return self._cache_key_partition()[2]
3644 return self._cache_key_partition()[2]
3645
3645
3646 @classmethod
3646 @classmethod
3647 def generate_new_state_uid(cls, based_on=None):
3647 def generate_new_state_uid(cls, based_on=None):
3648 if based_on:
3648 if based_on:
3649 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3649 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3650 else:
3650 else:
3651 return str(uuid.uuid4())
3651 return str(uuid.uuid4())
3652
3652
3653 @classmethod
3653 @classmethod
3654 def delete_all_cache(cls):
3654 def delete_all_cache(cls):
3655 """
3655 """
3656 Delete all cache keys from database.
3656 Delete all cache keys from database.
3657 Should only be run when all instances are down and all entries
3657 Should only be run when all instances are down and all entries
3658 thus stale.
3658 thus stale.
3659 """
3659 """
3660 cls.query().delete()
3660 cls.query().delete()
3661 Session().commit()
3661 Session().commit()
3662
3662
3663 @classmethod
3663 @classmethod
3664 def set_invalidate(cls, cache_uid, delete=False):
3664 def set_invalidate(cls, cache_uid, delete=False):
3665 """
3665 """
3666 Mark all caches of a repo as invalid in the database.
3666 Mark all caches of a repo as invalid in the database.
3667 """
3667 """
3668
3668
3669 try:
3669 try:
3670 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3670 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3671 if delete:
3671 if delete:
3672 qry.delete()
3672 qry.delete()
3673 log.debug('cache objects deleted for cache args %s',
3673 log.debug('cache objects deleted for cache args %s',
3674 safe_str(cache_uid))
3674 safe_str(cache_uid))
3675 else:
3675 else:
3676 qry.update({"cache_active": False,
3676 qry.update({"cache_active": False,
3677 "cache_state_uid": cls.generate_new_state_uid()})
3677 "cache_state_uid": cls.generate_new_state_uid()})
3678 log.debug('cache objects marked as invalid for cache args %s',
3678 log.debug('cache objects marked as invalid for cache args %s',
3679 safe_str(cache_uid))
3679 safe_str(cache_uid))
3680
3680
3681 Session().commit()
3681 Session().commit()
3682 except Exception:
3682 except Exception:
3683 log.exception(
3683 log.exception(
3684 'Cache key invalidation failed for cache args %s',
3684 'Cache key invalidation failed for cache args %s',
3685 safe_str(cache_uid))
3685 safe_str(cache_uid))
3686 Session().rollback()
3686 Session().rollback()
3687
3687
3688 @classmethod
3688 @classmethod
3689 def get_active_cache(cls, cache_key):
3689 def get_active_cache(cls, cache_key):
3690 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3690 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3691 if inv_obj:
3691 if inv_obj:
3692 return inv_obj
3692 return inv_obj
3693 return None
3693 return None
3694
3694
3695 @classmethod
3695 @classmethod
3696 def get_namespace_map(cls, namespace):
3696 def get_namespace_map(cls, namespace):
3697 return {
3697 return {
3698 x.cache_key: x
3698 x.cache_key: x
3699 for x in cls.query().filter(cls.cache_args == namespace)}
3699 for x in cls.query().filter(cls.cache_args == namespace)}
3700
3700
3701
3701
3702 class ChangesetComment(Base, BaseModel):
3702 class ChangesetComment(Base, BaseModel):
3703 __tablename__ = 'changeset_comments'
3703 __tablename__ = 'changeset_comments'
3704 __table_args__ = (
3704 __table_args__ = (
3705 Index('cc_revision_idx', 'revision'),
3705 Index('cc_revision_idx', 'revision'),
3706 base_table_args,
3706 base_table_args,
3707 )
3707 )
3708
3708
3709 COMMENT_OUTDATED = u'comment_outdated'
3709 COMMENT_OUTDATED = u'comment_outdated'
3710 COMMENT_TYPE_NOTE = u'note'
3710 COMMENT_TYPE_NOTE = u'note'
3711 COMMENT_TYPE_TODO = u'todo'
3711 COMMENT_TYPE_TODO = u'todo'
3712 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3712 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3713
3713
3714 OP_IMMUTABLE = u'immutable'
3715 OP_CHANGEABLE = u'changeable'
3716
3714 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3717 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3715 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3718 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3716 revision = Column('revision', String(40), nullable=True)
3719 revision = Column('revision', String(40), nullable=True)
3717 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3720 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3718 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3721 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3719 line_no = Column('line_no', Unicode(10), nullable=True)
3722 line_no = Column('line_no', Unicode(10), nullable=True)
3720 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3723 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3721 f_path = Column('f_path', Unicode(1000), nullable=True)
3724 f_path = Column('f_path', Unicode(1000), nullable=True)
3722 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3725 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3723 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3726 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3724 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3727 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3725 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3728 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3726 renderer = Column('renderer', Unicode(64), nullable=True)
3729 renderer = Column('renderer', Unicode(64), nullable=True)
3727 display_state = Column('display_state', Unicode(128), nullable=True)
3730 display_state = Column('display_state', Unicode(128), nullable=True)
3731 immutable_state = Column('immutable_state', Unicode(128), nullable=True, default=OP_CHANGEABLE)
3728
3732
3729 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3733 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3730 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3734 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3731
3735
3732 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3736 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3733 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3737 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3734
3738
3735 author = relationship('User', lazy='joined')
3739 author = relationship('User', lazy='joined')
3736 repo = relationship('Repository')
3740 repo = relationship('Repository')
3737 status_change = relationship('ChangesetStatus', cascade="all, delete-orphan", lazy='joined')
3741 status_change = relationship('ChangesetStatus', cascade="all, delete-orphan", lazy='joined')
3738 pull_request = relationship('PullRequest', lazy='joined')
3742 pull_request = relationship('PullRequest', lazy='joined')
3739 pull_request_version = relationship('PullRequestVersion')
3743 pull_request_version = relationship('PullRequestVersion')
3740
3744
3741 @classmethod
3745 @classmethod
3742 def get_users(cls, revision=None, pull_request_id=None):
3746 def get_users(cls, revision=None, pull_request_id=None):
3743 """
3747 """
3744 Returns user associated with this ChangesetComment. ie those
3748 Returns user associated with this ChangesetComment. ie those
3745 who actually commented
3749 who actually commented
3746
3750
3747 :param cls:
3751 :param cls:
3748 :param revision:
3752 :param revision:
3749 """
3753 """
3750 q = Session().query(User)\
3754 q = Session().query(User)\
3751 .join(ChangesetComment.author)
3755 .join(ChangesetComment.author)
3752 if revision:
3756 if revision:
3753 q = q.filter(cls.revision == revision)
3757 q = q.filter(cls.revision == revision)
3754 elif pull_request_id:
3758 elif pull_request_id:
3755 q = q.filter(cls.pull_request_id == pull_request_id)
3759 q = q.filter(cls.pull_request_id == pull_request_id)
3756 return q.all()
3760 return q.all()
3757
3761
3758 @classmethod
3762 @classmethod
3759 def get_index_from_version(cls, pr_version, versions):
3763 def get_index_from_version(cls, pr_version, versions):
3760 num_versions = [x.pull_request_version_id for x in versions]
3764 num_versions = [x.pull_request_version_id for x in versions]
3761 try:
3765 try:
3762 return num_versions.index(pr_version) +1
3766 return num_versions.index(pr_version) +1
3763 except (IndexError, ValueError):
3767 except (IndexError, ValueError):
3764 return
3768 return
3765
3769
3766 @property
3770 @property
3767 def outdated(self):
3771 def outdated(self):
3768 return self.display_state == self.COMMENT_OUTDATED
3772 return self.display_state == self.COMMENT_OUTDATED
3769
3773
3774 @property
3775 def immutable(self):
3776 return self.immutable_state == self.OP_IMMUTABLE
3777
3770 def outdated_at_version(self, version):
3778 def outdated_at_version(self, version):
3771 """
3779 """
3772 Checks if comment is outdated for given pull request version
3780 Checks if comment is outdated for given pull request version
3773 """
3781 """
3774 return self.outdated and self.pull_request_version_id != version
3782 return self.outdated and self.pull_request_version_id != version
3775
3783
3776 def older_than_version(self, version):
3784 def older_than_version(self, version):
3777 """
3785 """
3778 Checks if comment is made from previous version than given
3786 Checks if comment is made from previous version than given
3779 """
3787 """
3780 if version is None:
3788 if version is None:
3781 return self.pull_request_version_id is not None
3789 return self.pull_request_version_id is not None
3782
3790
3783 return self.pull_request_version_id < version
3791 return self.pull_request_version_id < version
3784
3792
3785 @property
3793 @property
3786 def resolved(self):
3794 def resolved(self):
3787 return self.resolved_by[0] if self.resolved_by else None
3795 return self.resolved_by[0] if self.resolved_by else None
3788
3796
3789 @property
3797 @property
3790 def is_todo(self):
3798 def is_todo(self):
3791 return self.comment_type == self.COMMENT_TYPE_TODO
3799 return self.comment_type == self.COMMENT_TYPE_TODO
3792
3800
3793 @property
3801 @property
3794 def is_inline(self):
3802 def is_inline(self):
3795 return self.line_no and self.f_path
3803 return self.line_no and self.f_path
3796
3804
3797 def get_index_version(self, versions):
3805 def get_index_version(self, versions):
3798 return self.get_index_from_version(
3806 return self.get_index_from_version(
3799 self.pull_request_version_id, versions)
3807 self.pull_request_version_id, versions)
3800
3808
3801 def __repr__(self):
3809 def __repr__(self):
3802 if self.comment_id:
3810 if self.comment_id:
3803 return '<DB:Comment #%s>' % self.comment_id
3811 return '<DB:Comment #%s>' % self.comment_id
3804 else:
3812 else:
3805 return '<DB:Comment at %#x>' % id(self)
3813 return '<DB:Comment at %#x>' % id(self)
3806
3814
3807 def get_api_data(self):
3815 def get_api_data(self):
3808 comment = self
3816 comment = self
3809 data = {
3817 data = {
3810 'comment_id': comment.comment_id,
3818 'comment_id': comment.comment_id,
3811 'comment_type': comment.comment_type,
3819 'comment_type': comment.comment_type,
3812 'comment_text': comment.text,
3820 'comment_text': comment.text,
3813 'comment_status': comment.status_change,
3821 'comment_status': comment.status_change,
3814 'comment_f_path': comment.f_path,
3822 'comment_f_path': comment.f_path,
3815 'comment_lineno': comment.line_no,
3823 'comment_lineno': comment.line_no,
3816 'comment_author': comment.author,
3824 'comment_author': comment.author,
3817 'comment_created_on': comment.created_on,
3825 'comment_created_on': comment.created_on,
3818 'comment_resolved_by': self.resolved,
3826 'comment_resolved_by': self.resolved,
3819 'comment_commit_id': comment.revision,
3827 'comment_commit_id': comment.revision,
3820 'comment_pull_request_id': comment.pull_request_id,
3828 'comment_pull_request_id': comment.pull_request_id,
3821 }
3829 }
3822 return data
3830 return data
3823
3831
3824 def __json__(self):
3832 def __json__(self):
3825 data = dict()
3833 data = dict()
3826 data.update(self.get_api_data())
3834 data.update(self.get_api_data())
3827 return data
3835 return data
3828
3836
3829
3837
3830 class ChangesetStatus(Base, BaseModel):
3838 class ChangesetStatus(Base, BaseModel):
3831 __tablename__ = 'changeset_statuses'
3839 __tablename__ = 'changeset_statuses'
3832 __table_args__ = (
3840 __table_args__ = (
3833 Index('cs_revision_idx', 'revision'),
3841 Index('cs_revision_idx', 'revision'),
3834 Index('cs_version_idx', 'version'),
3842 Index('cs_version_idx', 'version'),
3835 UniqueConstraint('repo_id', 'revision', 'version'),
3843 UniqueConstraint('repo_id', 'revision', 'version'),
3836 base_table_args
3844 base_table_args
3837 )
3845 )
3838
3846
3839 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3847 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3840 STATUS_APPROVED = 'approved'
3848 STATUS_APPROVED = 'approved'
3841 STATUS_REJECTED = 'rejected'
3849 STATUS_REJECTED = 'rejected'
3842 STATUS_UNDER_REVIEW = 'under_review'
3850 STATUS_UNDER_REVIEW = 'under_review'
3843
3851
3844 STATUSES = [
3852 STATUSES = [
3845 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3853 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3846 (STATUS_APPROVED, _("Approved")),
3854 (STATUS_APPROVED, _("Approved")),
3847 (STATUS_REJECTED, _("Rejected")),
3855 (STATUS_REJECTED, _("Rejected")),
3848 (STATUS_UNDER_REVIEW, _("Under Review")),
3856 (STATUS_UNDER_REVIEW, _("Under Review")),
3849 ]
3857 ]
3850
3858
3851 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3859 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3852 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3860 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3853 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3861 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3854 revision = Column('revision', String(40), nullable=False)
3862 revision = Column('revision', String(40), nullable=False)
3855 status = Column('status', String(128), nullable=False, default=DEFAULT)
3863 status = Column('status', String(128), nullable=False, default=DEFAULT)
3856 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3864 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3857 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3865 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3858 version = Column('version', Integer(), nullable=False, default=0)
3866 version = Column('version', Integer(), nullable=False, default=0)
3859 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3867 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3860
3868
3861 author = relationship('User', lazy='joined')
3869 author = relationship('User', lazy='joined')
3862 repo = relationship('Repository')
3870 repo = relationship('Repository')
3863 comment = relationship('ChangesetComment', lazy='joined')
3871 comment = relationship('ChangesetComment', lazy='joined')
3864 pull_request = relationship('PullRequest', lazy='joined')
3872 pull_request = relationship('PullRequest', lazy='joined')
3865
3873
3866 def __unicode__(self):
3874 def __unicode__(self):
3867 return u"<%s('%s[v%s]:%s')>" % (
3875 return u"<%s('%s[v%s]:%s')>" % (
3868 self.__class__.__name__,
3876 self.__class__.__name__,
3869 self.status, self.version, self.author
3877 self.status, self.version, self.author
3870 )
3878 )
3871
3879
3872 @classmethod
3880 @classmethod
3873 def get_status_lbl(cls, value):
3881 def get_status_lbl(cls, value):
3874 return dict(cls.STATUSES).get(value)
3882 return dict(cls.STATUSES).get(value)
3875
3883
3876 @property
3884 @property
3877 def status_lbl(self):
3885 def status_lbl(self):
3878 return ChangesetStatus.get_status_lbl(self.status)
3886 return ChangesetStatus.get_status_lbl(self.status)
3879
3887
3880 def get_api_data(self):
3888 def get_api_data(self):
3881 status = self
3889 status = self
3882 data = {
3890 data = {
3883 'status_id': status.changeset_status_id,
3891 'status_id': status.changeset_status_id,
3884 'status': status.status,
3892 'status': status.status,
3885 }
3893 }
3886 return data
3894 return data
3887
3895
3888 def __json__(self):
3896 def __json__(self):
3889 data = dict()
3897 data = dict()
3890 data.update(self.get_api_data())
3898 data.update(self.get_api_data())
3891 return data
3899 return data
3892
3900
3893
3901
3894 class _SetState(object):
3902 class _SetState(object):
3895 """
3903 """
3896 Context processor allowing changing state for sensitive operation such as
3904 Context processor allowing changing state for sensitive operation such as
3897 pull request update or merge
3905 pull request update or merge
3898 """
3906 """
3899
3907
3900 def __init__(self, pull_request, pr_state, back_state=None):
3908 def __init__(self, pull_request, pr_state, back_state=None):
3901 self._pr = pull_request
3909 self._pr = pull_request
3902 self._org_state = back_state or pull_request.pull_request_state
3910 self._org_state = back_state or pull_request.pull_request_state
3903 self._pr_state = pr_state
3911 self._pr_state = pr_state
3904 self._current_state = None
3912 self._current_state = None
3905
3913
3906 def __enter__(self):
3914 def __enter__(self):
3907 log.debug('StateLock: entering set state context of pr %s, setting state to: `%s`',
3915 log.debug('StateLock: entering set state context of pr %s, setting state to: `%s`',
3908 self._pr, self._pr_state)
3916 self._pr, self._pr_state)
3909 self.set_pr_state(self._pr_state)
3917 self.set_pr_state(self._pr_state)
3910 return self
3918 return self
3911
3919
3912 def __exit__(self, exc_type, exc_val, exc_tb):
3920 def __exit__(self, exc_type, exc_val, exc_tb):
3913 if exc_val is not None:
3921 if exc_val is not None:
3914 log.error(traceback.format_exc(exc_tb))
3922 log.error(traceback.format_exc(exc_tb))
3915 return None
3923 return None
3916
3924
3917 self.set_pr_state(self._org_state)
3925 self.set_pr_state(self._org_state)
3918 log.debug('StateLock: exiting set state context of pr %s, setting state to: `%s`',
3926 log.debug('StateLock: exiting set state context of pr %s, setting state to: `%s`',
3919 self._pr, self._org_state)
3927 self._pr, self._org_state)
3920
3928
3921 @property
3929 @property
3922 def state(self):
3930 def state(self):
3923 return self._current_state
3931 return self._current_state
3924
3932
3925 def set_pr_state(self, pr_state):
3933 def set_pr_state(self, pr_state):
3926 try:
3934 try:
3927 self._pr.pull_request_state = pr_state
3935 self._pr.pull_request_state = pr_state
3928 Session().add(self._pr)
3936 Session().add(self._pr)
3929 Session().commit()
3937 Session().commit()
3930 self._current_state = pr_state
3938 self._current_state = pr_state
3931 except Exception:
3939 except Exception:
3932 log.exception('Failed to set PullRequest %s state to %s', self._pr, pr_state)
3940 log.exception('Failed to set PullRequest %s state to %s', self._pr, pr_state)
3933 raise
3941 raise
3934
3942
3935
3943
3936 class _PullRequestBase(BaseModel):
3944 class _PullRequestBase(BaseModel):
3937 """
3945 """
3938 Common attributes of pull request and version entries.
3946 Common attributes of pull request and version entries.
3939 """
3947 """
3940
3948
3941 # .status values
3949 # .status values
3942 STATUS_NEW = u'new'
3950 STATUS_NEW = u'new'
3943 STATUS_OPEN = u'open'
3951 STATUS_OPEN = u'open'
3944 STATUS_CLOSED = u'closed'
3952 STATUS_CLOSED = u'closed'
3945
3953
3946 # available states
3954 # available states
3947 STATE_CREATING = u'creating'
3955 STATE_CREATING = u'creating'
3948 STATE_UPDATING = u'updating'
3956 STATE_UPDATING = u'updating'
3949 STATE_MERGING = u'merging'
3957 STATE_MERGING = u'merging'
3950 STATE_CREATED = u'created'
3958 STATE_CREATED = u'created'
3951
3959
3952 title = Column('title', Unicode(255), nullable=True)
3960 title = Column('title', Unicode(255), nullable=True)
3953 description = Column(
3961 description = Column(
3954 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3962 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3955 nullable=True)
3963 nullable=True)
3956 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3964 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3957
3965
3958 # new/open/closed status of pull request (not approve/reject/etc)
3966 # new/open/closed status of pull request (not approve/reject/etc)
3959 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3967 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3960 created_on = Column(
3968 created_on = Column(
3961 'created_on', DateTime(timezone=False), nullable=False,
3969 'created_on', DateTime(timezone=False), nullable=False,
3962 default=datetime.datetime.now)
3970 default=datetime.datetime.now)
3963 updated_on = Column(
3971 updated_on = Column(
3964 'updated_on', DateTime(timezone=False), nullable=False,
3972 'updated_on', DateTime(timezone=False), nullable=False,
3965 default=datetime.datetime.now)
3973 default=datetime.datetime.now)
3966
3974
3967 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3975 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3968
3976
3969 @declared_attr
3977 @declared_attr
3970 def user_id(cls):
3978 def user_id(cls):
3971 return Column(
3979 return Column(
3972 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3980 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3973 unique=None)
3981 unique=None)
3974
3982
3975 # 500 revisions max
3983 # 500 revisions max
3976 _revisions = Column(
3984 _revisions = Column(
3977 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3985 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3978
3986
3979 @declared_attr
3987 @declared_attr
3980 def source_repo_id(cls):
3988 def source_repo_id(cls):
3981 # TODO: dan: rename column to source_repo_id
3989 # TODO: dan: rename column to source_repo_id
3982 return Column(
3990 return Column(
3983 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3991 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3984 nullable=False)
3992 nullable=False)
3985
3993
3986 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3994 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3987
3995
3988 @hybrid_property
3996 @hybrid_property
3989 def source_ref(self):
3997 def source_ref(self):
3990 return self._source_ref
3998 return self._source_ref
3991
3999
3992 @source_ref.setter
4000 @source_ref.setter
3993 def source_ref(self, val):
4001 def source_ref(self, val):
3994 parts = (val or '').split(':')
4002 parts = (val or '').split(':')
3995 if len(parts) != 3:
4003 if len(parts) != 3:
3996 raise ValueError(
4004 raise ValueError(
3997 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4005 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3998 self._source_ref = safe_unicode(val)
4006 self._source_ref = safe_unicode(val)
3999
4007
4000 _target_ref = Column('other_ref', Unicode(255), nullable=False)
4008 _target_ref = Column('other_ref', Unicode(255), nullable=False)
4001
4009
4002 @hybrid_property
4010 @hybrid_property
4003 def target_ref(self):
4011 def target_ref(self):
4004 return self._target_ref
4012 return self._target_ref
4005
4013
4006 @target_ref.setter
4014 @target_ref.setter
4007 def target_ref(self, val):
4015 def target_ref(self, val):
4008 parts = (val or '').split(':')
4016 parts = (val or '').split(':')
4009 if len(parts) != 3:
4017 if len(parts) != 3:
4010 raise ValueError(
4018 raise ValueError(
4011 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4019 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4012 self._target_ref = safe_unicode(val)
4020 self._target_ref = safe_unicode(val)
4013
4021
4014 @declared_attr
4022 @declared_attr
4015 def target_repo_id(cls):
4023 def target_repo_id(cls):
4016 # TODO: dan: rename column to target_repo_id
4024 # TODO: dan: rename column to target_repo_id
4017 return Column(
4025 return Column(
4018 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4026 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4019 nullable=False)
4027 nullable=False)
4020
4028
4021 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
4029 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
4022
4030
4023 # TODO: dan: rename column to last_merge_source_rev
4031 # TODO: dan: rename column to last_merge_source_rev
4024 _last_merge_source_rev = Column(
4032 _last_merge_source_rev = Column(
4025 'last_merge_org_rev', String(40), nullable=True)
4033 'last_merge_org_rev', String(40), nullable=True)
4026 # TODO: dan: rename column to last_merge_target_rev
4034 # TODO: dan: rename column to last_merge_target_rev
4027 _last_merge_target_rev = Column(
4035 _last_merge_target_rev = Column(
4028 'last_merge_other_rev', String(40), nullable=True)
4036 'last_merge_other_rev', String(40), nullable=True)
4029 _last_merge_status = Column('merge_status', Integer(), nullable=True)
4037 _last_merge_status = Column('merge_status', Integer(), nullable=True)
4030 last_merge_metadata = Column(
4038 last_merge_metadata = Column(
4031 'last_merge_metadata', MutationObj.as_mutable(
4039 'last_merge_metadata', MutationObj.as_mutable(
4032 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4040 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4033
4041
4034 merge_rev = Column('merge_rev', String(40), nullable=True)
4042 merge_rev = Column('merge_rev', String(40), nullable=True)
4035
4043
4036 reviewer_data = Column(
4044 reviewer_data = Column(
4037 'reviewer_data_json', MutationObj.as_mutable(
4045 'reviewer_data_json', MutationObj.as_mutable(
4038 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4046 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4039
4047
4040 @property
4048 @property
4041 def reviewer_data_json(self):
4049 def reviewer_data_json(self):
4042 return json.dumps(self.reviewer_data)
4050 return json.dumps(self.reviewer_data)
4043
4051
4044 @property
4052 @property
4045 def work_in_progress(self):
4053 def work_in_progress(self):
4046 """checks if pull request is work in progress by checking the title"""
4054 """checks if pull request is work in progress by checking the title"""
4047 title = self.title.upper()
4055 title = self.title.upper()
4048 if re.match(r'^(\[WIP\]\s*|WIP:\s*|WIP\s+)', title):
4056 if re.match(r'^(\[WIP\]\s*|WIP:\s*|WIP\s+)', title):
4049 return True
4057 return True
4050 return False
4058 return False
4051
4059
4052 @hybrid_property
4060 @hybrid_property
4053 def description_safe(self):
4061 def description_safe(self):
4054 from rhodecode.lib import helpers as h
4062 from rhodecode.lib import helpers as h
4055 return h.escape(self.description)
4063 return h.escape(self.description)
4056
4064
4057 @hybrid_property
4065 @hybrid_property
4058 def revisions(self):
4066 def revisions(self):
4059 return self._revisions.split(':') if self._revisions else []
4067 return self._revisions.split(':') if self._revisions else []
4060
4068
4061 @revisions.setter
4069 @revisions.setter
4062 def revisions(self, val):
4070 def revisions(self, val):
4063 self._revisions = u':'.join(val)
4071 self._revisions = u':'.join(val)
4064
4072
4065 @hybrid_property
4073 @hybrid_property
4066 def last_merge_status(self):
4074 def last_merge_status(self):
4067 return safe_int(self._last_merge_status)
4075 return safe_int(self._last_merge_status)
4068
4076
4069 @last_merge_status.setter
4077 @last_merge_status.setter
4070 def last_merge_status(self, val):
4078 def last_merge_status(self, val):
4071 self._last_merge_status = val
4079 self._last_merge_status = val
4072
4080
4073 @declared_attr
4081 @declared_attr
4074 def author(cls):
4082 def author(cls):
4075 return relationship('User', lazy='joined')
4083 return relationship('User', lazy='joined')
4076
4084
4077 @declared_attr
4085 @declared_attr
4078 def source_repo(cls):
4086 def source_repo(cls):
4079 return relationship(
4087 return relationship(
4080 'Repository',
4088 'Repository',
4081 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
4089 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
4082
4090
4083 @property
4091 @property
4084 def source_ref_parts(self):
4092 def source_ref_parts(self):
4085 return self.unicode_to_reference(self.source_ref)
4093 return self.unicode_to_reference(self.source_ref)
4086
4094
4087 @declared_attr
4095 @declared_attr
4088 def target_repo(cls):
4096 def target_repo(cls):
4089 return relationship(
4097 return relationship(
4090 'Repository',
4098 'Repository',
4091 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
4099 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
4092
4100
4093 @property
4101 @property
4094 def target_ref_parts(self):
4102 def target_ref_parts(self):
4095 return self.unicode_to_reference(self.target_ref)
4103 return self.unicode_to_reference(self.target_ref)
4096
4104
4097 @property
4105 @property
4098 def shadow_merge_ref(self):
4106 def shadow_merge_ref(self):
4099 return self.unicode_to_reference(self._shadow_merge_ref)
4107 return self.unicode_to_reference(self._shadow_merge_ref)
4100
4108
4101 @shadow_merge_ref.setter
4109 @shadow_merge_ref.setter
4102 def shadow_merge_ref(self, ref):
4110 def shadow_merge_ref(self, ref):
4103 self._shadow_merge_ref = self.reference_to_unicode(ref)
4111 self._shadow_merge_ref = self.reference_to_unicode(ref)
4104
4112
4105 @staticmethod
4113 @staticmethod
4106 def unicode_to_reference(raw):
4114 def unicode_to_reference(raw):
4107 """
4115 """
4108 Convert a unicode (or string) to a reference object.
4116 Convert a unicode (or string) to a reference object.
4109 If unicode evaluates to False it returns None.
4117 If unicode evaluates to False it returns None.
4110 """
4118 """
4111 if raw:
4119 if raw:
4112 refs = raw.split(':')
4120 refs = raw.split(':')
4113 return Reference(*refs)
4121 return Reference(*refs)
4114 else:
4122 else:
4115 return None
4123 return None
4116
4124
4117 @staticmethod
4125 @staticmethod
4118 def reference_to_unicode(ref):
4126 def reference_to_unicode(ref):
4119 """
4127 """
4120 Convert a reference object to unicode.
4128 Convert a reference object to unicode.
4121 If reference is None it returns None.
4129 If reference is None it returns None.
4122 """
4130 """
4123 if ref:
4131 if ref:
4124 return u':'.join(ref)
4132 return u':'.join(ref)
4125 else:
4133 else:
4126 return None
4134 return None
4127
4135
4128 def get_api_data(self, with_merge_state=True):
4136 def get_api_data(self, with_merge_state=True):
4129 from rhodecode.model.pull_request import PullRequestModel
4137 from rhodecode.model.pull_request import PullRequestModel
4130
4138
4131 pull_request = self
4139 pull_request = self
4132 if with_merge_state:
4140 if with_merge_state:
4133 merge_response, merge_status, msg = \
4141 merge_response, merge_status, msg = \
4134 PullRequestModel().merge_status(pull_request)
4142 PullRequestModel().merge_status(pull_request)
4135 merge_state = {
4143 merge_state = {
4136 'status': merge_status,
4144 'status': merge_status,
4137 'message': safe_unicode(msg),
4145 'message': safe_unicode(msg),
4138 }
4146 }
4139 else:
4147 else:
4140 merge_state = {'status': 'not_available',
4148 merge_state = {'status': 'not_available',
4141 'message': 'not_available'}
4149 'message': 'not_available'}
4142
4150
4143 merge_data = {
4151 merge_data = {
4144 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4152 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4145 'reference': (
4153 'reference': (
4146 pull_request.shadow_merge_ref._asdict()
4154 pull_request.shadow_merge_ref._asdict()
4147 if pull_request.shadow_merge_ref else None),
4155 if pull_request.shadow_merge_ref else None),
4148 }
4156 }
4149
4157
4150 data = {
4158 data = {
4151 'pull_request_id': pull_request.pull_request_id,
4159 'pull_request_id': pull_request.pull_request_id,
4152 'url': PullRequestModel().get_url(pull_request),
4160 'url': PullRequestModel().get_url(pull_request),
4153 'title': pull_request.title,
4161 'title': pull_request.title,
4154 'description': pull_request.description,
4162 'description': pull_request.description,
4155 'status': pull_request.status,
4163 'status': pull_request.status,
4156 'state': pull_request.pull_request_state,
4164 'state': pull_request.pull_request_state,
4157 'created_on': pull_request.created_on,
4165 'created_on': pull_request.created_on,
4158 'updated_on': pull_request.updated_on,
4166 'updated_on': pull_request.updated_on,
4159 'commit_ids': pull_request.revisions,
4167 'commit_ids': pull_request.revisions,
4160 'review_status': pull_request.calculated_review_status(),
4168 'review_status': pull_request.calculated_review_status(),
4161 'mergeable': merge_state,
4169 'mergeable': merge_state,
4162 'source': {
4170 'source': {
4163 'clone_url': pull_request.source_repo.clone_url(),
4171 'clone_url': pull_request.source_repo.clone_url(),
4164 'repository': pull_request.source_repo.repo_name,
4172 'repository': pull_request.source_repo.repo_name,
4165 'reference': {
4173 'reference': {
4166 'name': pull_request.source_ref_parts.name,
4174 'name': pull_request.source_ref_parts.name,
4167 'type': pull_request.source_ref_parts.type,
4175 'type': pull_request.source_ref_parts.type,
4168 'commit_id': pull_request.source_ref_parts.commit_id,
4176 'commit_id': pull_request.source_ref_parts.commit_id,
4169 },
4177 },
4170 },
4178 },
4171 'target': {
4179 'target': {
4172 'clone_url': pull_request.target_repo.clone_url(),
4180 'clone_url': pull_request.target_repo.clone_url(),
4173 'repository': pull_request.target_repo.repo_name,
4181 'repository': pull_request.target_repo.repo_name,
4174 'reference': {
4182 'reference': {
4175 'name': pull_request.target_ref_parts.name,
4183 'name': pull_request.target_ref_parts.name,
4176 'type': pull_request.target_ref_parts.type,
4184 'type': pull_request.target_ref_parts.type,
4177 'commit_id': pull_request.target_ref_parts.commit_id,
4185 'commit_id': pull_request.target_ref_parts.commit_id,
4178 },
4186 },
4179 },
4187 },
4180 'merge': merge_data,
4188 'merge': merge_data,
4181 'author': pull_request.author.get_api_data(include_secrets=False,
4189 'author': pull_request.author.get_api_data(include_secrets=False,
4182 details='basic'),
4190 details='basic'),
4183 'reviewers': [
4191 'reviewers': [
4184 {
4192 {
4185 'user': reviewer.get_api_data(include_secrets=False,
4193 'user': reviewer.get_api_data(include_secrets=False,
4186 details='basic'),
4194 details='basic'),
4187 'reasons': reasons,
4195 'reasons': reasons,
4188 'review_status': st[0][1].status if st else 'not_reviewed',
4196 'review_status': st[0][1].status if st else 'not_reviewed',
4189 }
4197 }
4190 for obj, reviewer, reasons, mandatory, st in
4198 for obj, reviewer, reasons, mandatory, st in
4191 pull_request.reviewers_statuses()
4199 pull_request.reviewers_statuses()
4192 ]
4200 ]
4193 }
4201 }
4194
4202
4195 return data
4203 return data
4196
4204
4197 def set_state(self, pull_request_state, final_state=None):
4205 def set_state(self, pull_request_state, final_state=None):
4198 """
4206 """
4199 # goes from initial state to updating to initial state.
4207 # goes from initial state to updating to initial state.
4200 # initial state can be changed by specifying back_state=
4208 # initial state can be changed by specifying back_state=
4201 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4209 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4202 pull_request.merge()
4210 pull_request.merge()
4203
4211
4204 :param pull_request_state:
4212 :param pull_request_state:
4205 :param final_state:
4213 :param final_state:
4206
4214
4207 """
4215 """
4208
4216
4209 return _SetState(self, pull_request_state, back_state=final_state)
4217 return _SetState(self, pull_request_state, back_state=final_state)
4210
4218
4211
4219
4212 class PullRequest(Base, _PullRequestBase):
4220 class PullRequest(Base, _PullRequestBase):
4213 __tablename__ = 'pull_requests'
4221 __tablename__ = 'pull_requests'
4214 __table_args__ = (
4222 __table_args__ = (
4215 base_table_args,
4223 base_table_args,
4216 )
4224 )
4217
4225
4218 pull_request_id = Column(
4226 pull_request_id = Column(
4219 'pull_request_id', Integer(), nullable=False, primary_key=True)
4227 'pull_request_id', Integer(), nullable=False, primary_key=True)
4220
4228
4221 def __repr__(self):
4229 def __repr__(self):
4222 if self.pull_request_id:
4230 if self.pull_request_id:
4223 return '<DB:PullRequest #%s>' % self.pull_request_id
4231 return '<DB:PullRequest #%s>' % self.pull_request_id
4224 else:
4232 else:
4225 return '<DB:PullRequest at %#x>' % id(self)
4233 return '<DB:PullRequest at %#x>' % id(self)
4226
4234
4227 reviewers = relationship('PullRequestReviewers', cascade="all, delete-orphan")
4235 reviewers = relationship('PullRequestReviewers', cascade="all, delete-orphan")
4228 statuses = relationship('ChangesetStatus', cascade="all, delete-orphan")
4236 statuses = relationship('ChangesetStatus', cascade="all, delete-orphan")
4229 comments = relationship('ChangesetComment', cascade="all, delete-orphan")
4237 comments = relationship('ChangesetComment', cascade="all, delete-orphan")
4230 versions = relationship('PullRequestVersion', cascade="all, delete-orphan",
4238 versions = relationship('PullRequestVersion', cascade="all, delete-orphan",
4231 lazy='dynamic')
4239 lazy='dynamic')
4232
4240
4233 @classmethod
4241 @classmethod
4234 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4242 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4235 internal_methods=None):
4243 internal_methods=None):
4236
4244
4237 class PullRequestDisplay(object):
4245 class PullRequestDisplay(object):
4238 """
4246 """
4239 Special object wrapper for showing PullRequest data via Versions
4247 Special object wrapper for showing PullRequest data via Versions
4240 It mimics PR object as close as possible. This is read only object
4248 It mimics PR object as close as possible. This is read only object
4241 just for display
4249 just for display
4242 """
4250 """
4243
4251
4244 def __init__(self, attrs, internal=None):
4252 def __init__(self, attrs, internal=None):
4245 self.attrs = attrs
4253 self.attrs = attrs
4246 # internal have priority over the given ones via attrs
4254 # internal have priority over the given ones via attrs
4247 self.internal = internal or ['versions']
4255 self.internal = internal or ['versions']
4248
4256
4249 def __getattr__(self, item):
4257 def __getattr__(self, item):
4250 if item in self.internal:
4258 if item in self.internal:
4251 return getattr(self, item)
4259 return getattr(self, item)
4252 try:
4260 try:
4253 return self.attrs[item]
4261 return self.attrs[item]
4254 except KeyError:
4262 except KeyError:
4255 raise AttributeError(
4263 raise AttributeError(
4256 '%s object has no attribute %s' % (self, item))
4264 '%s object has no attribute %s' % (self, item))
4257
4265
4258 def __repr__(self):
4266 def __repr__(self):
4259 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
4267 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
4260
4268
4261 def versions(self):
4269 def versions(self):
4262 return pull_request_obj.versions.order_by(
4270 return pull_request_obj.versions.order_by(
4263 PullRequestVersion.pull_request_version_id).all()
4271 PullRequestVersion.pull_request_version_id).all()
4264
4272
4265 def is_closed(self):
4273 def is_closed(self):
4266 return pull_request_obj.is_closed()
4274 return pull_request_obj.is_closed()
4267
4275
4268 def is_state_changing(self):
4276 def is_state_changing(self):
4269 return pull_request_obj.is_state_changing()
4277 return pull_request_obj.is_state_changing()
4270
4278
4271 @property
4279 @property
4272 def pull_request_version_id(self):
4280 def pull_request_version_id(self):
4273 return getattr(pull_request_obj, 'pull_request_version_id', None)
4281 return getattr(pull_request_obj, 'pull_request_version_id', None)
4274
4282
4275 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4283 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4276
4284
4277 attrs.author = StrictAttributeDict(
4285 attrs.author = StrictAttributeDict(
4278 pull_request_obj.author.get_api_data())
4286 pull_request_obj.author.get_api_data())
4279 if pull_request_obj.target_repo:
4287 if pull_request_obj.target_repo:
4280 attrs.target_repo = StrictAttributeDict(
4288 attrs.target_repo = StrictAttributeDict(
4281 pull_request_obj.target_repo.get_api_data())
4289 pull_request_obj.target_repo.get_api_data())
4282 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4290 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4283
4291
4284 if pull_request_obj.source_repo:
4292 if pull_request_obj.source_repo:
4285 attrs.source_repo = StrictAttributeDict(
4293 attrs.source_repo = StrictAttributeDict(
4286 pull_request_obj.source_repo.get_api_data())
4294 pull_request_obj.source_repo.get_api_data())
4287 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4295 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4288
4296
4289 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4297 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4290 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4298 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4291 attrs.revisions = pull_request_obj.revisions
4299 attrs.revisions = pull_request_obj.revisions
4292
4300
4293 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4301 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4294 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4302 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4295 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4303 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4296
4304
4297 return PullRequestDisplay(attrs, internal=internal_methods)
4305 return PullRequestDisplay(attrs, internal=internal_methods)
4298
4306
4299 def is_closed(self):
4307 def is_closed(self):
4300 return self.status == self.STATUS_CLOSED
4308 return self.status == self.STATUS_CLOSED
4301
4309
4302 def is_state_changing(self):
4310 def is_state_changing(self):
4303 return self.pull_request_state != PullRequest.STATE_CREATED
4311 return self.pull_request_state != PullRequest.STATE_CREATED
4304
4312
4305 def __json__(self):
4313 def __json__(self):
4306 return {
4314 return {
4307 'revisions': self.revisions,
4315 'revisions': self.revisions,
4308 'versions': self.versions_count
4316 'versions': self.versions_count
4309 }
4317 }
4310
4318
4311 def calculated_review_status(self):
4319 def calculated_review_status(self):
4312 from rhodecode.model.changeset_status import ChangesetStatusModel
4320 from rhodecode.model.changeset_status import ChangesetStatusModel
4313 return ChangesetStatusModel().calculated_review_status(self)
4321 return ChangesetStatusModel().calculated_review_status(self)
4314
4322
4315 def reviewers_statuses(self):
4323 def reviewers_statuses(self):
4316 from rhodecode.model.changeset_status import ChangesetStatusModel
4324 from rhodecode.model.changeset_status import ChangesetStatusModel
4317 return ChangesetStatusModel().reviewers_statuses(self)
4325 return ChangesetStatusModel().reviewers_statuses(self)
4318
4326
4319 @property
4327 @property
4320 def workspace_id(self):
4328 def workspace_id(self):
4321 from rhodecode.model.pull_request import PullRequestModel
4329 from rhodecode.model.pull_request import PullRequestModel
4322 return PullRequestModel()._workspace_id(self)
4330 return PullRequestModel()._workspace_id(self)
4323
4331
4324 def get_shadow_repo(self):
4332 def get_shadow_repo(self):
4325 workspace_id = self.workspace_id
4333 workspace_id = self.workspace_id
4326 shadow_repository_path = self.target_repo.get_shadow_repository_path(workspace_id)
4334 shadow_repository_path = self.target_repo.get_shadow_repository_path(workspace_id)
4327 if os.path.isdir(shadow_repository_path):
4335 if os.path.isdir(shadow_repository_path):
4328 vcs_obj = self.target_repo.scm_instance()
4336 vcs_obj = self.target_repo.scm_instance()
4329 return vcs_obj.get_shadow_instance(shadow_repository_path)
4337 return vcs_obj.get_shadow_instance(shadow_repository_path)
4330
4338
4331 @property
4339 @property
4332 def versions_count(self):
4340 def versions_count(self):
4333 """
4341 """
4334 return number of versions this PR have, e.g a PR that once been
4342 return number of versions this PR have, e.g a PR that once been
4335 updated will have 2 versions
4343 updated will have 2 versions
4336 """
4344 """
4337 return self.versions.count() + 1
4345 return self.versions.count() + 1
4338
4346
4339
4347
4340 class PullRequestVersion(Base, _PullRequestBase):
4348 class PullRequestVersion(Base, _PullRequestBase):
4341 __tablename__ = 'pull_request_versions'
4349 __tablename__ = 'pull_request_versions'
4342 __table_args__ = (
4350 __table_args__ = (
4343 base_table_args,
4351 base_table_args,
4344 )
4352 )
4345
4353
4346 pull_request_version_id = Column(
4354 pull_request_version_id = Column(
4347 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
4355 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
4348 pull_request_id = Column(
4356 pull_request_id = Column(
4349 'pull_request_id', Integer(),
4357 'pull_request_id', Integer(),
4350 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4358 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4351 pull_request = relationship('PullRequest')
4359 pull_request = relationship('PullRequest')
4352
4360
4353 def __repr__(self):
4361 def __repr__(self):
4354 if self.pull_request_version_id:
4362 if self.pull_request_version_id:
4355 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
4363 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
4356 else:
4364 else:
4357 return '<DB:PullRequestVersion at %#x>' % id(self)
4365 return '<DB:PullRequestVersion at %#x>' % id(self)
4358
4366
4359 @property
4367 @property
4360 def reviewers(self):
4368 def reviewers(self):
4361 return self.pull_request.reviewers
4369 return self.pull_request.reviewers
4362
4370
4363 @property
4371 @property
4364 def versions(self):
4372 def versions(self):
4365 return self.pull_request.versions
4373 return self.pull_request.versions
4366
4374
4367 def is_closed(self):
4375 def is_closed(self):
4368 # calculate from original
4376 # calculate from original
4369 return self.pull_request.status == self.STATUS_CLOSED
4377 return self.pull_request.status == self.STATUS_CLOSED
4370
4378
4371 def is_state_changing(self):
4379 def is_state_changing(self):
4372 return self.pull_request.pull_request_state != PullRequest.STATE_CREATED
4380 return self.pull_request.pull_request_state != PullRequest.STATE_CREATED
4373
4381
4374 def calculated_review_status(self):
4382 def calculated_review_status(self):
4375 return self.pull_request.calculated_review_status()
4383 return self.pull_request.calculated_review_status()
4376
4384
4377 def reviewers_statuses(self):
4385 def reviewers_statuses(self):
4378 return self.pull_request.reviewers_statuses()
4386 return self.pull_request.reviewers_statuses()
4379
4387
4380
4388
4381 class PullRequestReviewers(Base, BaseModel):
4389 class PullRequestReviewers(Base, BaseModel):
4382 __tablename__ = 'pull_request_reviewers'
4390 __tablename__ = 'pull_request_reviewers'
4383 __table_args__ = (
4391 __table_args__ = (
4384 base_table_args,
4392 base_table_args,
4385 )
4393 )
4386
4394
4387 @hybrid_property
4395 @hybrid_property
4388 def reasons(self):
4396 def reasons(self):
4389 if not self._reasons:
4397 if not self._reasons:
4390 return []
4398 return []
4391 return self._reasons
4399 return self._reasons
4392
4400
4393 @reasons.setter
4401 @reasons.setter
4394 def reasons(self, val):
4402 def reasons(self, val):
4395 val = val or []
4403 val = val or []
4396 if any(not isinstance(x, compat.string_types) for x in val):
4404 if any(not isinstance(x, compat.string_types) for x in val):
4397 raise Exception('invalid reasons type, must be list of strings')
4405 raise Exception('invalid reasons type, must be list of strings')
4398 self._reasons = val
4406 self._reasons = val
4399
4407
4400 pull_requests_reviewers_id = Column(
4408 pull_requests_reviewers_id = Column(
4401 'pull_requests_reviewers_id', Integer(), nullable=False,
4409 'pull_requests_reviewers_id', Integer(), nullable=False,
4402 primary_key=True)
4410 primary_key=True)
4403 pull_request_id = Column(
4411 pull_request_id = Column(
4404 "pull_request_id", Integer(),
4412 "pull_request_id", Integer(),
4405 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4413 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4406 user_id = Column(
4414 user_id = Column(
4407 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4415 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4408 _reasons = Column(
4416 _reasons = Column(
4409 'reason', MutationList.as_mutable(
4417 'reason', MutationList.as_mutable(
4410 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4418 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4411
4419
4412 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4420 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4413 user = relationship('User')
4421 user = relationship('User')
4414 pull_request = relationship('PullRequest')
4422 pull_request = relationship('PullRequest')
4415
4423
4416 rule_data = Column(
4424 rule_data = Column(
4417 'rule_data_json',
4425 'rule_data_json',
4418 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4426 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4419
4427
4420 def rule_user_group_data(self):
4428 def rule_user_group_data(self):
4421 """
4429 """
4422 Returns the voting user group rule data for this reviewer
4430 Returns the voting user group rule data for this reviewer
4423 """
4431 """
4424
4432
4425 if self.rule_data and 'vote_rule' in self.rule_data:
4433 if self.rule_data and 'vote_rule' in self.rule_data:
4426 user_group_data = {}
4434 user_group_data = {}
4427 if 'rule_user_group_entry_id' in self.rule_data:
4435 if 'rule_user_group_entry_id' in self.rule_data:
4428 # means a group with voting rules !
4436 # means a group with voting rules !
4429 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4437 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4430 user_group_data['name'] = self.rule_data['rule_name']
4438 user_group_data['name'] = self.rule_data['rule_name']
4431 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4439 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4432
4440
4433 return user_group_data
4441 return user_group_data
4434
4442
4435 def __unicode__(self):
4443 def __unicode__(self):
4436 return u"<%s('id:%s')>" % (self.__class__.__name__,
4444 return u"<%s('id:%s')>" % (self.__class__.__name__,
4437 self.pull_requests_reviewers_id)
4445 self.pull_requests_reviewers_id)
4438
4446
4439
4447
4440 class Notification(Base, BaseModel):
4448 class Notification(Base, BaseModel):
4441 __tablename__ = 'notifications'
4449 __tablename__ = 'notifications'
4442 __table_args__ = (
4450 __table_args__ = (
4443 Index('notification_type_idx', 'type'),
4451 Index('notification_type_idx', 'type'),
4444 base_table_args,
4452 base_table_args,
4445 )
4453 )
4446
4454
4447 TYPE_CHANGESET_COMMENT = u'cs_comment'
4455 TYPE_CHANGESET_COMMENT = u'cs_comment'
4448 TYPE_MESSAGE = u'message'
4456 TYPE_MESSAGE = u'message'
4449 TYPE_MENTION = u'mention'
4457 TYPE_MENTION = u'mention'
4450 TYPE_REGISTRATION = u'registration'
4458 TYPE_REGISTRATION = u'registration'
4451 TYPE_PULL_REQUEST = u'pull_request'
4459 TYPE_PULL_REQUEST = u'pull_request'
4452 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4460 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4453 TYPE_PULL_REQUEST_UPDATE = u'pull_request_update'
4461 TYPE_PULL_REQUEST_UPDATE = u'pull_request_update'
4454
4462
4455 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4463 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4456 subject = Column('subject', Unicode(512), nullable=True)
4464 subject = Column('subject', Unicode(512), nullable=True)
4457 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4465 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4458 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4466 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4459 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4467 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4460 type_ = Column('type', Unicode(255))
4468 type_ = Column('type', Unicode(255))
4461
4469
4462 created_by_user = relationship('User')
4470 created_by_user = relationship('User')
4463 notifications_to_users = relationship('UserNotification', lazy='joined',
4471 notifications_to_users = relationship('UserNotification', lazy='joined',
4464 cascade="all, delete-orphan")
4472 cascade="all, delete-orphan")
4465
4473
4466 @property
4474 @property
4467 def recipients(self):
4475 def recipients(self):
4468 return [x.user for x in UserNotification.query()\
4476 return [x.user for x in UserNotification.query()\
4469 .filter(UserNotification.notification == self)\
4477 .filter(UserNotification.notification == self)\
4470 .order_by(UserNotification.user_id.asc()).all()]
4478 .order_by(UserNotification.user_id.asc()).all()]
4471
4479
4472 @classmethod
4480 @classmethod
4473 def create(cls, created_by, subject, body, recipients, type_=None):
4481 def create(cls, created_by, subject, body, recipients, type_=None):
4474 if type_ is None:
4482 if type_ is None:
4475 type_ = Notification.TYPE_MESSAGE
4483 type_ = Notification.TYPE_MESSAGE
4476
4484
4477 notification = cls()
4485 notification = cls()
4478 notification.created_by_user = created_by
4486 notification.created_by_user = created_by
4479 notification.subject = subject
4487 notification.subject = subject
4480 notification.body = body
4488 notification.body = body
4481 notification.type_ = type_
4489 notification.type_ = type_
4482 notification.created_on = datetime.datetime.now()
4490 notification.created_on = datetime.datetime.now()
4483
4491
4484 # For each recipient link the created notification to his account
4492 # For each recipient link the created notification to his account
4485 for u in recipients:
4493 for u in recipients:
4486 assoc = UserNotification()
4494 assoc = UserNotification()
4487 assoc.user_id = u.user_id
4495 assoc.user_id = u.user_id
4488 assoc.notification = notification
4496 assoc.notification = notification
4489
4497
4490 # if created_by is inside recipients mark his notification
4498 # if created_by is inside recipients mark his notification
4491 # as read
4499 # as read
4492 if u.user_id == created_by.user_id:
4500 if u.user_id == created_by.user_id:
4493 assoc.read = True
4501 assoc.read = True
4494 Session().add(assoc)
4502 Session().add(assoc)
4495
4503
4496 Session().add(notification)
4504 Session().add(notification)
4497
4505
4498 return notification
4506 return notification
4499
4507
4500
4508
4501 class UserNotification(Base, BaseModel):
4509 class UserNotification(Base, BaseModel):
4502 __tablename__ = 'user_to_notification'
4510 __tablename__ = 'user_to_notification'
4503 __table_args__ = (
4511 __table_args__ = (
4504 UniqueConstraint('user_id', 'notification_id'),
4512 UniqueConstraint('user_id', 'notification_id'),
4505 base_table_args
4513 base_table_args
4506 )
4514 )
4507
4515
4508 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4516 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4509 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4517 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4510 read = Column('read', Boolean, default=False)
4518 read = Column('read', Boolean, default=False)
4511 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4519 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4512
4520
4513 user = relationship('User', lazy="joined")
4521 user = relationship('User', lazy="joined")
4514 notification = relationship('Notification', lazy="joined",
4522 notification = relationship('Notification', lazy="joined",
4515 order_by=lambda: Notification.created_on.desc(),)
4523 order_by=lambda: Notification.created_on.desc(),)
4516
4524
4517 def mark_as_read(self):
4525 def mark_as_read(self):
4518 self.read = True
4526 self.read = True
4519 Session().add(self)
4527 Session().add(self)
4520
4528
4521
4529
4522 class UserNotice(Base, BaseModel):
4530 class UserNotice(Base, BaseModel):
4523 __tablename__ = 'user_notices'
4531 __tablename__ = 'user_notices'
4524 __table_args__ = (
4532 __table_args__ = (
4525 base_table_args
4533 base_table_args
4526 )
4534 )
4527
4535
4528 NOTIFICATION_TYPE_MESSAGE = 'message'
4536 NOTIFICATION_TYPE_MESSAGE = 'message'
4529 NOTIFICATION_TYPE_NOTICE = 'notice'
4537 NOTIFICATION_TYPE_NOTICE = 'notice'
4530
4538
4531 NOTIFICATION_LEVEL_INFO = 'info'
4539 NOTIFICATION_LEVEL_INFO = 'info'
4532 NOTIFICATION_LEVEL_WARNING = 'warning'
4540 NOTIFICATION_LEVEL_WARNING = 'warning'
4533 NOTIFICATION_LEVEL_ERROR = 'error'
4541 NOTIFICATION_LEVEL_ERROR = 'error'
4534
4542
4535 user_notice_id = Column('gist_id', Integer(), primary_key=True)
4543 user_notice_id = Column('gist_id', Integer(), primary_key=True)
4536
4544
4537 notice_subject = Column('notice_subject', Unicode(512), nullable=True)
4545 notice_subject = Column('notice_subject', Unicode(512), nullable=True)
4538 notice_body = Column('notice_body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4546 notice_body = Column('notice_body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4539
4547
4540 notice_read = Column('notice_read', Boolean, default=False)
4548 notice_read = Column('notice_read', Boolean, default=False)
4541
4549
4542 notification_level = Column('notification_level', String(1024), default=NOTIFICATION_LEVEL_INFO)
4550 notification_level = Column('notification_level', String(1024), default=NOTIFICATION_LEVEL_INFO)
4543 notification_type = Column('notification_type', String(1024), default=NOTIFICATION_TYPE_NOTICE)
4551 notification_type = Column('notification_type', String(1024), default=NOTIFICATION_TYPE_NOTICE)
4544
4552
4545 notice_created_by = Column('notice_created_by', Integer(), ForeignKey('users.user_id'), nullable=True)
4553 notice_created_by = Column('notice_created_by', Integer(), ForeignKey('users.user_id'), nullable=True)
4546 notice_created_on = Column('notice_created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4554 notice_created_on = Column('notice_created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4547
4555
4548 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'))
4556 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'))
4549 user = relationship('User', lazy="joined", primaryjoin='User.user_id==UserNotice.user_id')
4557 user = relationship('User', lazy="joined", primaryjoin='User.user_id==UserNotice.user_id')
4550
4558
4551 @classmethod
4559 @classmethod
4552 def create_for_user(cls, user, subject, body, notice_level=NOTIFICATION_LEVEL_INFO, allow_duplicate=False):
4560 def create_for_user(cls, user, subject, body, notice_level=NOTIFICATION_LEVEL_INFO, allow_duplicate=False):
4553
4561
4554 if notice_level not in [cls.NOTIFICATION_LEVEL_ERROR,
4562 if notice_level not in [cls.NOTIFICATION_LEVEL_ERROR,
4555 cls.NOTIFICATION_LEVEL_WARNING,
4563 cls.NOTIFICATION_LEVEL_WARNING,
4556 cls.NOTIFICATION_LEVEL_INFO]:
4564 cls.NOTIFICATION_LEVEL_INFO]:
4557 return
4565 return
4558
4566
4559 from rhodecode.model.user import UserModel
4567 from rhodecode.model.user import UserModel
4560 user = UserModel().get_user(user)
4568 user = UserModel().get_user(user)
4561
4569
4562 new_notice = UserNotice()
4570 new_notice = UserNotice()
4563 if not allow_duplicate:
4571 if not allow_duplicate:
4564 existing_msg = UserNotice().query() \
4572 existing_msg = UserNotice().query() \
4565 .filter(UserNotice.user == user) \
4573 .filter(UserNotice.user == user) \
4566 .filter(UserNotice.notice_body == body) \
4574 .filter(UserNotice.notice_body == body) \
4567 .filter(UserNotice.notice_read == false()) \
4575 .filter(UserNotice.notice_read == false()) \
4568 .scalar()
4576 .scalar()
4569 if existing_msg:
4577 if existing_msg:
4570 log.warning('Ignoring duplicate notice for user %s', user)
4578 log.warning('Ignoring duplicate notice for user %s', user)
4571 return
4579 return
4572
4580
4573 new_notice.user = user
4581 new_notice.user = user
4574 new_notice.notice_subject = subject
4582 new_notice.notice_subject = subject
4575 new_notice.notice_body = body
4583 new_notice.notice_body = body
4576 new_notice.notification_level = notice_level
4584 new_notice.notification_level = notice_level
4577 Session().add(new_notice)
4585 Session().add(new_notice)
4578 Session().commit()
4586 Session().commit()
4579
4587
4580
4588
4581 class Gist(Base, BaseModel):
4589 class Gist(Base, BaseModel):
4582 __tablename__ = 'gists'
4590 __tablename__ = 'gists'
4583 __table_args__ = (
4591 __table_args__ = (
4584 Index('g_gist_access_id_idx', 'gist_access_id'),
4592 Index('g_gist_access_id_idx', 'gist_access_id'),
4585 Index('g_created_on_idx', 'created_on'),
4593 Index('g_created_on_idx', 'created_on'),
4586 base_table_args
4594 base_table_args
4587 )
4595 )
4588
4596
4589 GIST_PUBLIC = u'public'
4597 GIST_PUBLIC = u'public'
4590 GIST_PRIVATE = u'private'
4598 GIST_PRIVATE = u'private'
4591 DEFAULT_FILENAME = u'gistfile1.txt'
4599 DEFAULT_FILENAME = u'gistfile1.txt'
4592
4600
4593 ACL_LEVEL_PUBLIC = u'acl_public'
4601 ACL_LEVEL_PUBLIC = u'acl_public'
4594 ACL_LEVEL_PRIVATE = u'acl_private'
4602 ACL_LEVEL_PRIVATE = u'acl_private'
4595
4603
4596 gist_id = Column('gist_id', Integer(), primary_key=True)
4604 gist_id = Column('gist_id', Integer(), primary_key=True)
4597 gist_access_id = Column('gist_access_id', Unicode(250))
4605 gist_access_id = Column('gist_access_id', Unicode(250))
4598 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4606 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4599 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4607 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4600 gist_expires = Column('gist_expires', Float(53), nullable=False)
4608 gist_expires = Column('gist_expires', Float(53), nullable=False)
4601 gist_type = Column('gist_type', Unicode(128), nullable=False)
4609 gist_type = Column('gist_type', Unicode(128), nullable=False)
4602 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4610 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4603 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4611 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4604 acl_level = Column('acl_level', Unicode(128), nullable=True)
4612 acl_level = Column('acl_level', Unicode(128), nullable=True)
4605
4613
4606 owner = relationship('User')
4614 owner = relationship('User')
4607
4615
4608 def __repr__(self):
4616 def __repr__(self):
4609 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4617 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4610
4618
4611 @hybrid_property
4619 @hybrid_property
4612 def description_safe(self):
4620 def description_safe(self):
4613 from rhodecode.lib import helpers as h
4621 from rhodecode.lib import helpers as h
4614 return h.escape(self.gist_description)
4622 return h.escape(self.gist_description)
4615
4623
4616 @classmethod
4624 @classmethod
4617 def get_or_404(cls, id_):
4625 def get_or_404(cls, id_):
4618 from pyramid.httpexceptions import HTTPNotFound
4626 from pyramid.httpexceptions import HTTPNotFound
4619
4627
4620 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4628 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4621 if not res:
4629 if not res:
4622 raise HTTPNotFound()
4630 raise HTTPNotFound()
4623 return res
4631 return res
4624
4632
4625 @classmethod
4633 @classmethod
4626 def get_by_access_id(cls, gist_access_id):
4634 def get_by_access_id(cls, gist_access_id):
4627 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4635 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4628
4636
4629 def gist_url(self):
4637 def gist_url(self):
4630 from rhodecode.model.gist import GistModel
4638 from rhodecode.model.gist import GistModel
4631 return GistModel().get_url(self)
4639 return GistModel().get_url(self)
4632
4640
4633 @classmethod
4641 @classmethod
4634 def base_path(cls):
4642 def base_path(cls):
4635 """
4643 """
4636 Returns base path when all gists are stored
4644 Returns base path when all gists are stored
4637
4645
4638 :param cls:
4646 :param cls:
4639 """
4647 """
4640 from rhodecode.model.gist import GIST_STORE_LOC
4648 from rhodecode.model.gist import GIST_STORE_LOC
4641 q = Session().query(RhodeCodeUi)\
4649 q = Session().query(RhodeCodeUi)\
4642 .filter(RhodeCodeUi.ui_key == URL_SEP)
4650 .filter(RhodeCodeUi.ui_key == URL_SEP)
4643 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4651 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4644 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4652 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4645
4653
4646 def get_api_data(self):
4654 def get_api_data(self):
4647 """
4655 """
4648 Common function for generating gist related data for API
4656 Common function for generating gist related data for API
4649 """
4657 """
4650 gist = self
4658 gist = self
4651 data = {
4659 data = {
4652 'gist_id': gist.gist_id,
4660 'gist_id': gist.gist_id,
4653 'type': gist.gist_type,
4661 'type': gist.gist_type,
4654 'access_id': gist.gist_access_id,
4662 'access_id': gist.gist_access_id,
4655 'description': gist.gist_description,
4663 'description': gist.gist_description,
4656 'url': gist.gist_url(),
4664 'url': gist.gist_url(),
4657 'expires': gist.gist_expires,
4665 'expires': gist.gist_expires,
4658 'created_on': gist.created_on,
4666 'created_on': gist.created_on,
4659 'modified_at': gist.modified_at,
4667 'modified_at': gist.modified_at,
4660 'content': None,
4668 'content': None,
4661 'acl_level': gist.acl_level,
4669 'acl_level': gist.acl_level,
4662 }
4670 }
4663 return data
4671 return data
4664
4672
4665 def __json__(self):
4673 def __json__(self):
4666 data = dict(
4674 data = dict(
4667 )
4675 )
4668 data.update(self.get_api_data())
4676 data.update(self.get_api_data())
4669 return data
4677 return data
4670 # SCM functions
4678 # SCM functions
4671
4679
4672 def scm_instance(self, **kwargs):
4680 def scm_instance(self, **kwargs):
4673 """
4681 """
4674 Get an instance of VCS Repository
4682 Get an instance of VCS Repository
4675
4683
4676 :param kwargs:
4684 :param kwargs:
4677 """
4685 """
4678 from rhodecode.model.gist import GistModel
4686 from rhodecode.model.gist import GistModel
4679 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4687 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4680 return get_vcs_instance(
4688 return get_vcs_instance(
4681 repo_path=safe_str(full_repo_path), create=False,
4689 repo_path=safe_str(full_repo_path), create=False,
4682 _vcs_alias=GistModel.vcs_backend)
4690 _vcs_alias=GistModel.vcs_backend)
4683
4691
4684
4692
4685 class ExternalIdentity(Base, BaseModel):
4693 class ExternalIdentity(Base, BaseModel):
4686 __tablename__ = 'external_identities'
4694 __tablename__ = 'external_identities'
4687 __table_args__ = (
4695 __table_args__ = (
4688 Index('local_user_id_idx', 'local_user_id'),
4696 Index('local_user_id_idx', 'local_user_id'),
4689 Index('external_id_idx', 'external_id'),
4697 Index('external_id_idx', 'external_id'),
4690 base_table_args
4698 base_table_args
4691 )
4699 )
4692
4700
4693 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4701 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4694 external_username = Column('external_username', Unicode(1024), default=u'')
4702 external_username = Column('external_username', Unicode(1024), default=u'')
4695 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4703 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4696 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4704 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4697 access_token = Column('access_token', String(1024), default=u'')
4705 access_token = Column('access_token', String(1024), default=u'')
4698 alt_token = Column('alt_token', String(1024), default=u'')
4706 alt_token = Column('alt_token', String(1024), default=u'')
4699 token_secret = Column('token_secret', String(1024), default=u'')
4707 token_secret = Column('token_secret', String(1024), default=u'')
4700
4708
4701 @classmethod
4709 @classmethod
4702 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4710 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4703 """
4711 """
4704 Returns ExternalIdentity instance based on search params
4712 Returns ExternalIdentity instance based on search params
4705
4713
4706 :param external_id:
4714 :param external_id:
4707 :param provider_name:
4715 :param provider_name:
4708 :return: ExternalIdentity
4716 :return: ExternalIdentity
4709 """
4717 """
4710 query = cls.query()
4718 query = cls.query()
4711 query = query.filter(cls.external_id == external_id)
4719 query = query.filter(cls.external_id == external_id)
4712 query = query.filter(cls.provider_name == provider_name)
4720 query = query.filter(cls.provider_name == provider_name)
4713 if local_user_id:
4721 if local_user_id:
4714 query = query.filter(cls.local_user_id == local_user_id)
4722 query = query.filter(cls.local_user_id == local_user_id)
4715 return query.first()
4723 return query.first()
4716
4724
4717 @classmethod
4725 @classmethod
4718 def user_by_external_id_and_provider(cls, external_id, provider_name):
4726 def user_by_external_id_and_provider(cls, external_id, provider_name):
4719 """
4727 """
4720 Returns User instance based on search params
4728 Returns User instance based on search params
4721
4729
4722 :param external_id:
4730 :param external_id:
4723 :param provider_name:
4731 :param provider_name:
4724 :return: User
4732 :return: User
4725 """
4733 """
4726 query = User.query()
4734 query = User.query()
4727 query = query.filter(cls.external_id == external_id)
4735 query = query.filter(cls.external_id == external_id)
4728 query = query.filter(cls.provider_name == provider_name)
4736 query = query.filter(cls.provider_name == provider_name)
4729 query = query.filter(User.user_id == cls.local_user_id)
4737 query = query.filter(User.user_id == cls.local_user_id)
4730 return query.first()
4738 return query.first()
4731
4739
4732 @classmethod
4740 @classmethod
4733 def by_local_user_id(cls, local_user_id):
4741 def by_local_user_id(cls, local_user_id):
4734 """
4742 """
4735 Returns all tokens for user
4743 Returns all tokens for user
4736
4744
4737 :param local_user_id:
4745 :param local_user_id:
4738 :return: ExternalIdentity
4746 :return: ExternalIdentity
4739 """
4747 """
4740 query = cls.query()
4748 query = cls.query()
4741 query = query.filter(cls.local_user_id == local_user_id)
4749 query = query.filter(cls.local_user_id == local_user_id)
4742 return query
4750 return query
4743
4751
4744 @classmethod
4752 @classmethod
4745 def load_provider_plugin(cls, plugin_id):
4753 def load_provider_plugin(cls, plugin_id):
4746 from rhodecode.authentication.base import loadplugin
4754 from rhodecode.authentication.base import loadplugin
4747 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4755 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4748 auth_plugin = loadplugin(_plugin_id)
4756 auth_plugin = loadplugin(_plugin_id)
4749 return auth_plugin
4757 return auth_plugin
4750
4758
4751
4759
4752 class Integration(Base, BaseModel):
4760 class Integration(Base, BaseModel):
4753 __tablename__ = 'integrations'
4761 __tablename__ = 'integrations'
4754 __table_args__ = (
4762 __table_args__ = (
4755 base_table_args
4763 base_table_args
4756 )
4764 )
4757
4765
4758 integration_id = Column('integration_id', Integer(), primary_key=True)
4766 integration_id = Column('integration_id', Integer(), primary_key=True)
4759 integration_type = Column('integration_type', String(255))
4767 integration_type = Column('integration_type', String(255))
4760 enabled = Column('enabled', Boolean(), nullable=False)
4768 enabled = Column('enabled', Boolean(), nullable=False)
4761 name = Column('name', String(255), nullable=False)
4769 name = Column('name', String(255), nullable=False)
4762 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4770 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4763 default=False)
4771 default=False)
4764
4772
4765 settings = Column(
4773 settings = Column(
4766 'settings_json', MutationObj.as_mutable(
4774 'settings_json', MutationObj.as_mutable(
4767 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4775 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4768 repo_id = Column(
4776 repo_id = Column(
4769 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4777 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4770 nullable=True, unique=None, default=None)
4778 nullable=True, unique=None, default=None)
4771 repo = relationship('Repository', lazy='joined')
4779 repo = relationship('Repository', lazy='joined')
4772
4780
4773 repo_group_id = Column(
4781 repo_group_id = Column(
4774 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4782 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4775 nullable=True, unique=None, default=None)
4783 nullable=True, unique=None, default=None)
4776 repo_group = relationship('RepoGroup', lazy='joined')
4784 repo_group = relationship('RepoGroup', lazy='joined')
4777
4785
4778 @property
4786 @property
4779 def scope(self):
4787 def scope(self):
4780 if self.repo:
4788 if self.repo:
4781 return repr(self.repo)
4789 return repr(self.repo)
4782 if self.repo_group:
4790 if self.repo_group:
4783 if self.child_repos_only:
4791 if self.child_repos_only:
4784 return repr(self.repo_group) + ' (child repos only)'
4792 return repr(self.repo_group) + ' (child repos only)'
4785 else:
4793 else:
4786 return repr(self.repo_group) + ' (recursive)'
4794 return repr(self.repo_group) + ' (recursive)'
4787 if self.child_repos_only:
4795 if self.child_repos_only:
4788 return 'root_repos'
4796 return 'root_repos'
4789 return 'global'
4797 return 'global'
4790
4798
4791 def __repr__(self):
4799 def __repr__(self):
4792 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4800 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4793
4801
4794
4802
4795 class RepoReviewRuleUser(Base, BaseModel):
4803 class RepoReviewRuleUser(Base, BaseModel):
4796 __tablename__ = 'repo_review_rules_users'
4804 __tablename__ = 'repo_review_rules_users'
4797 __table_args__ = (
4805 __table_args__ = (
4798 base_table_args
4806 base_table_args
4799 )
4807 )
4800
4808
4801 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4809 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4802 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4810 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4803 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4811 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4804 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4812 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4805 user = relationship('User')
4813 user = relationship('User')
4806
4814
4807 def rule_data(self):
4815 def rule_data(self):
4808 return {
4816 return {
4809 'mandatory': self.mandatory
4817 'mandatory': self.mandatory
4810 }
4818 }
4811
4819
4812
4820
4813 class RepoReviewRuleUserGroup(Base, BaseModel):
4821 class RepoReviewRuleUserGroup(Base, BaseModel):
4814 __tablename__ = 'repo_review_rules_users_groups'
4822 __tablename__ = 'repo_review_rules_users_groups'
4815 __table_args__ = (
4823 __table_args__ = (
4816 base_table_args
4824 base_table_args
4817 )
4825 )
4818
4826
4819 VOTE_RULE_ALL = -1
4827 VOTE_RULE_ALL = -1
4820
4828
4821 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4829 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4822 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4830 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4823 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4831 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4824 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4832 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4825 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4833 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4826 users_group = relationship('UserGroup')
4834 users_group = relationship('UserGroup')
4827
4835
4828 def rule_data(self):
4836 def rule_data(self):
4829 return {
4837 return {
4830 'mandatory': self.mandatory,
4838 'mandatory': self.mandatory,
4831 'vote_rule': self.vote_rule
4839 'vote_rule': self.vote_rule
4832 }
4840 }
4833
4841
4834 @property
4842 @property
4835 def vote_rule_label(self):
4843 def vote_rule_label(self):
4836 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4844 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4837 return 'all must vote'
4845 return 'all must vote'
4838 else:
4846 else:
4839 return 'min. vote {}'.format(self.vote_rule)
4847 return 'min. vote {}'.format(self.vote_rule)
4840
4848
4841
4849
4842 class RepoReviewRule(Base, BaseModel):
4850 class RepoReviewRule(Base, BaseModel):
4843 __tablename__ = 'repo_review_rules'
4851 __tablename__ = 'repo_review_rules'
4844 __table_args__ = (
4852 __table_args__ = (
4845 base_table_args
4853 base_table_args
4846 )
4854 )
4847
4855
4848 repo_review_rule_id = Column(
4856 repo_review_rule_id = Column(
4849 'repo_review_rule_id', Integer(), primary_key=True)
4857 'repo_review_rule_id', Integer(), primary_key=True)
4850 repo_id = Column(
4858 repo_id = Column(
4851 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4859 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4852 repo = relationship('Repository', backref='review_rules')
4860 repo = relationship('Repository', backref='review_rules')
4853
4861
4854 review_rule_name = Column('review_rule_name', String(255))
4862 review_rule_name = Column('review_rule_name', String(255))
4855 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4863 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4856 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4864 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4857 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4865 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4858
4866
4859 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4867 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4860 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4868 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4861 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4869 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4862 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4870 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4863
4871
4864 rule_users = relationship('RepoReviewRuleUser')
4872 rule_users = relationship('RepoReviewRuleUser')
4865 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4873 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4866
4874
4867 def _validate_pattern(self, value):
4875 def _validate_pattern(self, value):
4868 re.compile('^' + glob2re(value) + '$')
4876 re.compile('^' + glob2re(value) + '$')
4869
4877
4870 @hybrid_property
4878 @hybrid_property
4871 def source_branch_pattern(self):
4879 def source_branch_pattern(self):
4872 return self._branch_pattern or '*'
4880 return self._branch_pattern or '*'
4873
4881
4874 @source_branch_pattern.setter
4882 @source_branch_pattern.setter
4875 def source_branch_pattern(self, value):
4883 def source_branch_pattern(self, value):
4876 self._validate_pattern(value)
4884 self._validate_pattern(value)
4877 self._branch_pattern = value or '*'
4885 self._branch_pattern = value or '*'
4878
4886
4879 @hybrid_property
4887 @hybrid_property
4880 def target_branch_pattern(self):
4888 def target_branch_pattern(self):
4881 return self._target_branch_pattern or '*'
4889 return self._target_branch_pattern or '*'
4882
4890
4883 @target_branch_pattern.setter
4891 @target_branch_pattern.setter
4884 def target_branch_pattern(self, value):
4892 def target_branch_pattern(self, value):
4885 self._validate_pattern(value)
4893 self._validate_pattern(value)
4886 self._target_branch_pattern = value or '*'
4894 self._target_branch_pattern = value or '*'
4887
4895
4888 @hybrid_property
4896 @hybrid_property
4889 def file_pattern(self):
4897 def file_pattern(self):
4890 return self._file_pattern or '*'
4898 return self._file_pattern or '*'
4891
4899
4892 @file_pattern.setter
4900 @file_pattern.setter
4893 def file_pattern(self, value):
4901 def file_pattern(self, value):
4894 self._validate_pattern(value)
4902 self._validate_pattern(value)
4895 self._file_pattern = value or '*'
4903 self._file_pattern = value or '*'
4896
4904
4897 def matches(self, source_branch, target_branch, files_changed):
4905 def matches(self, source_branch, target_branch, files_changed):
4898 """
4906 """
4899 Check if this review rule matches a branch/files in a pull request
4907 Check if this review rule matches a branch/files in a pull request
4900
4908
4901 :param source_branch: source branch name for the commit
4909 :param source_branch: source branch name for the commit
4902 :param target_branch: target branch name for the commit
4910 :param target_branch: target branch name for the commit
4903 :param files_changed: list of file paths changed in the pull request
4911 :param files_changed: list of file paths changed in the pull request
4904 """
4912 """
4905
4913
4906 source_branch = source_branch or ''
4914 source_branch = source_branch or ''
4907 target_branch = target_branch or ''
4915 target_branch = target_branch or ''
4908 files_changed = files_changed or []
4916 files_changed = files_changed or []
4909
4917
4910 branch_matches = True
4918 branch_matches = True
4911 if source_branch or target_branch:
4919 if source_branch or target_branch:
4912 if self.source_branch_pattern == '*':
4920 if self.source_branch_pattern == '*':
4913 source_branch_match = True
4921 source_branch_match = True
4914 else:
4922 else:
4915 if self.source_branch_pattern.startswith('re:'):
4923 if self.source_branch_pattern.startswith('re:'):
4916 source_pattern = self.source_branch_pattern[3:]
4924 source_pattern = self.source_branch_pattern[3:]
4917 else:
4925 else:
4918 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4926 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4919 source_branch_regex = re.compile(source_pattern)
4927 source_branch_regex = re.compile(source_pattern)
4920 source_branch_match = bool(source_branch_regex.search(source_branch))
4928 source_branch_match = bool(source_branch_regex.search(source_branch))
4921 if self.target_branch_pattern == '*':
4929 if self.target_branch_pattern == '*':
4922 target_branch_match = True
4930 target_branch_match = True
4923 else:
4931 else:
4924 if self.target_branch_pattern.startswith('re:'):
4932 if self.target_branch_pattern.startswith('re:'):
4925 target_pattern = self.target_branch_pattern[3:]
4933 target_pattern = self.target_branch_pattern[3:]
4926 else:
4934 else:
4927 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4935 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4928 target_branch_regex = re.compile(target_pattern)
4936 target_branch_regex = re.compile(target_pattern)
4929 target_branch_match = bool(target_branch_regex.search(target_branch))
4937 target_branch_match = bool(target_branch_regex.search(target_branch))
4930
4938
4931 branch_matches = source_branch_match and target_branch_match
4939 branch_matches = source_branch_match and target_branch_match
4932
4940
4933 files_matches = True
4941 files_matches = True
4934 if self.file_pattern != '*':
4942 if self.file_pattern != '*':
4935 files_matches = False
4943 files_matches = False
4936 if self.file_pattern.startswith('re:'):
4944 if self.file_pattern.startswith('re:'):
4937 file_pattern = self.file_pattern[3:]
4945 file_pattern = self.file_pattern[3:]
4938 else:
4946 else:
4939 file_pattern = glob2re(self.file_pattern)
4947 file_pattern = glob2re(self.file_pattern)
4940 file_regex = re.compile(file_pattern)
4948 file_regex = re.compile(file_pattern)
4941 for filename in files_changed:
4949 for filename in files_changed:
4942 if file_regex.search(filename):
4950 if file_regex.search(filename):
4943 files_matches = True
4951 files_matches = True
4944 break
4952 break
4945
4953
4946 return branch_matches and files_matches
4954 return branch_matches and files_matches
4947
4955
4948 @property
4956 @property
4949 def review_users(self):
4957 def review_users(self):
4950 """ Returns the users which this rule applies to """
4958 """ Returns the users which this rule applies to """
4951
4959
4952 users = collections.OrderedDict()
4960 users = collections.OrderedDict()
4953
4961
4954 for rule_user in self.rule_users:
4962 for rule_user in self.rule_users:
4955 if rule_user.user.active:
4963 if rule_user.user.active:
4956 if rule_user.user not in users:
4964 if rule_user.user not in users:
4957 users[rule_user.user.username] = {
4965 users[rule_user.user.username] = {
4958 'user': rule_user.user,
4966 'user': rule_user.user,
4959 'source': 'user',
4967 'source': 'user',
4960 'source_data': {},
4968 'source_data': {},
4961 'data': rule_user.rule_data()
4969 'data': rule_user.rule_data()
4962 }
4970 }
4963
4971
4964 for rule_user_group in self.rule_user_groups:
4972 for rule_user_group in self.rule_user_groups:
4965 source_data = {
4973 source_data = {
4966 'user_group_id': rule_user_group.users_group.users_group_id,
4974 'user_group_id': rule_user_group.users_group.users_group_id,
4967 'name': rule_user_group.users_group.users_group_name,
4975 'name': rule_user_group.users_group.users_group_name,
4968 'members': len(rule_user_group.users_group.members)
4976 'members': len(rule_user_group.users_group.members)
4969 }
4977 }
4970 for member in rule_user_group.users_group.members:
4978 for member in rule_user_group.users_group.members:
4971 if member.user.active:
4979 if member.user.active:
4972 key = member.user.username
4980 key = member.user.username
4973 if key in users:
4981 if key in users:
4974 # skip this member as we have him already
4982 # skip this member as we have him already
4975 # this prevents from override the "first" matched
4983 # this prevents from override the "first" matched
4976 # users with duplicates in multiple groups
4984 # users with duplicates in multiple groups
4977 continue
4985 continue
4978
4986
4979 users[key] = {
4987 users[key] = {
4980 'user': member.user,
4988 'user': member.user,
4981 'source': 'user_group',
4989 'source': 'user_group',
4982 'source_data': source_data,
4990 'source_data': source_data,
4983 'data': rule_user_group.rule_data()
4991 'data': rule_user_group.rule_data()
4984 }
4992 }
4985
4993
4986 return users
4994 return users
4987
4995
4988 def user_group_vote_rule(self, user_id):
4996 def user_group_vote_rule(self, user_id):
4989
4997
4990 rules = []
4998 rules = []
4991 if not self.rule_user_groups:
4999 if not self.rule_user_groups:
4992 return rules
5000 return rules
4993
5001
4994 for user_group in self.rule_user_groups:
5002 for user_group in self.rule_user_groups:
4995 user_group_members = [x.user_id for x in user_group.users_group.members]
5003 user_group_members = [x.user_id for x in user_group.users_group.members]
4996 if user_id in user_group_members:
5004 if user_id in user_group_members:
4997 rules.append(user_group)
5005 rules.append(user_group)
4998 return rules
5006 return rules
4999
5007
5000 def __repr__(self):
5008 def __repr__(self):
5001 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
5009 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
5002 self.repo_review_rule_id, self.repo)
5010 self.repo_review_rule_id, self.repo)
5003
5011
5004
5012
5005 class ScheduleEntry(Base, BaseModel):
5013 class ScheduleEntry(Base, BaseModel):
5006 __tablename__ = 'schedule_entries'
5014 __tablename__ = 'schedule_entries'
5007 __table_args__ = (
5015 __table_args__ = (
5008 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
5016 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
5009 UniqueConstraint('task_uid', name='s_task_uid_idx'),
5017 UniqueConstraint('task_uid', name='s_task_uid_idx'),
5010 base_table_args,
5018 base_table_args,
5011 )
5019 )
5012
5020
5013 schedule_types = ['crontab', 'timedelta', 'integer']
5021 schedule_types = ['crontab', 'timedelta', 'integer']
5014 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
5022 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
5015
5023
5016 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
5024 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
5017 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
5025 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
5018 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
5026 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
5019
5027
5020 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
5028 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
5021 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
5029 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
5022
5030
5023 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
5031 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
5024 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
5032 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
5025
5033
5026 # task
5034 # task
5027 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
5035 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
5028 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
5036 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
5029 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
5037 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
5030 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
5038 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
5031
5039
5032 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5040 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5033 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
5041 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
5034
5042
5035 @hybrid_property
5043 @hybrid_property
5036 def schedule_type(self):
5044 def schedule_type(self):
5037 return self._schedule_type
5045 return self._schedule_type
5038
5046
5039 @schedule_type.setter
5047 @schedule_type.setter
5040 def schedule_type(self, val):
5048 def schedule_type(self, val):
5041 if val not in self.schedule_types:
5049 if val not in self.schedule_types:
5042 raise ValueError('Value must be on of `{}` and got `{}`'.format(
5050 raise ValueError('Value must be on of `{}` and got `{}`'.format(
5043 val, self.schedule_type))
5051 val, self.schedule_type))
5044
5052
5045 self._schedule_type = val
5053 self._schedule_type = val
5046
5054
5047 @classmethod
5055 @classmethod
5048 def get_uid(cls, obj):
5056 def get_uid(cls, obj):
5049 args = obj.task_args
5057 args = obj.task_args
5050 kwargs = obj.task_kwargs
5058 kwargs = obj.task_kwargs
5051 if isinstance(args, JsonRaw):
5059 if isinstance(args, JsonRaw):
5052 try:
5060 try:
5053 args = json.loads(args)
5061 args = json.loads(args)
5054 except ValueError:
5062 except ValueError:
5055 args = tuple()
5063 args = tuple()
5056
5064
5057 if isinstance(kwargs, JsonRaw):
5065 if isinstance(kwargs, JsonRaw):
5058 try:
5066 try:
5059 kwargs = json.loads(kwargs)
5067 kwargs = json.loads(kwargs)
5060 except ValueError:
5068 except ValueError:
5061 kwargs = dict()
5069 kwargs = dict()
5062
5070
5063 dot_notation = obj.task_dot_notation
5071 dot_notation = obj.task_dot_notation
5064 val = '.'.join(map(safe_str, [
5072 val = '.'.join(map(safe_str, [
5065 sorted(dot_notation), args, sorted(kwargs.items())]))
5073 sorted(dot_notation), args, sorted(kwargs.items())]))
5066 return hashlib.sha1(val).hexdigest()
5074 return hashlib.sha1(val).hexdigest()
5067
5075
5068 @classmethod
5076 @classmethod
5069 def get_by_schedule_name(cls, schedule_name):
5077 def get_by_schedule_name(cls, schedule_name):
5070 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
5078 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
5071
5079
5072 @classmethod
5080 @classmethod
5073 def get_by_schedule_id(cls, schedule_id):
5081 def get_by_schedule_id(cls, schedule_id):
5074 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
5082 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
5075
5083
5076 @property
5084 @property
5077 def task(self):
5085 def task(self):
5078 return self.task_dot_notation
5086 return self.task_dot_notation
5079
5087
5080 @property
5088 @property
5081 def schedule(self):
5089 def schedule(self):
5082 from rhodecode.lib.celerylib.utils import raw_2_schedule
5090 from rhodecode.lib.celerylib.utils import raw_2_schedule
5083 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
5091 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
5084 return schedule
5092 return schedule
5085
5093
5086 @property
5094 @property
5087 def args(self):
5095 def args(self):
5088 try:
5096 try:
5089 return list(self.task_args or [])
5097 return list(self.task_args or [])
5090 except ValueError:
5098 except ValueError:
5091 return list()
5099 return list()
5092
5100
5093 @property
5101 @property
5094 def kwargs(self):
5102 def kwargs(self):
5095 try:
5103 try:
5096 return dict(self.task_kwargs or {})
5104 return dict(self.task_kwargs or {})
5097 except ValueError:
5105 except ValueError:
5098 return dict()
5106 return dict()
5099
5107
5100 def _as_raw(self, val):
5108 def _as_raw(self, val):
5101 if hasattr(val, 'de_coerce'):
5109 if hasattr(val, 'de_coerce'):
5102 val = val.de_coerce()
5110 val = val.de_coerce()
5103 if val:
5111 if val:
5104 val = json.dumps(val)
5112 val = json.dumps(val)
5105
5113
5106 return val
5114 return val
5107
5115
5108 @property
5116 @property
5109 def schedule_definition_raw(self):
5117 def schedule_definition_raw(self):
5110 return self._as_raw(self.schedule_definition)
5118 return self._as_raw(self.schedule_definition)
5111
5119
5112 @property
5120 @property
5113 def args_raw(self):
5121 def args_raw(self):
5114 return self._as_raw(self.task_args)
5122 return self._as_raw(self.task_args)
5115
5123
5116 @property
5124 @property
5117 def kwargs_raw(self):
5125 def kwargs_raw(self):
5118 return self._as_raw(self.task_kwargs)
5126 return self._as_raw(self.task_kwargs)
5119
5127
5120 def __repr__(self):
5128 def __repr__(self):
5121 return '<DB:ScheduleEntry({}:{})>'.format(
5129 return '<DB:ScheduleEntry({}:{})>'.format(
5122 self.schedule_entry_id, self.schedule_name)
5130 self.schedule_entry_id, self.schedule_name)
5123
5131
5124
5132
5125 @event.listens_for(ScheduleEntry, 'before_update')
5133 @event.listens_for(ScheduleEntry, 'before_update')
5126 def update_task_uid(mapper, connection, target):
5134 def update_task_uid(mapper, connection, target):
5127 target.task_uid = ScheduleEntry.get_uid(target)
5135 target.task_uid = ScheduleEntry.get_uid(target)
5128
5136
5129
5137
5130 @event.listens_for(ScheduleEntry, 'before_insert')
5138 @event.listens_for(ScheduleEntry, 'before_insert')
5131 def set_task_uid(mapper, connection, target):
5139 def set_task_uid(mapper, connection, target):
5132 target.task_uid = ScheduleEntry.get_uid(target)
5140 target.task_uid = ScheduleEntry.get_uid(target)
5133
5141
5134
5142
5135 class _BaseBranchPerms(BaseModel):
5143 class _BaseBranchPerms(BaseModel):
5136 @classmethod
5144 @classmethod
5137 def compute_hash(cls, value):
5145 def compute_hash(cls, value):
5138 return sha1_safe(value)
5146 return sha1_safe(value)
5139
5147
5140 @hybrid_property
5148 @hybrid_property
5141 def branch_pattern(self):
5149 def branch_pattern(self):
5142 return self._branch_pattern or '*'
5150 return self._branch_pattern or '*'
5143
5151
5144 @hybrid_property
5152 @hybrid_property
5145 def branch_hash(self):
5153 def branch_hash(self):
5146 return self._branch_hash
5154 return self._branch_hash
5147
5155
5148 def _validate_glob(self, value):
5156 def _validate_glob(self, value):
5149 re.compile('^' + glob2re(value) + '$')
5157 re.compile('^' + glob2re(value) + '$')
5150
5158
5151 @branch_pattern.setter
5159 @branch_pattern.setter
5152 def branch_pattern(self, value):
5160 def branch_pattern(self, value):
5153 self._validate_glob(value)
5161 self._validate_glob(value)
5154 self._branch_pattern = value or '*'
5162 self._branch_pattern = value or '*'
5155 # set the Hash when setting the branch pattern
5163 # set the Hash when setting the branch pattern
5156 self._branch_hash = self.compute_hash(self._branch_pattern)
5164 self._branch_hash = self.compute_hash(self._branch_pattern)
5157
5165
5158 def matches(self, branch):
5166 def matches(self, branch):
5159 """
5167 """
5160 Check if this the branch matches entry
5168 Check if this the branch matches entry
5161
5169
5162 :param branch: branch name for the commit
5170 :param branch: branch name for the commit
5163 """
5171 """
5164
5172
5165 branch = branch or ''
5173 branch = branch or ''
5166
5174
5167 branch_matches = True
5175 branch_matches = True
5168 if branch:
5176 if branch:
5169 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
5177 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
5170 branch_matches = bool(branch_regex.search(branch))
5178 branch_matches = bool(branch_regex.search(branch))
5171
5179
5172 return branch_matches
5180 return branch_matches
5173
5181
5174
5182
5175 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
5183 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
5176 __tablename__ = 'user_to_repo_branch_permissions'
5184 __tablename__ = 'user_to_repo_branch_permissions'
5177 __table_args__ = (
5185 __table_args__ = (
5178 base_table_args
5186 base_table_args
5179 )
5187 )
5180
5188
5181 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5189 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5182
5190
5183 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5191 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5184 repo = relationship('Repository', backref='user_branch_perms')
5192 repo = relationship('Repository', backref='user_branch_perms')
5185
5193
5186 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5194 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5187 permission = relationship('Permission')
5195 permission = relationship('Permission')
5188
5196
5189 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
5197 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
5190 user_repo_to_perm = relationship('UserRepoToPerm')
5198 user_repo_to_perm = relationship('UserRepoToPerm')
5191
5199
5192 rule_order = Column('rule_order', Integer(), nullable=False)
5200 rule_order = Column('rule_order', Integer(), nullable=False)
5193 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5201 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5194 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5202 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5195
5203
5196 def __unicode__(self):
5204 def __unicode__(self):
5197 return u'<UserBranchPermission(%s => %r)>' % (
5205 return u'<UserBranchPermission(%s => %r)>' % (
5198 self.user_repo_to_perm, self.branch_pattern)
5206 self.user_repo_to_perm, self.branch_pattern)
5199
5207
5200
5208
5201 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
5209 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
5202 __tablename__ = 'user_group_to_repo_branch_permissions'
5210 __tablename__ = 'user_group_to_repo_branch_permissions'
5203 __table_args__ = (
5211 __table_args__ = (
5204 base_table_args
5212 base_table_args
5205 )
5213 )
5206
5214
5207 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5215 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5208
5216
5209 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5217 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5210 repo = relationship('Repository', backref='user_group_branch_perms')
5218 repo = relationship('Repository', backref='user_group_branch_perms')
5211
5219
5212 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5220 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5213 permission = relationship('Permission')
5221 permission = relationship('Permission')
5214
5222
5215 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('users_group_repo_to_perm.users_group_to_perm_id'), nullable=False, unique=None, default=None)
5223 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('users_group_repo_to_perm.users_group_to_perm_id'), nullable=False, unique=None, default=None)
5216 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
5224 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
5217
5225
5218 rule_order = Column('rule_order', Integer(), nullable=False)
5226 rule_order = Column('rule_order', Integer(), nullable=False)
5219 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5227 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5220 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5228 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5221
5229
5222 def __unicode__(self):
5230 def __unicode__(self):
5223 return u'<UserBranchPermission(%s => %r)>' % (
5231 return u'<UserBranchPermission(%s => %r)>' % (
5224 self.user_group_repo_to_perm, self.branch_pattern)
5232 self.user_group_repo_to_perm, self.branch_pattern)
5225
5233
5226
5234
5227 class UserBookmark(Base, BaseModel):
5235 class UserBookmark(Base, BaseModel):
5228 __tablename__ = 'user_bookmarks'
5236 __tablename__ = 'user_bookmarks'
5229 __table_args__ = (
5237 __table_args__ = (
5230 UniqueConstraint('user_id', 'bookmark_repo_id'),
5238 UniqueConstraint('user_id', 'bookmark_repo_id'),
5231 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5239 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5232 UniqueConstraint('user_id', 'bookmark_position'),
5240 UniqueConstraint('user_id', 'bookmark_position'),
5233 base_table_args
5241 base_table_args
5234 )
5242 )
5235
5243
5236 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5244 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5237 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5245 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5238 position = Column("bookmark_position", Integer(), nullable=False)
5246 position = Column("bookmark_position", Integer(), nullable=False)
5239 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5247 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5240 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5248 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5241 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5249 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5242
5250
5243 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5251 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5244 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5252 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5245
5253
5246 user = relationship("User")
5254 user = relationship("User")
5247
5255
5248 repository = relationship("Repository")
5256 repository = relationship("Repository")
5249 repository_group = relationship("RepoGroup")
5257 repository_group = relationship("RepoGroup")
5250
5258
5251 @classmethod
5259 @classmethod
5252 def get_by_position_for_user(cls, position, user_id):
5260 def get_by_position_for_user(cls, position, user_id):
5253 return cls.query() \
5261 return cls.query() \
5254 .filter(UserBookmark.user_id == user_id) \
5262 .filter(UserBookmark.user_id == user_id) \
5255 .filter(UserBookmark.position == position).scalar()
5263 .filter(UserBookmark.position == position).scalar()
5256
5264
5257 @classmethod
5265 @classmethod
5258 def get_bookmarks_for_user(cls, user_id, cache=True):
5266 def get_bookmarks_for_user(cls, user_id, cache=True):
5259 bookmarks = cls.query() \
5267 bookmarks = cls.query() \
5260 .filter(UserBookmark.user_id == user_id) \
5268 .filter(UserBookmark.user_id == user_id) \
5261 .options(joinedload(UserBookmark.repository)) \
5269 .options(joinedload(UserBookmark.repository)) \
5262 .options(joinedload(UserBookmark.repository_group)) \
5270 .options(joinedload(UserBookmark.repository_group)) \
5263 .order_by(UserBookmark.position.asc())
5271 .order_by(UserBookmark.position.asc())
5264
5272
5265 if cache:
5273 if cache:
5266 bookmarks = bookmarks.options(
5274 bookmarks = bookmarks.options(
5267 FromCache("sql_cache_short", "get_user_{}_bookmarks".format(user_id))
5275 FromCache("sql_cache_short", "get_user_{}_bookmarks".format(user_id))
5268 )
5276 )
5269
5277
5270 return bookmarks.all()
5278 return bookmarks.all()
5271
5279
5272 def __unicode__(self):
5280 def __unicode__(self):
5273 return u'<UserBookmark(%s @ %r)>' % (self.position, self.redirect_url)
5281 return u'<UserBookmark(%s @ %r)>' % (self.position, self.redirect_url)
5274
5282
5275
5283
5276 class FileStore(Base, BaseModel):
5284 class FileStore(Base, BaseModel):
5277 __tablename__ = 'file_store'
5285 __tablename__ = 'file_store'
5278 __table_args__ = (
5286 __table_args__ = (
5279 base_table_args
5287 base_table_args
5280 )
5288 )
5281
5289
5282 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5290 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5283 file_uid = Column('file_uid', String(1024), nullable=False)
5291 file_uid = Column('file_uid', String(1024), nullable=False)
5284 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5292 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5285 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5293 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5286 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5294 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5287
5295
5288 # sha256 hash
5296 # sha256 hash
5289 file_hash = Column('file_hash', String(512), nullable=False)
5297 file_hash = Column('file_hash', String(512), nullable=False)
5290 file_size = Column('file_size', BigInteger(), nullable=False)
5298 file_size = Column('file_size', BigInteger(), nullable=False)
5291
5299
5292 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5300 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5293 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5301 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5294 accessed_count = Column('accessed_count', Integer(), default=0)
5302 accessed_count = Column('accessed_count', Integer(), default=0)
5295
5303
5296 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5304 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5297
5305
5298 # if repo/repo_group reference is set, check for permissions
5306 # if repo/repo_group reference is set, check for permissions
5299 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5307 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5300
5308
5301 # hidden defines an attachment that should be hidden from showing in artifact listing
5309 # hidden defines an attachment that should be hidden from showing in artifact listing
5302 hidden = Column('hidden', Boolean(), nullable=False, default=False)
5310 hidden = Column('hidden', Boolean(), nullable=False, default=False)
5303
5311
5304 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5312 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5305 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
5313 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
5306
5314
5307 file_metadata = relationship('FileStoreMetadata', lazy='joined')
5315 file_metadata = relationship('FileStoreMetadata', lazy='joined')
5308
5316
5309 # scope limited to user, which requester have access to
5317 # scope limited to user, which requester have access to
5310 scope_user_id = Column(
5318 scope_user_id = Column(
5311 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5319 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5312 nullable=True, unique=None, default=None)
5320 nullable=True, unique=None, default=None)
5313 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
5321 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
5314
5322
5315 # scope limited to user group, which requester have access to
5323 # scope limited to user group, which requester have access to
5316 scope_user_group_id = Column(
5324 scope_user_group_id = Column(
5317 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5325 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5318 nullable=True, unique=None, default=None)
5326 nullable=True, unique=None, default=None)
5319 user_group = relationship('UserGroup', lazy='joined')
5327 user_group = relationship('UserGroup', lazy='joined')
5320
5328
5321 # scope limited to repo, which requester have access to
5329 # scope limited to repo, which requester have access to
5322 scope_repo_id = Column(
5330 scope_repo_id = Column(
5323 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5331 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5324 nullable=True, unique=None, default=None)
5332 nullable=True, unique=None, default=None)
5325 repo = relationship('Repository', lazy='joined')
5333 repo = relationship('Repository', lazy='joined')
5326
5334
5327 # scope limited to repo group, which requester have access to
5335 # scope limited to repo group, which requester have access to
5328 scope_repo_group_id = Column(
5336 scope_repo_group_id = Column(
5329 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5337 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5330 nullable=True, unique=None, default=None)
5338 nullable=True, unique=None, default=None)
5331 repo_group = relationship('RepoGroup', lazy='joined')
5339 repo_group = relationship('RepoGroup', lazy='joined')
5332
5340
5333 @classmethod
5341 @classmethod
5334 def get_by_store_uid(cls, file_store_uid):
5342 def get_by_store_uid(cls, file_store_uid):
5335 return FileStore.query().filter(FileStore.file_uid == file_store_uid).scalar()
5343 return FileStore.query().filter(FileStore.file_uid == file_store_uid).scalar()
5336
5344
5337 @classmethod
5345 @classmethod
5338 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5346 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5339 file_description='', enabled=True, hidden=False, check_acl=True,
5347 file_description='', enabled=True, hidden=False, check_acl=True,
5340 user_id=None, scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5348 user_id=None, scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5341
5349
5342 store_entry = FileStore()
5350 store_entry = FileStore()
5343 store_entry.file_uid = file_uid
5351 store_entry.file_uid = file_uid
5344 store_entry.file_display_name = file_display_name
5352 store_entry.file_display_name = file_display_name
5345 store_entry.file_org_name = filename
5353 store_entry.file_org_name = filename
5346 store_entry.file_size = file_size
5354 store_entry.file_size = file_size
5347 store_entry.file_hash = file_hash
5355 store_entry.file_hash = file_hash
5348 store_entry.file_description = file_description
5356 store_entry.file_description = file_description
5349
5357
5350 store_entry.check_acl = check_acl
5358 store_entry.check_acl = check_acl
5351 store_entry.enabled = enabled
5359 store_entry.enabled = enabled
5352 store_entry.hidden = hidden
5360 store_entry.hidden = hidden
5353
5361
5354 store_entry.user_id = user_id
5362 store_entry.user_id = user_id
5355 store_entry.scope_user_id = scope_user_id
5363 store_entry.scope_user_id = scope_user_id
5356 store_entry.scope_repo_id = scope_repo_id
5364 store_entry.scope_repo_id = scope_repo_id
5357 store_entry.scope_repo_group_id = scope_repo_group_id
5365 store_entry.scope_repo_group_id = scope_repo_group_id
5358
5366
5359 return store_entry
5367 return store_entry
5360
5368
5361 @classmethod
5369 @classmethod
5362 def store_metadata(cls, file_store_id, args, commit=True):
5370 def store_metadata(cls, file_store_id, args, commit=True):
5363 file_store = FileStore.get(file_store_id)
5371 file_store = FileStore.get(file_store_id)
5364 if file_store is None:
5372 if file_store is None:
5365 return
5373 return
5366
5374
5367 for section, key, value, value_type in args:
5375 for section, key, value, value_type in args:
5368 has_key = FileStoreMetadata().query() \
5376 has_key = FileStoreMetadata().query() \
5369 .filter(FileStoreMetadata.file_store_id == file_store.file_store_id) \
5377 .filter(FileStoreMetadata.file_store_id == file_store.file_store_id) \
5370 .filter(FileStoreMetadata.file_store_meta_section == section) \
5378 .filter(FileStoreMetadata.file_store_meta_section == section) \
5371 .filter(FileStoreMetadata.file_store_meta_key == key) \
5379 .filter(FileStoreMetadata.file_store_meta_key == key) \
5372 .scalar()
5380 .scalar()
5373 if has_key:
5381 if has_key:
5374 msg = 'key `{}` already defined under section `{}` for this file.'\
5382 msg = 'key `{}` already defined under section `{}` for this file.'\
5375 .format(key, section)
5383 .format(key, section)
5376 raise ArtifactMetadataDuplicate(msg, err_section=section, err_key=key)
5384 raise ArtifactMetadataDuplicate(msg, err_section=section, err_key=key)
5377
5385
5378 # NOTE(marcink): raises ArtifactMetadataBadValueType
5386 # NOTE(marcink): raises ArtifactMetadataBadValueType
5379 FileStoreMetadata.valid_value_type(value_type)
5387 FileStoreMetadata.valid_value_type(value_type)
5380
5388
5381 meta_entry = FileStoreMetadata()
5389 meta_entry = FileStoreMetadata()
5382 meta_entry.file_store = file_store
5390 meta_entry.file_store = file_store
5383 meta_entry.file_store_meta_section = section
5391 meta_entry.file_store_meta_section = section
5384 meta_entry.file_store_meta_key = key
5392 meta_entry.file_store_meta_key = key
5385 meta_entry.file_store_meta_value_type = value_type
5393 meta_entry.file_store_meta_value_type = value_type
5386 meta_entry.file_store_meta_value = value
5394 meta_entry.file_store_meta_value = value
5387
5395
5388 Session().add(meta_entry)
5396 Session().add(meta_entry)
5389
5397
5390 try:
5398 try:
5391 if commit:
5399 if commit:
5392 Session().commit()
5400 Session().commit()
5393 except IntegrityError:
5401 except IntegrityError:
5394 Session().rollback()
5402 Session().rollback()
5395 raise ArtifactMetadataDuplicate('Duplicate section/key found for this file.')
5403 raise ArtifactMetadataDuplicate('Duplicate section/key found for this file.')
5396
5404
5397 @classmethod
5405 @classmethod
5398 def bump_access_counter(cls, file_uid, commit=True):
5406 def bump_access_counter(cls, file_uid, commit=True):
5399 FileStore().query()\
5407 FileStore().query()\
5400 .filter(FileStore.file_uid == file_uid)\
5408 .filter(FileStore.file_uid == file_uid)\
5401 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5409 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5402 FileStore.accessed_on: datetime.datetime.now()})
5410 FileStore.accessed_on: datetime.datetime.now()})
5403 if commit:
5411 if commit:
5404 Session().commit()
5412 Session().commit()
5405
5413
5406 def __json__(self):
5414 def __json__(self):
5407 data = {
5415 data = {
5408 'filename': self.file_display_name,
5416 'filename': self.file_display_name,
5409 'filename_org': self.file_org_name,
5417 'filename_org': self.file_org_name,
5410 'file_uid': self.file_uid,
5418 'file_uid': self.file_uid,
5411 'description': self.file_description,
5419 'description': self.file_description,
5412 'hidden': self.hidden,
5420 'hidden': self.hidden,
5413 'size': self.file_size,
5421 'size': self.file_size,
5414 'created_on': self.created_on,
5422 'created_on': self.created_on,
5415 'uploaded_by': self.upload_user.get_api_data(details='basic'),
5423 'uploaded_by': self.upload_user.get_api_data(details='basic'),
5416 'downloaded_times': self.accessed_count,
5424 'downloaded_times': self.accessed_count,
5417 'sha256': self.file_hash,
5425 'sha256': self.file_hash,
5418 'metadata': self.file_metadata,
5426 'metadata': self.file_metadata,
5419 }
5427 }
5420
5428
5421 return data
5429 return data
5422
5430
5423 def __repr__(self):
5431 def __repr__(self):
5424 return '<FileStore({})>'.format(self.file_store_id)
5432 return '<FileStore({})>'.format(self.file_store_id)
5425
5433
5426
5434
5427 class FileStoreMetadata(Base, BaseModel):
5435 class FileStoreMetadata(Base, BaseModel):
5428 __tablename__ = 'file_store_metadata'
5436 __tablename__ = 'file_store_metadata'
5429 __table_args__ = (
5437 __table_args__ = (
5430 UniqueConstraint('file_store_id', 'file_store_meta_section_hash', 'file_store_meta_key_hash'),
5438 UniqueConstraint('file_store_id', 'file_store_meta_section_hash', 'file_store_meta_key_hash'),
5431 Index('file_store_meta_section_idx', 'file_store_meta_section', mysql_length=255),
5439 Index('file_store_meta_section_idx', 'file_store_meta_section', mysql_length=255),
5432 Index('file_store_meta_key_idx', 'file_store_meta_key', mysql_length=255),
5440 Index('file_store_meta_key_idx', 'file_store_meta_key', mysql_length=255),
5433 base_table_args
5441 base_table_args
5434 )
5442 )
5435 SETTINGS_TYPES = {
5443 SETTINGS_TYPES = {
5436 'str': safe_str,
5444 'str': safe_str,
5437 'int': safe_int,
5445 'int': safe_int,
5438 'unicode': safe_unicode,
5446 'unicode': safe_unicode,
5439 'bool': str2bool,
5447 'bool': str2bool,
5440 'list': functools.partial(aslist, sep=',')
5448 'list': functools.partial(aslist, sep=',')
5441 }
5449 }
5442
5450
5443 file_store_meta_id = Column(
5451 file_store_meta_id = Column(
5444 "file_store_meta_id", Integer(), nullable=False, unique=True, default=None,
5452 "file_store_meta_id", Integer(), nullable=False, unique=True, default=None,
5445 primary_key=True)
5453 primary_key=True)
5446 _file_store_meta_section = Column(
5454 _file_store_meta_section = Column(
5447 "file_store_meta_section", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5455 "file_store_meta_section", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5448 nullable=True, unique=None, default=None)
5456 nullable=True, unique=None, default=None)
5449 _file_store_meta_section_hash = Column(
5457 _file_store_meta_section_hash = Column(
5450 "file_store_meta_section_hash", String(255),
5458 "file_store_meta_section_hash", String(255),
5451 nullable=True, unique=None, default=None)
5459 nullable=True, unique=None, default=None)
5452 _file_store_meta_key = Column(
5460 _file_store_meta_key = Column(
5453 "file_store_meta_key", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5461 "file_store_meta_key", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5454 nullable=True, unique=None, default=None)
5462 nullable=True, unique=None, default=None)
5455 _file_store_meta_key_hash = Column(
5463 _file_store_meta_key_hash = Column(
5456 "file_store_meta_key_hash", String(255), nullable=True, unique=None, default=None)
5464 "file_store_meta_key_hash", String(255), nullable=True, unique=None, default=None)
5457 _file_store_meta_value = Column(
5465 _file_store_meta_value = Column(
5458 "file_store_meta_value", UnicodeText().with_variant(UnicodeText(20480), 'mysql'),
5466 "file_store_meta_value", UnicodeText().with_variant(UnicodeText(20480), 'mysql'),
5459 nullable=True, unique=None, default=None)
5467 nullable=True, unique=None, default=None)
5460 _file_store_meta_value_type = Column(
5468 _file_store_meta_value_type = Column(
5461 "file_store_meta_value_type", String(255), nullable=True, unique=None,
5469 "file_store_meta_value_type", String(255), nullable=True, unique=None,
5462 default='unicode')
5470 default='unicode')
5463
5471
5464 file_store_id = Column(
5472 file_store_id = Column(
5465 'file_store_id', Integer(), ForeignKey('file_store.file_store_id'),
5473 'file_store_id', Integer(), ForeignKey('file_store.file_store_id'),
5466 nullable=True, unique=None, default=None)
5474 nullable=True, unique=None, default=None)
5467
5475
5468 file_store = relationship('FileStore', lazy='joined')
5476 file_store = relationship('FileStore', lazy='joined')
5469
5477
5470 @classmethod
5478 @classmethod
5471 def valid_value_type(cls, value):
5479 def valid_value_type(cls, value):
5472 if value.split('.')[0] not in cls.SETTINGS_TYPES:
5480 if value.split('.')[0] not in cls.SETTINGS_TYPES:
5473 raise ArtifactMetadataBadValueType(
5481 raise ArtifactMetadataBadValueType(
5474 'value_type must be one of %s got %s' % (cls.SETTINGS_TYPES.keys(), value))
5482 'value_type must be one of %s got %s' % (cls.SETTINGS_TYPES.keys(), value))
5475
5483
5476 @hybrid_property
5484 @hybrid_property
5477 def file_store_meta_section(self):
5485 def file_store_meta_section(self):
5478 return self._file_store_meta_section
5486 return self._file_store_meta_section
5479
5487
5480 @file_store_meta_section.setter
5488 @file_store_meta_section.setter
5481 def file_store_meta_section(self, value):
5489 def file_store_meta_section(self, value):
5482 self._file_store_meta_section = value
5490 self._file_store_meta_section = value
5483 self._file_store_meta_section_hash = _hash_key(value)
5491 self._file_store_meta_section_hash = _hash_key(value)
5484
5492
5485 @hybrid_property
5493 @hybrid_property
5486 def file_store_meta_key(self):
5494 def file_store_meta_key(self):
5487 return self._file_store_meta_key
5495 return self._file_store_meta_key
5488
5496
5489 @file_store_meta_key.setter
5497 @file_store_meta_key.setter
5490 def file_store_meta_key(self, value):
5498 def file_store_meta_key(self, value):
5491 self._file_store_meta_key = value
5499 self._file_store_meta_key = value
5492 self._file_store_meta_key_hash = _hash_key(value)
5500 self._file_store_meta_key_hash = _hash_key(value)
5493
5501
5494 @hybrid_property
5502 @hybrid_property
5495 def file_store_meta_value(self):
5503 def file_store_meta_value(self):
5496 val = self._file_store_meta_value
5504 val = self._file_store_meta_value
5497
5505
5498 if self._file_store_meta_value_type:
5506 if self._file_store_meta_value_type:
5499 # e.g unicode.encrypted == unicode
5507 # e.g unicode.encrypted == unicode
5500 _type = self._file_store_meta_value_type.split('.')[0]
5508 _type = self._file_store_meta_value_type.split('.')[0]
5501 # decode the encrypted value if it's encrypted field type
5509 # decode the encrypted value if it's encrypted field type
5502 if '.encrypted' in self._file_store_meta_value_type:
5510 if '.encrypted' in self._file_store_meta_value_type:
5503 cipher = EncryptedTextValue()
5511 cipher = EncryptedTextValue()
5504 val = safe_unicode(cipher.process_result_value(val, None))
5512 val = safe_unicode(cipher.process_result_value(val, None))
5505 # do final type conversion
5513 # do final type conversion
5506 converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
5514 converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
5507 val = converter(val)
5515 val = converter(val)
5508
5516
5509 return val
5517 return val
5510
5518
5511 @file_store_meta_value.setter
5519 @file_store_meta_value.setter
5512 def file_store_meta_value(self, val):
5520 def file_store_meta_value(self, val):
5513 val = safe_unicode(val)
5521 val = safe_unicode(val)
5514 # encode the encrypted value
5522 # encode the encrypted value
5515 if '.encrypted' in self.file_store_meta_value_type:
5523 if '.encrypted' in self.file_store_meta_value_type:
5516 cipher = EncryptedTextValue()
5524 cipher = EncryptedTextValue()
5517 val = safe_unicode(cipher.process_bind_param(val, None))
5525 val = safe_unicode(cipher.process_bind_param(val, None))
5518 self._file_store_meta_value = val
5526 self._file_store_meta_value = val
5519
5527
5520 @hybrid_property
5528 @hybrid_property
5521 def file_store_meta_value_type(self):
5529 def file_store_meta_value_type(self):
5522 return self._file_store_meta_value_type
5530 return self._file_store_meta_value_type
5523
5531
5524 @file_store_meta_value_type.setter
5532 @file_store_meta_value_type.setter
5525 def file_store_meta_value_type(self, val):
5533 def file_store_meta_value_type(self, val):
5526 # e.g unicode.encrypted
5534 # e.g unicode.encrypted
5527 self.valid_value_type(val)
5535 self.valid_value_type(val)
5528 self._file_store_meta_value_type = val
5536 self._file_store_meta_value_type = val
5529
5537
5530 def __json__(self):
5538 def __json__(self):
5531 data = {
5539 data = {
5532 'artifact': self.file_store.file_uid,
5540 'artifact': self.file_store.file_uid,
5533 'section': self.file_store_meta_section,
5541 'section': self.file_store_meta_section,
5534 'key': self.file_store_meta_key,
5542 'key': self.file_store_meta_key,
5535 'value': self.file_store_meta_value,
5543 'value': self.file_store_meta_value,
5536 }
5544 }
5537
5545
5538 return data
5546 return data
5539
5547
5540 def __repr__(self):
5548 def __repr__(self):
5541 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.file_store_meta_section,
5549 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.file_store_meta_section,
5542 self.file_store_meta_key, self.file_store_meta_value)
5550 self.file_store_meta_key, self.file_store_meta_value)
5543
5551
5544
5552
5545 class DbMigrateVersion(Base, BaseModel):
5553 class DbMigrateVersion(Base, BaseModel):
5546 __tablename__ = 'db_migrate_version'
5554 __tablename__ = 'db_migrate_version'
5547 __table_args__ = (
5555 __table_args__ = (
5548 base_table_args,
5556 base_table_args,
5549 )
5557 )
5550
5558
5551 repository_id = Column('repository_id', String(250), primary_key=True)
5559 repository_id = Column('repository_id', String(250), primary_key=True)
5552 repository_path = Column('repository_path', Text)
5560 repository_path = Column('repository_path', Text)
5553 version = Column('version', Integer)
5561 version = Column('version', Integer)
5554
5562
5555 @classmethod
5563 @classmethod
5556 def set_version(cls, version):
5564 def set_version(cls, version):
5557 """
5565 """
5558 Helper for forcing a different version, usually for debugging purposes via ishell.
5566 Helper for forcing a different version, usually for debugging purposes via ishell.
5559 """
5567 """
5560 ver = DbMigrateVersion.query().first()
5568 ver = DbMigrateVersion.query().first()
5561 ver.version = version
5569 ver.version = version
5562 Session().commit()
5570 Session().commit()
5563
5571
5564
5572
5565 class DbSession(Base, BaseModel):
5573 class DbSession(Base, BaseModel):
5566 __tablename__ = 'db_session'
5574 __tablename__ = 'db_session'
5567 __table_args__ = (
5575 __table_args__ = (
5568 base_table_args,
5576 base_table_args,
5569 )
5577 )
5570
5578
5571 def __repr__(self):
5579 def __repr__(self):
5572 return '<DB:DbSession({})>'.format(self.id)
5580 return '<DB:DbSession({})>'.format(self.id)
5573
5581
5574 id = Column('id', Integer())
5582 id = Column('id', Integer())
5575 namespace = Column('namespace', String(255), primary_key=True)
5583 namespace = Column('namespace', String(255), primary_key=True)
5576 accessed = Column('accessed', DateTime, nullable=False)
5584 accessed = Column('accessed', DateTime, nullable=False)
5577 created = Column('created', DateTime, nullable=False)
5585 created = Column('created', DateTime, nullable=False)
5578 data = Column('data', PickleType, nullable=False)
5586 data = Column('data', PickleType, nullable=False)
@@ -1,426 +1,426 b''
1 ## -*- coding: utf-8 -*-
1 ## -*- coding: utf-8 -*-
2 ## usage:
2 ## usage:
3 ## <%namespace name="comment" file="/changeset/changeset_file_comment.mako"/>
3 ## <%namespace name="comment" file="/changeset/changeset_file_comment.mako"/>
4 ## ${comment.comment_block(comment)}
4 ## ${comment.comment_block(comment)}
5 ##
5 ##
6 <%namespace name="base" file="/base/base.mako"/>
6 <%namespace name="base" file="/base/base.mako"/>
7
7
8 <%def name="comment_block(comment, inline=False, active_pattern_entries=None)">
8 <%def name="comment_block(comment, inline=False, active_pattern_entries=None)">
9 <% pr_index_ver = comment.get_index_version(getattr(c, 'versions', [])) %>
9 <% pr_index_ver = comment.get_index_version(getattr(c, 'versions', [])) %>
10 <% latest_ver = len(getattr(c, 'versions', [])) %>
10 <% latest_ver = len(getattr(c, 'versions', [])) %>
11 % if inline:
11 % if inline:
12 <% outdated_at_ver = comment.outdated_at_version(getattr(c, 'at_version_num', None)) %>
12 <% outdated_at_ver = comment.outdated_at_version(getattr(c, 'at_version_num', None)) %>
13 % else:
13 % else:
14 <% outdated_at_ver = comment.older_than_version(getattr(c, 'at_version_num', None)) %>
14 <% outdated_at_ver = comment.older_than_version(getattr(c, 'at_version_num', None)) %>
15 % endif
15 % endif
16
16
17 <div class="comment
17 <div class="comment
18 ${'comment-inline' if inline else 'comment-general'}
18 ${'comment-inline' if inline else 'comment-general'}
19 ${'comment-outdated' if outdated_at_ver else 'comment-current'}"
19 ${'comment-outdated' if outdated_at_ver else 'comment-current'}"
20 id="comment-${comment.comment_id}"
20 id="comment-${comment.comment_id}"
21 line="${comment.line_no}"
21 line="${comment.line_no}"
22 data-comment-id="${comment.comment_id}"
22 data-comment-id="${comment.comment_id}"
23 data-comment-type="${comment.comment_type}"
23 data-comment-type="${comment.comment_type}"
24 data-comment-line-no="${comment.line_no}"
24 data-comment-line-no="${comment.line_no}"
25 data-comment-inline=${h.json.dumps(inline)}
25 data-comment-inline=${h.json.dumps(inline)}
26 style="${'display: none;' if outdated_at_ver else ''}">
26 style="${'display: none;' if outdated_at_ver else ''}">
27
27
28 <div class="meta">
28 <div class="meta">
29 <div class="comment-type-label">
29 <div class="comment-type-label">
30 <div class="comment-label ${comment.comment_type or 'note'}" id="comment-label-${comment.comment_id}" title="line: ${comment.line_no}">
30 <div class="comment-label ${comment.comment_type or 'note'}" id="comment-label-${comment.comment_id}" title="line: ${comment.line_no}">
31 % if comment.comment_type == 'todo':
31 % if comment.comment_type == 'todo':
32 % if comment.resolved:
32 % if comment.resolved:
33 <div class="resolved tooltip" title="${_('Resolved by comment #{}').format(comment.resolved.comment_id)}">
33 <div class="resolved tooltip" title="${_('Resolved by comment #{}').format(comment.resolved.comment_id)}">
34 <a href="#comment-${comment.resolved.comment_id}">${comment.comment_type}</a>
34 <a href="#comment-${comment.resolved.comment_id}">${comment.comment_type}</a>
35 </div>
35 </div>
36 % else:
36 % else:
37 <div class="resolved tooltip" style="display: none">
37 <div class="resolved tooltip" style="display: none">
38 <span>${comment.comment_type}</span>
38 <span>${comment.comment_type}</span>
39 </div>
39 </div>
40 <div class="resolve tooltip" onclick="return Rhodecode.comments.createResolutionComment(${comment.comment_id});" title="${_('Click to resolve this comment')}">
40 <div class="resolve tooltip" onclick="return Rhodecode.comments.createResolutionComment(${comment.comment_id});" title="${_('Click to resolve this comment')}">
41 ${comment.comment_type}
41 ${comment.comment_type}
42 </div>
42 </div>
43 % endif
43 % endif
44 % else:
44 % else:
45 % if comment.resolved_comment:
45 % if comment.resolved_comment:
46 fix
46 fix
47 <a href="#comment-${comment.resolved_comment.comment_id}" onclick="Rhodecode.comments.scrollToComment($('#comment-${comment.resolved_comment.comment_id}'), 0, ${h.json.dumps(comment.resolved_comment.outdated)})">
47 <a href="#comment-${comment.resolved_comment.comment_id}" onclick="Rhodecode.comments.scrollToComment($('#comment-${comment.resolved_comment.comment_id}'), 0, ${h.json.dumps(comment.resolved_comment.outdated)})">
48 <span style="text-decoration: line-through">#${comment.resolved_comment.comment_id}</span>
48 <span style="text-decoration: line-through">#${comment.resolved_comment.comment_id}</span>
49 </a>
49 </a>
50 % else:
50 % else:
51 ${comment.comment_type or 'note'}
51 ${comment.comment_type or 'note'}
52 % endif
52 % endif
53 % endif
53 % endif
54 </div>
54 </div>
55 </div>
55 </div>
56
56
57 <div class="author ${'author-inline' if inline else 'author-general'}">
57 <div class="author ${'author-inline' if inline else 'author-general'}">
58 ${base.gravatar_with_user(comment.author.email, 16, tooltip=True)}
58 ${base.gravatar_with_user(comment.author.email, 16, tooltip=True)}
59 </div>
59 </div>
60 <div class="date">
60 <div class="date">
61 ${h.age_component(comment.modified_at, time_is_local=True)}
61 ${h.age_component(comment.modified_at, time_is_local=True)}
62 </div>
62 </div>
63 % if inline:
63 % if inline:
64 <span></span>
64 <span></span>
65 % else:
65 % else:
66 <div class="status-change">
66 <div class="status-change">
67 % if comment.pull_request:
67 % if comment.pull_request:
68 <a href="${h.route_path('pullrequest_show',repo_name=comment.pull_request.target_repo.repo_name,pull_request_id=comment.pull_request.pull_request_id)}">
68 <a href="${h.route_path('pullrequest_show',repo_name=comment.pull_request.target_repo.repo_name,pull_request_id=comment.pull_request.pull_request_id)}">
69 % if comment.status_change:
69 % if comment.status_change:
70 ${_('pull request !{}').format(comment.pull_request.pull_request_id)}:
70 ${_('pull request !{}').format(comment.pull_request.pull_request_id)}:
71 % else:
71 % else:
72 ${_('pull request !{}').format(comment.pull_request.pull_request_id)}
72 ${_('pull request !{}').format(comment.pull_request.pull_request_id)}
73 % endif
73 % endif
74 </a>
74 </a>
75 % else:
75 % else:
76 % if comment.status_change:
76 % if comment.status_change:
77 ${_('Status change on commit')}:
77 ${_('Status change on commit')}:
78 % endif
78 % endif
79 % endif
79 % endif
80 </div>
80 </div>
81 % endif
81 % endif
82
82
83 % if comment.status_change:
83 % if comment.status_change:
84 <i class="icon-circle review-status-${comment.status_change[0].status}"></i>
84 <i class="icon-circle review-status-${comment.status_change[0].status}"></i>
85 <div title="${_('Commit status')}" class="changeset-status-lbl">
85 <div title="${_('Commit status')}" class="changeset-status-lbl">
86 ${comment.status_change[0].status_lbl}
86 ${comment.status_change[0].status_lbl}
87 </div>
87 </div>
88 % endif
88 % endif
89
89
90 <a class="permalink" href="#comment-${comment.comment_id}"> &para;</a>
90 <a class="permalink" href="#comment-${comment.comment_id}"> &para;</a>
91
91
92 <div class="comment-links-block">
92 <div class="comment-links-block">
93 % if comment.pull_request and comment.pull_request.author.user_id == comment.author.user_id:
93 % if comment.pull_request and comment.pull_request.author.user_id == comment.author.user_id:
94 <span class="tag authortag tooltip" title="${_('Pull request author')}">
94 <span class="tag authortag tooltip" title="${_('Pull request author')}">
95 ${_('author')}
95 ${_('author')}
96 </span>
96 </span>
97 |
97 |
98 % endif
98 % endif
99 % if inline:
99 % if inline:
100 <div class="pr-version-inline">
100 <div class="pr-version-inline">
101 <a href="${request.current_route_path(_query=dict(version=comment.pull_request_version_id), _anchor='comment-{}'.format(comment.comment_id))}">
101 <a href="${request.current_route_path(_query=dict(version=comment.pull_request_version_id), _anchor='comment-{}'.format(comment.comment_id))}">
102 % if outdated_at_ver:
102 % if outdated_at_ver:
103 <code class="pr-version-num" title="${_('Outdated comment from pull request version v{0}, latest v{1}').format(pr_index_ver, latest_ver)}">
103 <code class="pr-version-num" title="${_('Outdated comment from pull request version v{0}, latest v{1}').format(pr_index_ver, latest_ver)}">
104 outdated ${'v{}'.format(pr_index_ver)} |
104 outdated ${'v{}'.format(pr_index_ver)} |
105 </code>
105 </code>
106 % elif pr_index_ver:
106 % elif pr_index_ver:
107 <code class="pr-version-num" title="${_('Comment from pull request version v{0}, latest v{1}').format(pr_index_ver, latest_ver)}">
107 <code class="pr-version-num" title="${_('Comment from pull request version v{0}, latest v{1}').format(pr_index_ver, latest_ver)}">
108 ${'v{}'.format(pr_index_ver)} |
108 ${'v{}'.format(pr_index_ver)} |
109 </code>
109 </code>
110 % endif
110 % endif
111 </a>
111 </a>
112 </div>
112 </div>
113 % else:
113 % else:
114 % if comment.pull_request_version_id and pr_index_ver:
114 % if comment.pull_request_version_id and pr_index_ver:
115 |
115 |
116 <div class="pr-version">
116 <div class="pr-version">
117 % if comment.outdated:
117 % if comment.outdated:
118 <a href="?version=${comment.pull_request_version_id}#comment-${comment.comment_id}">
118 <a href="?version=${comment.pull_request_version_id}#comment-${comment.comment_id}">
119 ${_('Outdated comment from pull request version v{0}, latest v{1}').format(pr_index_ver, latest_ver)}
119 ${_('Outdated comment from pull request version v{0}, latest v{1}').format(pr_index_ver, latest_ver)}
120 </a>
120 </a>
121 % else:
121 % else:
122 <div title="${_('Comment from pull request version v{0}, latest v{1}').format(pr_index_ver, latest_ver)}">
122 <div title="${_('Comment from pull request version v{0}, latest v{1}').format(pr_index_ver, latest_ver)}">
123 <a href="${h.route_path('pullrequest_show',repo_name=comment.pull_request.target_repo.repo_name,pull_request_id=comment.pull_request.pull_request_id, version=comment.pull_request_version_id)}">
123 <a href="${h.route_path('pullrequest_show',repo_name=comment.pull_request.target_repo.repo_name,pull_request_id=comment.pull_request.pull_request_id, version=comment.pull_request_version_id)}">
124 <code class="pr-version-num">
124 <code class="pr-version-num">
125 ${'v{}'.format(pr_index_ver)}
125 ${'v{}'.format(pr_index_ver)}
126 </code>
126 </code>
127 </a>
127 </a>
128 </div>
128 </div>
129 % endif
129 % endif
130 </div>
130 </div>
131 % endif
131 % endif
132 % endif
132 % endif
133
133
134 ## show delete comment if it's not a PR (regular comments) or it's PR that is not closed
134 ## show delete comment if it's not a PR (regular comments) or it's PR that is not closed
135 ## only super-admin, repo admin OR comment owner can delete, also hide delete if currently viewed comment is outdated
135 ## only super-admin, repo admin OR comment owner can delete, also hide delete if currently viewed comment is outdated
136 %if not outdated_at_ver and (not comment.pull_request or (comment.pull_request and not comment.pull_request.is_closed())):
136 %if not outdated_at_ver and (not comment.pull_request or (comment.pull_request and not comment.pull_request.is_closed())):
137 ## permissions to delete
137 ## permissions to delete
138 %if c.is_super_admin or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or comment.author.user_id == c.rhodecode_user.user_id:
138 %if comment.immutable is False and (c.is_super_admin or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or comment.author.user_id == c.rhodecode_user.user_id):
139 ## TODO: dan: add edit comment here
139 ## TODO: dan: add edit comment here
140 <a onclick="return Rhodecode.comments.deleteComment(this);" class="delete-comment"> ${_('Delete')}</a>
140 <a onclick="return Rhodecode.comments.deleteComment(this);" class="delete-comment"> ${_('Delete')}</a>
141 %else:
141 %else:
142 <button class="btn-link" disabled="disabled"> ${_('Delete')}</button>
142 <button class="btn-link" disabled="disabled"> ${_('Delete')}</button>
143 %endif
143 %endif
144 %else:
144 %else:
145 <button class="btn-link" disabled="disabled"> ${_('Delete')}</button>
145 <button class="btn-link" disabled="disabled"> ${_('Delete')}</button>
146 %endif
146 %endif
147
147
148 % if outdated_at_ver:
148 % if outdated_at_ver:
149 | <a onclick="return Rhodecode.comments.prevOutdatedComment(this);" class="prev-comment"> ${_('Prev')}</a>
149 | <a onclick="return Rhodecode.comments.prevOutdatedComment(this);" class="prev-comment"> ${_('Prev')}</a>
150 | <a onclick="return Rhodecode.comments.nextOutdatedComment(this);" class="next-comment"> ${_('Next')}</a>
150 | <a onclick="return Rhodecode.comments.nextOutdatedComment(this);" class="next-comment"> ${_('Next')}</a>
151 % else:
151 % else:
152 | <a onclick="return Rhodecode.comments.prevComment(this);" class="prev-comment"> ${_('Prev')}</a>
152 | <a onclick="return Rhodecode.comments.prevComment(this);" class="prev-comment"> ${_('Prev')}</a>
153 | <a onclick="return Rhodecode.comments.nextComment(this);" class="next-comment"> ${_('Next')}</a>
153 | <a onclick="return Rhodecode.comments.nextComment(this);" class="next-comment"> ${_('Next')}</a>
154 % endif
154 % endif
155
155
156 </div>
156 </div>
157 </div>
157 </div>
158 <div class="text">
158 <div class="text">
159 ${h.render(comment.text, renderer=comment.renderer, mentions=True, repo_name=getattr(c, 'repo_name', None), active_pattern_entries=active_pattern_entries)}
159 ${h.render(comment.text, renderer=comment.renderer, mentions=True, repo_name=getattr(c, 'repo_name', None), active_pattern_entries=active_pattern_entries)}
160 </div>
160 </div>
161
161
162 </div>
162 </div>
163 </%def>
163 </%def>
164
164
165 ## generate main comments
165 ## generate main comments
166 <%def name="generate_comments(comments, include_pull_request=False, is_pull_request=False)">
166 <%def name="generate_comments(comments, include_pull_request=False, is_pull_request=False)">
167 <%
167 <%
168 active_pattern_entries = h.get_active_pattern_entries(getattr(c, 'repo_name', None))
168 active_pattern_entries = h.get_active_pattern_entries(getattr(c, 'repo_name', None))
169 %>
169 %>
170
170
171 <div class="general-comments" id="comments">
171 <div class="general-comments" id="comments">
172 %for comment in comments:
172 %for comment in comments:
173 <div id="comment-tr-${comment.comment_id}">
173 <div id="comment-tr-${comment.comment_id}">
174 ## only render comments that are not from pull request, or from
174 ## only render comments that are not from pull request, or from
175 ## pull request and a status change
175 ## pull request and a status change
176 %if not comment.pull_request or (comment.pull_request and comment.status_change) or include_pull_request:
176 %if not comment.pull_request or (comment.pull_request and comment.status_change) or include_pull_request:
177 ${comment_block(comment, active_pattern_entries=active_pattern_entries)}
177 ${comment_block(comment, active_pattern_entries=active_pattern_entries)}
178 %endif
178 %endif
179 </div>
179 </div>
180 %endfor
180 %endfor
181 ## to anchor ajax comments
181 ## to anchor ajax comments
182 <div id="injected_page_comments"></div>
182 <div id="injected_page_comments"></div>
183 </div>
183 </div>
184 </%def>
184 </%def>
185
185
186
186
187 <%def name="comments(post_url, cur_status, is_pull_request=False, is_compare=False, change_status=True, form_extras=None)">
187 <%def name="comments(post_url, cur_status, is_pull_request=False, is_compare=False, change_status=True, form_extras=None)">
188
188
189 <div class="comments">
189 <div class="comments">
190 <%
190 <%
191 if is_pull_request:
191 if is_pull_request:
192 placeholder = _('Leave a comment on this Pull Request.')
192 placeholder = _('Leave a comment on this Pull Request.')
193 elif is_compare:
193 elif is_compare:
194 placeholder = _('Leave a comment on {} commits in this range.').format(len(form_extras))
194 placeholder = _('Leave a comment on {} commits in this range.').format(len(form_extras))
195 else:
195 else:
196 placeholder = _('Leave a comment on this Commit.')
196 placeholder = _('Leave a comment on this Commit.')
197 %>
197 %>
198
198
199 % if c.rhodecode_user.username != h.DEFAULT_USER:
199 % if c.rhodecode_user.username != h.DEFAULT_USER:
200 <div class="js-template" id="cb-comment-general-form-template">
200 <div class="js-template" id="cb-comment-general-form-template">
201 ## template generated for injection
201 ## template generated for injection
202 ${comment_form(form_type='general', review_statuses=c.commit_statuses, form_extras=form_extras)}
202 ${comment_form(form_type='general', review_statuses=c.commit_statuses, form_extras=form_extras)}
203 </div>
203 </div>
204
204
205 <div id="cb-comment-general-form-placeholder" class="comment-form ac">
205 <div id="cb-comment-general-form-placeholder" class="comment-form ac">
206 ## inject form here
206 ## inject form here
207 </div>
207 </div>
208 <script type="text/javascript">
208 <script type="text/javascript">
209 var lineNo = 'general';
209 var lineNo = 'general';
210 var resolvesCommentId = null;
210 var resolvesCommentId = null;
211 var generalCommentForm = Rhodecode.comments.createGeneralComment(
211 var generalCommentForm = Rhodecode.comments.createGeneralComment(
212 lineNo, "${placeholder}", resolvesCommentId);
212 lineNo, "${placeholder}", resolvesCommentId);
213
213
214 // set custom success callback on rangeCommit
214 // set custom success callback on rangeCommit
215 % if is_compare:
215 % if is_compare:
216 generalCommentForm.setHandleFormSubmit(function(o) {
216 generalCommentForm.setHandleFormSubmit(function(o) {
217 var self = generalCommentForm;
217 var self = generalCommentForm;
218
218
219 var text = self.cm.getValue();
219 var text = self.cm.getValue();
220 var status = self.getCommentStatus();
220 var status = self.getCommentStatus();
221 var commentType = self.getCommentType();
221 var commentType = self.getCommentType();
222
222
223 if (text === "" && !status) {
223 if (text === "" && !status) {
224 return;
224 return;
225 }
225 }
226
226
227 // we can pick which commits we want to make the comment by
227 // we can pick which commits we want to make the comment by
228 // selecting them via click on preview pane, this will alter the hidden inputs
228 // selecting them via click on preview pane, this will alter the hidden inputs
229 var cherryPicked = $('#changeset_compare_view_content .compare_select.hl').length > 0;
229 var cherryPicked = $('#changeset_compare_view_content .compare_select.hl').length > 0;
230
230
231 var commitIds = [];
231 var commitIds = [];
232 $('#changeset_compare_view_content .compare_select').each(function(el) {
232 $('#changeset_compare_view_content .compare_select').each(function(el) {
233 var commitId = this.id.replace('row-', '');
233 var commitId = this.id.replace('row-', '');
234 if ($(this).hasClass('hl') || !cherryPicked) {
234 if ($(this).hasClass('hl') || !cherryPicked) {
235 $("input[data-commit-id='{0}']".format(commitId)).val(commitId);
235 $("input[data-commit-id='{0}']".format(commitId)).val(commitId);
236 commitIds.push(commitId);
236 commitIds.push(commitId);
237 } else {
237 } else {
238 $("input[data-commit-id='{0}']".format(commitId)).val('')
238 $("input[data-commit-id='{0}']".format(commitId)).val('')
239 }
239 }
240 });
240 });
241
241
242 self.setActionButtonsDisabled(true);
242 self.setActionButtonsDisabled(true);
243 self.cm.setOption("readOnly", true);
243 self.cm.setOption("readOnly", true);
244 var postData = {
244 var postData = {
245 'text': text,
245 'text': text,
246 'changeset_status': status,
246 'changeset_status': status,
247 'comment_type': commentType,
247 'comment_type': commentType,
248 'commit_ids': commitIds,
248 'commit_ids': commitIds,
249 'csrf_token': CSRF_TOKEN
249 'csrf_token': CSRF_TOKEN
250 };
250 };
251
251
252 var submitSuccessCallback = function(o) {
252 var submitSuccessCallback = function(o) {
253 location.reload(true);
253 location.reload(true);
254 };
254 };
255 var submitFailCallback = function(){
255 var submitFailCallback = function(){
256 self.resetCommentFormState(text)
256 self.resetCommentFormState(text)
257 };
257 };
258 self.submitAjaxPOST(
258 self.submitAjaxPOST(
259 self.submitUrl, postData, submitSuccessCallback, submitFailCallback);
259 self.submitUrl, postData, submitSuccessCallback, submitFailCallback);
260 });
260 });
261 % endif
261 % endif
262
262
263 </script>
263 </script>
264 % else:
264 % else:
265 ## form state when not logged in
265 ## form state when not logged in
266 <div class="comment-form ac">
266 <div class="comment-form ac">
267
267
268 <div class="comment-area">
268 <div class="comment-area">
269 <div class="comment-area-header">
269 <div class="comment-area-header">
270 <ul class="nav-links clearfix">
270 <ul class="nav-links clearfix">
271 <li class="active">
271 <li class="active">
272 <a class="disabled" href="#edit-btn" disabled="disabled" onclick="return false">${_('Write')}</a>
272 <a class="disabled" href="#edit-btn" disabled="disabled" onclick="return false">${_('Write')}</a>
273 </li>
273 </li>
274 <li class="">
274 <li class="">
275 <a class="disabled" href="#preview-btn" disabled="disabled" onclick="return false">${_('Preview')}</a>
275 <a class="disabled" href="#preview-btn" disabled="disabled" onclick="return false">${_('Preview')}</a>
276 </li>
276 </li>
277 </ul>
277 </ul>
278 </div>
278 </div>
279
279
280 <div class="comment-area-write" style="display: block;">
280 <div class="comment-area-write" style="display: block;">
281 <div id="edit-container">
281 <div id="edit-container">
282 <div style="padding: 40px 0">
282 <div style="padding: 40px 0">
283 ${_('You need to be logged in to leave comments.')}
283 ${_('You need to be logged in to leave comments.')}
284 <a href="${h.route_path('login', _query={'came_from': h.current_route_path(request)})}">${_('Login now')}</a>
284 <a href="${h.route_path('login', _query={'came_from': h.current_route_path(request)})}">${_('Login now')}</a>
285 </div>
285 </div>
286 </div>
286 </div>
287 <div id="preview-container" class="clearfix" style="display: none;">
287 <div id="preview-container" class="clearfix" style="display: none;">
288 <div id="preview-box" class="preview-box"></div>
288 <div id="preview-box" class="preview-box"></div>
289 </div>
289 </div>
290 </div>
290 </div>
291
291
292 <div class="comment-area-footer">
292 <div class="comment-area-footer">
293 <div class="toolbar">
293 <div class="toolbar">
294 <div class="toolbar-text">
294 <div class="toolbar-text">
295 </div>
295 </div>
296 </div>
296 </div>
297 </div>
297 </div>
298 </div>
298 </div>
299
299
300 <div class="comment-footer">
300 <div class="comment-footer">
301 </div>
301 </div>
302
302
303 </div>
303 </div>
304 % endif
304 % endif
305
305
306 <script type="text/javascript">
306 <script type="text/javascript">
307 bindToggleButtons();
307 bindToggleButtons();
308 </script>
308 </script>
309 </div>
309 </div>
310 </%def>
310 </%def>
311
311
312
312
313 <%def name="comment_form(form_type, form_id='', lineno_id='{1}', review_statuses=None, form_extras=None)">
313 <%def name="comment_form(form_type, form_id='', lineno_id='{1}', review_statuses=None, form_extras=None)">
314
314
315 ## comment injected based on assumption that user is logged in
315 ## comment injected based on assumption that user is logged in
316 <form ${('id="{}"'.format(form_id) if form_id else '') |n} action="#" method="GET">
316 <form ${('id="{}"'.format(form_id) if form_id else '') |n} action="#" method="GET">
317
317
318 <div class="comment-area">
318 <div class="comment-area">
319 <div class="comment-area-header">
319 <div class="comment-area-header">
320 <div class="pull-left">
320 <div class="pull-left">
321 <ul class="nav-links clearfix">
321 <ul class="nav-links clearfix">
322 <li class="active">
322 <li class="active">
323 <a href="#edit-btn" tabindex="-1" id="edit-btn_${lineno_id}">${_('Write')}</a>
323 <a href="#edit-btn" tabindex="-1" id="edit-btn_${lineno_id}">${_('Write')}</a>
324 </li>
324 </li>
325 <li class="">
325 <li class="">
326 <a href="#preview-btn" tabindex="-1" id="preview-btn_${lineno_id}">${_('Preview')}</a>
326 <a href="#preview-btn" tabindex="-1" id="preview-btn_${lineno_id}">${_('Preview')}</a>
327 </li>
327 </li>
328 </ul>
328 </ul>
329 </div>
329 </div>
330 <div class="pull-right">
330 <div class="pull-right">
331 <span class="comment-area-text">${_('Mark as')}:</span>
331 <span class="comment-area-text">${_('Mark as')}:</span>
332 <select class="comment-type" id="comment_type_${lineno_id}" name="comment_type">
332 <select class="comment-type" id="comment_type_${lineno_id}" name="comment_type">
333 % for val in c.visual.comment_types:
333 % for val in c.visual.comment_types:
334 <option value="${val}">${val.upper()}</option>
334 <option value="${val}">${val.upper()}</option>
335 % endfor
335 % endfor
336 </select>
336 </select>
337 </div>
337 </div>
338 </div>
338 </div>
339
339
340 <div class="comment-area-write" style="display: block;">
340 <div class="comment-area-write" style="display: block;">
341 <div id="edit-container_${lineno_id}">
341 <div id="edit-container_${lineno_id}">
342 <textarea id="text_${lineno_id}" name="text" class="comment-block-ta ac-input"></textarea>
342 <textarea id="text_${lineno_id}" name="text" class="comment-block-ta ac-input"></textarea>
343 </div>
343 </div>
344 <div id="preview-container_${lineno_id}" class="clearfix" style="display: none;">
344 <div id="preview-container_${lineno_id}" class="clearfix" style="display: none;">
345 <div id="preview-box_${lineno_id}" class="preview-box"></div>
345 <div id="preview-box_${lineno_id}" class="preview-box"></div>
346 </div>
346 </div>
347 </div>
347 </div>
348
348
349 <div class="comment-area-footer comment-attachment-uploader">
349 <div class="comment-area-footer comment-attachment-uploader">
350 <div class="toolbar">
350 <div class="toolbar">
351
351
352 <div class="comment-attachment-text">
352 <div class="comment-attachment-text">
353 <div class="dropzone-text">
353 <div class="dropzone-text">
354 ${_("Drag'n Drop files here or")} <span class="link pick-attachment">${_('Choose your files')}</span>.<br>
354 ${_("Drag'n Drop files here or")} <span class="link pick-attachment">${_('Choose your files')}</span>.<br>
355 </div>
355 </div>
356 <div class="dropzone-upload" style="display:none">
356 <div class="dropzone-upload" style="display:none">
357 <i class="icon-spin animate-spin"></i> ${_('uploading...')}
357 <i class="icon-spin animate-spin"></i> ${_('uploading...')}
358 </div>
358 </div>
359 </div>
359 </div>
360
360
361 ## comments dropzone template, empty on purpose
361 ## comments dropzone template, empty on purpose
362 <div style="display: none" class="comment-attachment-uploader-template">
362 <div style="display: none" class="comment-attachment-uploader-template">
363 <div class="dz-file-preview" style="margin: 0">
363 <div class="dz-file-preview" style="margin: 0">
364 <div class="dz-error-message"></div>
364 <div class="dz-error-message"></div>
365 </div>
365 </div>
366 </div>
366 </div>
367
367
368 </div>
368 </div>
369 </div>
369 </div>
370 </div>
370 </div>
371
371
372 <div class="comment-footer">
372 <div class="comment-footer">
373
373
374 ## inject extra inputs into the form
374 ## inject extra inputs into the form
375 % if form_extras and isinstance(form_extras, (list, tuple)):
375 % if form_extras and isinstance(form_extras, (list, tuple)):
376 <div id="comment_form_extras">
376 <div id="comment_form_extras">
377 % for form_ex_el in form_extras:
377 % for form_ex_el in form_extras:
378 ${form_ex_el|n}
378 ${form_ex_el|n}
379 % endfor
379 % endfor
380 </div>
380 </div>
381 % endif
381 % endif
382
382
383 <div class="action-buttons">
383 <div class="action-buttons">
384 % if form_type != 'inline':
384 % if form_type != 'inline':
385 <div class="action-buttons-extra"></div>
385 <div class="action-buttons-extra"></div>
386 % endif
386 % endif
387
387
388 <input class="btn btn-success comment-button-input" id="save_${lineno_id}" name="save" type="submit" value="${_('Comment')}">
388 <input class="btn btn-success comment-button-input" id="save_${lineno_id}" name="save" type="submit" value="${_('Comment')}">
389
389
390 ## inline for has a file, and line-number together with cancel hide button.
390 ## inline for has a file, and line-number together with cancel hide button.
391 % if form_type == 'inline':
391 % if form_type == 'inline':
392 <input type="hidden" name="f_path" value="{0}">
392 <input type="hidden" name="f_path" value="{0}">
393 <input type="hidden" name="line" value="${lineno_id}">
393 <input type="hidden" name="line" value="${lineno_id}">
394 <button type="button" class="cb-comment-cancel" onclick="return Rhodecode.comments.cancelComment(this);">
394 <button type="button" class="cb-comment-cancel" onclick="return Rhodecode.comments.cancelComment(this);">
395 ${_('Cancel')}
395 ${_('Cancel')}
396 </button>
396 </button>
397 % endif
397 % endif
398 </div>
398 </div>
399
399
400 % if review_statuses:
400 % if review_statuses:
401 <div class="status_box">
401 <div class="status_box">
402 <select id="change_status_${lineno_id}" name="changeset_status">
402 <select id="change_status_${lineno_id}" name="changeset_status">
403 <option></option> ## Placeholder
403 <option></option> ## Placeholder
404 % for status, lbl in review_statuses:
404 % for status, lbl in review_statuses:
405 <option value="${status}" data-status="${status}">${lbl}</option>
405 <option value="${status}" data-status="${status}">${lbl}</option>
406 %if is_pull_request and change_status and status in ('approved', 'rejected'):
406 %if is_pull_request and change_status and status in ('approved', 'rejected'):
407 <option value="${status}_closed" data-status="${status}">${lbl} & ${_('Closed')}</option>
407 <option value="${status}_closed" data-status="${status}">${lbl} & ${_('Closed')}</option>
408 %endif
408 %endif
409 % endfor
409 % endfor
410 </select>
410 </select>
411 </div>
411 </div>
412 % endif
412 % endif
413
413
414 <div class="toolbar-text">
414 <div class="toolbar-text">
415 <% renderer_url = '<a href="%s">%s</a>' % (h.route_url('%s_help' % c.visual.default_renderer), c.visual.default_renderer.upper()) %>
415 <% renderer_url = '<a href="%s">%s</a>' % (h.route_url('%s_help' % c.visual.default_renderer), c.visual.default_renderer.upper()) %>
416 ${_('Comments parsed using {} syntax.').format(renderer_url)|n} <br/>
416 ${_('Comments parsed using {} syntax.').format(renderer_url)|n} <br/>
417 <span class="tooltip" title="${_('Use @username inside this text to send notification to this RhodeCode user')}">@mention</span>
417 <span class="tooltip" title="${_('Use @username inside this text to send notification to this RhodeCode user')}">@mention</span>
418 ${_('and')}
418 ${_('and')}
419 <span class="tooltip" title="${_('Start typing with / for certain actions to be triggered via text box.')}">`/` autocomplete</span>
419 <span class="tooltip" title="${_('Start typing with / for certain actions to be triggered via text box.')}">`/` autocomplete</span>
420 ${_('actions supported.')}
420 ${_('actions supported.')}
421 </div>
421 </div>
422 </div>
422 </div>
423
423
424 </form>
424 </form>
425
425
426 </%def> No newline at end of file
426 </%def>
General Comments 0
You need to be logged in to leave comments. Login now