##// END OF EJS Templates
pull-requests: expose version browsing of pull requests....
marcink -
r1255:952cdf08 default
parent child Browse files
Show More
@@ -1,983 +1,1003 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2012-2016 RhodeCode GmbH
3 # Copyright (C) 2012-2016 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 pull requests controller for rhodecode for initializing pull requests
22 pull requests controller for rhodecode for initializing pull requests
23 """
23 """
24 import types
24
25
25 import peppercorn
26 import peppercorn
26 import formencode
27 import formencode
27 import logging
28 import logging
28
29
30
29 from webob.exc import HTTPNotFound, HTTPForbidden, HTTPBadRequest
31 from webob.exc import HTTPNotFound, HTTPForbidden, HTTPBadRequest
30 from pylons import request, tmpl_context as c, url
32 from pylons import request, tmpl_context as c, url
31 from pylons.controllers.util import redirect
33 from pylons.controllers.util import redirect
32 from pylons.i18n.translation import _
34 from pylons.i18n.translation import _
33 from pyramid.threadlocal import get_current_registry
35 from pyramid.threadlocal import get_current_registry
34 from sqlalchemy.sql import func
36 from sqlalchemy.sql import func
35 from sqlalchemy.sql.expression import or_
37 from sqlalchemy.sql.expression import or_
36
38
37 from rhodecode import events
39 from rhodecode import events
38 from rhodecode.lib import auth, diffs, helpers as h, codeblocks
40 from rhodecode.lib import auth, diffs, helpers as h, codeblocks
39 from rhodecode.lib.ext_json import json
41 from rhodecode.lib.ext_json import json
40 from rhodecode.lib.base import (
42 from rhodecode.lib.base import (
41 BaseRepoController, render, vcs_operation_context)
43 BaseRepoController, render, vcs_operation_context)
42 from rhodecode.lib.auth import (
44 from rhodecode.lib.auth import (
43 LoginRequired, HasRepoPermissionAnyDecorator, NotAnonymous,
45 LoginRequired, HasRepoPermissionAnyDecorator, NotAnonymous,
44 HasAcceptedRepoType, XHRRequired)
46 HasAcceptedRepoType, XHRRequired)
45 from rhodecode.lib.channelstream import channelstream_request
47 from rhodecode.lib.channelstream import channelstream_request
46 from rhodecode.lib.compat import OrderedDict
48 from rhodecode.lib.compat import OrderedDict
47 from rhodecode.lib.utils import jsonify
49 from rhodecode.lib.utils import jsonify
48 from rhodecode.lib.utils2 import (
50 from rhodecode.lib.utils2 import (
49 safe_int, safe_str, str2bool, safe_unicode, StrictAttributeDict)
51 safe_int, safe_str, str2bool, safe_unicode)
50 from rhodecode.lib.vcs.backends.base import EmptyCommit, UpdateFailureReason
52 from rhodecode.lib.vcs.backends.base import (
53 EmptyCommit, UpdateFailureReason, EmptyRepository)
51 from rhodecode.lib.vcs.exceptions import (
54 from rhodecode.lib.vcs.exceptions import (
52 EmptyRepositoryError, CommitDoesNotExistError, RepositoryRequirementError,
55 EmptyRepositoryError, CommitDoesNotExistError, RepositoryRequirementError,
53 NodeDoesNotExistError)
56 NodeDoesNotExistError)
54
57
55 from rhodecode.model.changeset_status import ChangesetStatusModel
58 from rhodecode.model.changeset_status import ChangesetStatusModel
56 from rhodecode.model.comment import ChangesetCommentsModel
59 from rhodecode.model.comment import ChangesetCommentsModel
57 from rhodecode.model.db import (PullRequest, ChangesetStatus, ChangesetComment,
60 from rhodecode.model.db import (PullRequest, ChangesetStatus, ChangesetComment,
58 Repository, PullRequestVersion)
61 Repository, PullRequestVersion)
59 from rhodecode.model.forms import PullRequestForm
62 from rhodecode.model.forms import PullRequestForm
60 from rhodecode.model.meta import Session
63 from rhodecode.model.meta import Session
61 from rhodecode.model.pull_request import PullRequestModel
64 from rhodecode.model.pull_request import PullRequestModel
62
65
63 log = logging.getLogger(__name__)
66 log = logging.getLogger(__name__)
64
67
65
68
66 class PullrequestsController(BaseRepoController):
69 class PullrequestsController(BaseRepoController):
67 def __before__(self):
70 def __before__(self):
68 super(PullrequestsController, self).__before__()
71 super(PullrequestsController, self).__before__()
69
72
70 def _load_compare_data(self, pull_request, inline_comments, enable_comments=True):
73 def _load_compare_data(self, pull_request, inline_comments, enable_comments=True):
71 """
74 """
72 Load context data needed for generating compare diff
75 Load context data needed for generating compare diff
73
76
74 :param pull_request: object related to the request
77 :param pull_request: object related to the request
75 :param enable_comments: flag to determine if comments are included
78 :param enable_comments: flag to determine if comments are included
76 """
79 """
77 source_repo = pull_request.source_repo
80 source_repo = pull_request.source_repo
78 source_ref_id = pull_request.source_ref_parts.commit_id
81 source_ref_id = pull_request.source_ref_parts.commit_id
79
82
80 target_repo = pull_request.target_repo
83 target_repo = pull_request.target_repo
81 target_ref_id = pull_request.target_ref_parts.commit_id
84 target_ref_id = pull_request.target_ref_parts.commit_id
82
85
83 # despite opening commits for bookmarks/branches/tags, we always
86 # despite opening commits for bookmarks/branches/tags, we always
84 # convert this to rev to prevent changes after bookmark or branch change
87 # convert this to rev to prevent changes after bookmark or branch change
85 c.source_ref_type = 'rev'
88 c.source_ref_type = 'rev'
86 c.source_ref = source_ref_id
89 c.source_ref = source_ref_id
87
90
88 c.target_ref_type = 'rev'
91 c.target_ref_type = 'rev'
89 c.target_ref = target_ref_id
92 c.target_ref = target_ref_id
90
93
91 c.source_repo = source_repo
94 c.source_repo = source_repo
92 c.target_repo = target_repo
95 c.target_repo = target_repo
93
96
94 c.fulldiff = bool(request.GET.get('fulldiff'))
97 c.fulldiff = bool(request.GET.get('fulldiff'))
95
98
96 # diff_limit is the old behavior, will cut off the whole diff
99 # diff_limit is the old behavior, will cut off the whole diff
97 # if the limit is applied otherwise will just hide the
100 # if the limit is applied otherwise will just hide the
98 # big files from the front-end
101 # big files from the front-end
99 diff_limit = self.cut_off_limit_diff
102 diff_limit = self.cut_off_limit_diff
100 file_limit = self.cut_off_limit_file
103 file_limit = self.cut_off_limit_file
101
104
102 pre_load = ["author", "branch", "date", "message"]
105 pre_load = ["author", "branch", "date", "message"]
103
106
104 c.commit_ranges = []
107 c.commit_ranges = []
105 source_commit = EmptyCommit()
108 source_commit = EmptyCommit()
106 target_commit = EmptyCommit()
109 target_commit = EmptyCommit()
107 c.missing_requirements = False
110 c.missing_requirements = False
108 try:
111 try:
109 c.commit_ranges = [
112 c.commit_ranges = [
110 source_repo.get_commit(commit_id=rev, pre_load=pre_load)
113 source_repo.get_commit(commit_id=rev, pre_load=pre_load)
111 for rev in pull_request.revisions]
114 for rev in pull_request.revisions]
112
115
113 c.statuses = source_repo.statuses(
116 c.statuses = source_repo.statuses(
114 [x.raw_id for x in c.commit_ranges])
117 [x.raw_id for x in c.commit_ranges])
115
118
116 target_commit = source_repo.get_commit(
119 target_commit = source_repo.get_commit(
117 commit_id=safe_str(target_ref_id))
120 commit_id=safe_str(target_ref_id))
118 source_commit = source_repo.get_commit(
121 source_commit = source_repo.get_commit(
119 commit_id=safe_str(source_ref_id))
122 commit_id=safe_str(source_ref_id))
120 except RepositoryRequirementError:
123 except RepositoryRequirementError:
121 c.missing_requirements = True
124 c.missing_requirements = True
122
125
123 c.changes = {}
126 c.changes = {}
124 c.missing_commits = False
127 c.missing_commits = False
125 if (c.missing_requirements or
128 if (c.missing_requirements or
126 isinstance(source_commit, EmptyCommit) or
129 isinstance(source_commit, EmptyCommit) or
127 source_commit == target_commit):
130 source_commit == target_commit):
128 _parsed = []
131 _parsed = []
129 c.missing_commits = True
132 c.missing_commits = True
130 else:
133 else:
131 vcs_diff = PullRequestModel().get_diff(pull_request)
134 vcs_diff = PullRequestModel().get_diff(pull_request)
132 diff_processor = diffs.DiffProcessor(
135 diff_processor = diffs.DiffProcessor(
133 vcs_diff, format='newdiff', diff_limit=diff_limit,
136 vcs_diff, format='newdiff', diff_limit=diff_limit,
134 file_limit=file_limit, show_full_diff=c.fulldiff)
137 file_limit=file_limit, show_full_diff=c.fulldiff)
135 _parsed = diff_processor.prepare()
138 _parsed = diff_processor.prepare()
136
139
137 commit_changes = OrderedDict()
140 commit_changes = OrderedDict()
138 _parsed = diff_processor.prepare()
141 _parsed = diff_processor.prepare()
139 c.limited_diff = isinstance(_parsed, diffs.LimitedDiffContainer)
142 c.limited_diff = isinstance(_parsed, diffs.LimitedDiffContainer)
140
143
141 _parsed = diff_processor.prepare()
144 _parsed = diff_processor.prepare()
142
145
143 def _node_getter(commit):
146 def _node_getter(commit):
144 def get_node(fname):
147 def get_node(fname):
145 try:
148 try:
146 return commit.get_node(fname)
149 return commit.get_node(fname)
147 except NodeDoesNotExistError:
150 except NodeDoesNotExistError:
148 return None
151 return None
149 return get_node
152 return get_node
150
153
151 c.diffset = codeblocks.DiffSet(
154 c.diffset = codeblocks.DiffSet(
152 repo_name=c.repo_name,
155 repo_name=c.repo_name,
153 source_repo_name=c.source_repo.repo_name,
156 source_repo_name=c.source_repo.repo_name,
154 source_node_getter=_node_getter(target_commit),
157 source_node_getter=_node_getter(target_commit),
155 target_node_getter=_node_getter(source_commit),
158 target_node_getter=_node_getter(source_commit),
156 comments=inline_comments
159 comments=inline_comments
157 ).render_patchset(_parsed, target_commit.raw_id, source_commit.raw_id)
160 ).render_patchset(_parsed, target_commit.raw_id, source_commit.raw_id)
158
161
159 c.included_files = []
162 c.included_files = []
160 c.deleted_files = []
163 c.deleted_files = []
161
164
162 for f in _parsed:
165 for f in _parsed:
163 st = f['stats']
166 st = f['stats']
164 fid = h.FID('', f['filename'])
167 fid = h.FID('', f['filename'])
165 c.included_files.append(f['filename'])
168 c.included_files.append(f['filename'])
166
169
167 def _extract_ordering(self, request):
170 def _extract_ordering(self, request):
168 column_index = safe_int(request.GET.get('order[0][column]'))
171 column_index = safe_int(request.GET.get('order[0][column]'))
169 order_dir = request.GET.get('order[0][dir]', 'desc')
172 order_dir = request.GET.get('order[0][dir]', 'desc')
170 order_by = request.GET.get(
173 order_by = request.GET.get(
171 'columns[%s][data][sort]' % column_index, 'name_raw')
174 'columns[%s][data][sort]' % column_index, 'name_raw')
172 return order_by, order_dir
175 return order_by, order_dir
173
176
174 @LoginRequired()
177 @LoginRequired()
175 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
178 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
176 'repository.admin')
179 'repository.admin')
177 @HasAcceptedRepoType('git', 'hg')
180 @HasAcceptedRepoType('git', 'hg')
178 def show_all(self, repo_name):
181 def show_all(self, repo_name):
179 # filter types
182 # filter types
180 c.active = 'open'
183 c.active = 'open'
181 c.source = str2bool(request.GET.get('source'))
184 c.source = str2bool(request.GET.get('source'))
182 c.closed = str2bool(request.GET.get('closed'))
185 c.closed = str2bool(request.GET.get('closed'))
183 c.my = str2bool(request.GET.get('my'))
186 c.my = str2bool(request.GET.get('my'))
184 c.awaiting_review = str2bool(request.GET.get('awaiting_review'))
187 c.awaiting_review = str2bool(request.GET.get('awaiting_review'))
185 c.awaiting_my_review = str2bool(request.GET.get('awaiting_my_review'))
188 c.awaiting_my_review = str2bool(request.GET.get('awaiting_my_review'))
186 c.repo_name = repo_name
189 c.repo_name = repo_name
187
190
188 opened_by = None
191 opened_by = None
189 if c.my:
192 if c.my:
190 c.active = 'my'
193 c.active = 'my'
191 opened_by = [c.rhodecode_user.user_id]
194 opened_by = [c.rhodecode_user.user_id]
192
195
193 statuses = [PullRequest.STATUS_NEW, PullRequest.STATUS_OPEN]
196 statuses = [PullRequest.STATUS_NEW, PullRequest.STATUS_OPEN]
194 if c.closed:
197 if c.closed:
195 c.active = 'closed'
198 c.active = 'closed'
196 statuses = [PullRequest.STATUS_CLOSED]
199 statuses = [PullRequest.STATUS_CLOSED]
197
200
198 if c.awaiting_review and not c.source:
201 if c.awaiting_review and not c.source:
199 c.active = 'awaiting'
202 c.active = 'awaiting'
200 if c.source and not c.awaiting_review:
203 if c.source and not c.awaiting_review:
201 c.active = 'source'
204 c.active = 'source'
202 if c.awaiting_my_review:
205 if c.awaiting_my_review:
203 c.active = 'awaiting_my'
206 c.active = 'awaiting_my'
204
207
205 data = self._get_pull_requests_list(
208 data = self._get_pull_requests_list(
206 repo_name=repo_name, opened_by=opened_by, statuses=statuses)
209 repo_name=repo_name, opened_by=opened_by, statuses=statuses)
207 if not request.is_xhr:
210 if not request.is_xhr:
208 c.data = json.dumps(data['data'])
211 c.data = json.dumps(data['data'])
209 c.records_total = data['recordsTotal']
212 c.records_total = data['recordsTotal']
210 return render('/pullrequests/pullrequests.html')
213 return render('/pullrequests/pullrequests.html')
211 else:
214 else:
212 return json.dumps(data)
215 return json.dumps(data)
213
216
214 def _get_pull_requests_list(self, repo_name, opened_by, statuses):
217 def _get_pull_requests_list(self, repo_name, opened_by, statuses):
215 # pagination
218 # pagination
216 start = safe_int(request.GET.get('start'), 0)
219 start = safe_int(request.GET.get('start'), 0)
217 length = safe_int(request.GET.get('length'), c.visual.dashboard_items)
220 length = safe_int(request.GET.get('length'), c.visual.dashboard_items)
218 order_by, order_dir = self._extract_ordering(request)
221 order_by, order_dir = self._extract_ordering(request)
219
222
220 if c.awaiting_review:
223 if c.awaiting_review:
221 pull_requests = PullRequestModel().get_awaiting_review(
224 pull_requests = PullRequestModel().get_awaiting_review(
222 repo_name, source=c.source, opened_by=opened_by,
225 repo_name, source=c.source, opened_by=opened_by,
223 statuses=statuses, offset=start, length=length,
226 statuses=statuses, offset=start, length=length,
224 order_by=order_by, order_dir=order_dir)
227 order_by=order_by, order_dir=order_dir)
225 pull_requests_total_count = PullRequestModel(
228 pull_requests_total_count = PullRequestModel(
226 ).count_awaiting_review(
229 ).count_awaiting_review(
227 repo_name, source=c.source, statuses=statuses,
230 repo_name, source=c.source, statuses=statuses,
228 opened_by=opened_by)
231 opened_by=opened_by)
229 elif c.awaiting_my_review:
232 elif c.awaiting_my_review:
230 pull_requests = PullRequestModel().get_awaiting_my_review(
233 pull_requests = PullRequestModel().get_awaiting_my_review(
231 repo_name, source=c.source, opened_by=opened_by,
234 repo_name, source=c.source, opened_by=opened_by,
232 user_id=c.rhodecode_user.user_id, statuses=statuses,
235 user_id=c.rhodecode_user.user_id, statuses=statuses,
233 offset=start, length=length, order_by=order_by,
236 offset=start, length=length, order_by=order_by,
234 order_dir=order_dir)
237 order_dir=order_dir)
235 pull_requests_total_count = PullRequestModel(
238 pull_requests_total_count = PullRequestModel(
236 ).count_awaiting_my_review(
239 ).count_awaiting_my_review(
237 repo_name, source=c.source, user_id=c.rhodecode_user.user_id,
240 repo_name, source=c.source, user_id=c.rhodecode_user.user_id,
238 statuses=statuses, opened_by=opened_by)
241 statuses=statuses, opened_by=opened_by)
239 else:
242 else:
240 pull_requests = PullRequestModel().get_all(
243 pull_requests = PullRequestModel().get_all(
241 repo_name, source=c.source, opened_by=opened_by,
244 repo_name, source=c.source, opened_by=opened_by,
242 statuses=statuses, offset=start, length=length,
245 statuses=statuses, offset=start, length=length,
243 order_by=order_by, order_dir=order_dir)
246 order_by=order_by, order_dir=order_dir)
244 pull_requests_total_count = PullRequestModel().count_all(
247 pull_requests_total_count = PullRequestModel().count_all(
245 repo_name, source=c.source, statuses=statuses,
248 repo_name, source=c.source, statuses=statuses,
246 opened_by=opened_by)
249 opened_by=opened_by)
247
250
248 from rhodecode.lib.utils import PartialRenderer
251 from rhodecode.lib.utils import PartialRenderer
249 _render = PartialRenderer('data_table/_dt_elements.html')
252 _render = PartialRenderer('data_table/_dt_elements.html')
250 data = []
253 data = []
251 for pr in pull_requests:
254 for pr in pull_requests:
252 comments = ChangesetCommentsModel().get_all_comments(
255 comments = ChangesetCommentsModel().get_all_comments(
253 c.rhodecode_db_repo.repo_id, pull_request=pr)
256 c.rhodecode_db_repo.repo_id, pull_request=pr)
254
257
255 data.append({
258 data.append({
256 'name': _render('pullrequest_name',
259 'name': _render('pullrequest_name',
257 pr.pull_request_id, pr.target_repo.repo_name),
260 pr.pull_request_id, pr.target_repo.repo_name),
258 'name_raw': pr.pull_request_id,
261 'name_raw': pr.pull_request_id,
259 'status': _render('pullrequest_status',
262 'status': _render('pullrequest_status',
260 pr.calculated_review_status()),
263 pr.calculated_review_status()),
261 'title': _render(
264 'title': _render(
262 'pullrequest_title', pr.title, pr.description),
265 'pullrequest_title', pr.title, pr.description),
263 'description': h.escape(pr.description),
266 'description': h.escape(pr.description),
264 'updated_on': _render('pullrequest_updated_on',
267 'updated_on': _render('pullrequest_updated_on',
265 h.datetime_to_time(pr.updated_on)),
268 h.datetime_to_time(pr.updated_on)),
266 'updated_on_raw': h.datetime_to_time(pr.updated_on),
269 'updated_on_raw': h.datetime_to_time(pr.updated_on),
267 'created_on': _render('pullrequest_updated_on',
270 'created_on': _render('pullrequest_updated_on',
268 h.datetime_to_time(pr.created_on)),
271 h.datetime_to_time(pr.created_on)),
269 'created_on_raw': h.datetime_to_time(pr.created_on),
272 'created_on_raw': h.datetime_to_time(pr.created_on),
270 'author': _render('pullrequest_author',
273 'author': _render('pullrequest_author',
271 pr.author.full_contact, ),
274 pr.author.full_contact, ),
272 'author_raw': pr.author.full_name,
275 'author_raw': pr.author.full_name,
273 'comments': _render('pullrequest_comments', len(comments)),
276 'comments': _render('pullrequest_comments', len(comments)),
274 'comments_raw': len(comments),
277 'comments_raw': len(comments),
275 'closed': pr.is_closed(),
278 'closed': pr.is_closed(),
276 })
279 })
277 # json used to render the grid
280 # json used to render the grid
278 data = ({
281 data = ({
279 'data': data,
282 'data': data,
280 'recordsTotal': pull_requests_total_count,
283 'recordsTotal': pull_requests_total_count,
281 'recordsFiltered': pull_requests_total_count,
284 'recordsFiltered': pull_requests_total_count,
282 })
285 })
283 return data
286 return data
284
287
285 @LoginRequired()
288 @LoginRequired()
286 @NotAnonymous()
289 @NotAnonymous()
287 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
290 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
288 'repository.admin')
291 'repository.admin')
289 @HasAcceptedRepoType('git', 'hg')
292 @HasAcceptedRepoType('git', 'hg')
290 def index(self):
293 def index(self):
291 source_repo = c.rhodecode_db_repo
294 source_repo = c.rhodecode_db_repo
292
295
293 try:
296 try:
294 source_repo.scm_instance().get_commit()
297 source_repo.scm_instance().get_commit()
295 except EmptyRepositoryError:
298 except EmptyRepositoryError:
296 h.flash(h.literal(_('There are no commits yet')),
299 h.flash(h.literal(_('There are no commits yet')),
297 category='warning')
300 category='warning')
298 redirect(url('summary_home', repo_name=source_repo.repo_name))
301 redirect(url('summary_home', repo_name=source_repo.repo_name))
299
302
300 commit_id = request.GET.get('commit')
303 commit_id = request.GET.get('commit')
301 branch_ref = request.GET.get('branch')
304 branch_ref = request.GET.get('branch')
302 bookmark_ref = request.GET.get('bookmark')
305 bookmark_ref = request.GET.get('bookmark')
303
306
304 try:
307 try:
305 source_repo_data = PullRequestModel().generate_repo_data(
308 source_repo_data = PullRequestModel().generate_repo_data(
306 source_repo, commit_id=commit_id,
309 source_repo, commit_id=commit_id,
307 branch=branch_ref, bookmark=bookmark_ref)
310 branch=branch_ref, bookmark=bookmark_ref)
308 except CommitDoesNotExistError as e:
311 except CommitDoesNotExistError as e:
309 log.exception(e)
312 log.exception(e)
310 h.flash(_('Commit does not exist'), 'error')
313 h.flash(_('Commit does not exist'), 'error')
311 redirect(url('pullrequest_home', repo_name=source_repo.repo_name))
314 redirect(url('pullrequest_home', repo_name=source_repo.repo_name))
312
315
313 default_target_repo = source_repo
316 default_target_repo = source_repo
314
317
315 if source_repo.parent:
318 if source_repo.parent:
316 parent_vcs_obj = source_repo.parent.scm_instance()
319 parent_vcs_obj = source_repo.parent.scm_instance()
317 if parent_vcs_obj and not parent_vcs_obj.is_empty():
320 if parent_vcs_obj and not parent_vcs_obj.is_empty():
318 # change default if we have a parent repo
321 # change default if we have a parent repo
319 default_target_repo = source_repo.parent
322 default_target_repo = source_repo.parent
320
323
321 target_repo_data = PullRequestModel().generate_repo_data(
324 target_repo_data = PullRequestModel().generate_repo_data(
322 default_target_repo)
325 default_target_repo)
323
326
324 selected_source_ref = source_repo_data['refs']['selected_ref']
327 selected_source_ref = source_repo_data['refs']['selected_ref']
325
328
326 title_source_ref = selected_source_ref.split(':', 2)[1]
329 title_source_ref = selected_source_ref.split(':', 2)[1]
327 c.default_title = PullRequestModel().generate_pullrequest_title(
330 c.default_title = PullRequestModel().generate_pullrequest_title(
328 source=source_repo.repo_name,
331 source=source_repo.repo_name,
329 source_ref=title_source_ref,
332 source_ref=title_source_ref,
330 target=default_target_repo.repo_name
333 target=default_target_repo.repo_name
331 )
334 )
332
335
333 c.default_repo_data = {
336 c.default_repo_data = {
334 'source_repo_name': source_repo.repo_name,
337 'source_repo_name': source_repo.repo_name,
335 'source_refs_json': json.dumps(source_repo_data),
338 'source_refs_json': json.dumps(source_repo_data),
336 'target_repo_name': default_target_repo.repo_name,
339 'target_repo_name': default_target_repo.repo_name,
337 'target_refs_json': json.dumps(target_repo_data),
340 'target_refs_json': json.dumps(target_repo_data),
338 }
341 }
339 c.default_source_ref = selected_source_ref
342 c.default_source_ref = selected_source_ref
340
343
341 return render('/pullrequests/pullrequest.html')
344 return render('/pullrequests/pullrequest.html')
342
345
343 @LoginRequired()
346 @LoginRequired()
344 @NotAnonymous()
347 @NotAnonymous()
345 @XHRRequired()
348 @XHRRequired()
346 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
349 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
347 'repository.admin')
350 'repository.admin')
348 @jsonify
351 @jsonify
349 def get_repo_refs(self, repo_name, target_repo_name):
352 def get_repo_refs(self, repo_name, target_repo_name):
350 repo = Repository.get_by_repo_name(target_repo_name)
353 repo = Repository.get_by_repo_name(target_repo_name)
351 if not repo:
354 if not repo:
352 raise HTTPNotFound
355 raise HTTPNotFound
353 return PullRequestModel().generate_repo_data(repo)
356 return PullRequestModel().generate_repo_data(repo)
354
357
355 @LoginRequired()
358 @LoginRequired()
356 @NotAnonymous()
359 @NotAnonymous()
357 @XHRRequired()
360 @XHRRequired()
358 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
361 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
359 'repository.admin')
362 'repository.admin')
360 @jsonify
363 @jsonify
361 def get_repo_destinations(self, repo_name):
364 def get_repo_destinations(self, repo_name):
362 repo = Repository.get_by_repo_name(repo_name)
365 repo = Repository.get_by_repo_name(repo_name)
363 if not repo:
366 if not repo:
364 raise HTTPNotFound
367 raise HTTPNotFound
365 filter_query = request.GET.get('query')
368 filter_query = request.GET.get('query')
366
369
367 query = Repository.query() \
370 query = Repository.query() \
368 .order_by(func.length(Repository.repo_name)) \
371 .order_by(func.length(Repository.repo_name)) \
369 .filter(or_(
372 .filter(or_(
370 Repository.repo_name == repo.repo_name,
373 Repository.repo_name == repo.repo_name,
371 Repository.fork_id == repo.repo_id))
374 Repository.fork_id == repo.repo_id))
372
375
373 if filter_query:
376 if filter_query:
374 ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
377 ilike_expression = u'%{}%'.format(safe_unicode(filter_query))
375 query = query.filter(
378 query = query.filter(
376 Repository.repo_name.ilike(ilike_expression))
379 Repository.repo_name.ilike(ilike_expression))
377
380
378 add_parent = False
381 add_parent = False
379 if repo.parent:
382 if repo.parent:
380 if filter_query in repo.parent.repo_name:
383 if filter_query in repo.parent.repo_name:
381 parent_vcs_obj = repo.parent.scm_instance()
384 parent_vcs_obj = repo.parent.scm_instance()
382 if parent_vcs_obj and not parent_vcs_obj.is_empty():
385 if parent_vcs_obj and not parent_vcs_obj.is_empty():
383 add_parent = True
386 add_parent = True
384
387
385 limit = 20 - 1 if add_parent else 20
388 limit = 20 - 1 if add_parent else 20
386 all_repos = query.limit(limit).all()
389 all_repos = query.limit(limit).all()
387 if add_parent:
390 if add_parent:
388 all_repos += [repo.parent]
391 all_repos += [repo.parent]
389
392
390 repos = []
393 repos = []
391 for obj in self.scm_model.get_repos(all_repos):
394 for obj in self.scm_model.get_repos(all_repos):
392 repos.append({
395 repos.append({
393 'id': obj['name'],
396 'id': obj['name'],
394 'text': obj['name'],
397 'text': obj['name'],
395 'type': 'repo',
398 'type': 'repo',
396 'obj': obj['dbrepo']
399 'obj': obj['dbrepo']
397 })
400 })
398
401
399 data = {
402 data = {
400 'more': False,
403 'more': False,
401 'results': [{
404 'results': [{
402 'text': _('Repositories'),
405 'text': _('Repositories'),
403 'children': repos
406 'children': repos
404 }] if repos else []
407 }] if repos else []
405 }
408 }
406 return data
409 return data
407
410
408 @LoginRequired()
411 @LoginRequired()
409 @NotAnonymous()
412 @NotAnonymous()
410 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
413 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
411 'repository.admin')
414 'repository.admin')
412 @HasAcceptedRepoType('git', 'hg')
415 @HasAcceptedRepoType('git', 'hg')
413 @auth.CSRFRequired()
416 @auth.CSRFRequired()
414 def create(self, repo_name):
417 def create(self, repo_name):
415 repo = Repository.get_by_repo_name(repo_name)
418 repo = Repository.get_by_repo_name(repo_name)
416 if not repo:
419 if not repo:
417 raise HTTPNotFound
420 raise HTTPNotFound
418
421
419 controls = peppercorn.parse(request.POST.items())
422 controls = peppercorn.parse(request.POST.items())
420
423
421 try:
424 try:
422 _form = PullRequestForm(repo.repo_id)().to_python(controls)
425 _form = PullRequestForm(repo.repo_id)().to_python(controls)
423 except formencode.Invalid as errors:
426 except formencode.Invalid as errors:
424 if errors.error_dict.get('revisions'):
427 if errors.error_dict.get('revisions'):
425 msg = 'Revisions: %s' % errors.error_dict['revisions']
428 msg = 'Revisions: %s' % errors.error_dict['revisions']
426 elif errors.error_dict.get('pullrequest_title'):
429 elif errors.error_dict.get('pullrequest_title'):
427 msg = _('Pull request requires a title with min. 3 chars')
430 msg = _('Pull request requires a title with min. 3 chars')
428 else:
431 else:
429 msg = _('Error creating pull request: {}').format(errors)
432 msg = _('Error creating pull request: {}').format(errors)
430 log.exception(msg)
433 log.exception(msg)
431 h.flash(msg, 'error')
434 h.flash(msg, 'error')
432
435
433 # would rather just go back to form ...
436 # would rather just go back to form ...
434 return redirect(url('pullrequest_home', repo_name=repo_name))
437 return redirect(url('pullrequest_home', repo_name=repo_name))
435
438
436 source_repo = _form['source_repo']
439 source_repo = _form['source_repo']
437 source_ref = _form['source_ref']
440 source_ref = _form['source_ref']
438 target_repo = _form['target_repo']
441 target_repo = _form['target_repo']
439 target_ref = _form['target_ref']
442 target_ref = _form['target_ref']
440 commit_ids = _form['revisions'][::-1]
443 commit_ids = _form['revisions'][::-1]
441 reviewers = [
444 reviewers = [
442 (r['user_id'], r['reasons']) for r in _form['review_members']]
445 (r['user_id'], r['reasons']) for r in _form['review_members']]
443
446
444 # find the ancestor for this pr
447 # find the ancestor for this pr
445 source_db_repo = Repository.get_by_repo_name(_form['source_repo'])
448 source_db_repo = Repository.get_by_repo_name(_form['source_repo'])
446 target_db_repo = Repository.get_by_repo_name(_form['target_repo'])
449 target_db_repo = Repository.get_by_repo_name(_form['target_repo'])
447
450
448 source_scm = source_db_repo.scm_instance()
451 source_scm = source_db_repo.scm_instance()
449 target_scm = target_db_repo.scm_instance()
452 target_scm = target_db_repo.scm_instance()
450
453
451 source_commit = source_scm.get_commit(source_ref.split(':')[-1])
454 source_commit = source_scm.get_commit(source_ref.split(':')[-1])
452 target_commit = target_scm.get_commit(target_ref.split(':')[-1])
455 target_commit = target_scm.get_commit(target_ref.split(':')[-1])
453
456
454 ancestor = source_scm.get_common_ancestor(
457 ancestor = source_scm.get_common_ancestor(
455 source_commit.raw_id, target_commit.raw_id, target_scm)
458 source_commit.raw_id, target_commit.raw_id, target_scm)
456
459
457 target_ref_type, target_ref_name, __ = _form['target_ref'].split(':')
460 target_ref_type, target_ref_name, __ = _form['target_ref'].split(':')
458 target_ref = ':'.join((target_ref_type, target_ref_name, ancestor))
461 target_ref = ':'.join((target_ref_type, target_ref_name, ancestor))
459
462
460 pullrequest_title = _form['pullrequest_title']
463 pullrequest_title = _form['pullrequest_title']
461 title_source_ref = source_ref.split(':', 2)[1]
464 title_source_ref = source_ref.split(':', 2)[1]
462 if not pullrequest_title:
465 if not pullrequest_title:
463 pullrequest_title = PullRequestModel().generate_pullrequest_title(
466 pullrequest_title = PullRequestModel().generate_pullrequest_title(
464 source=source_repo,
467 source=source_repo,
465 source_ref=title_source_ref,
468 source_ref=title_source_ref,
466 target=target_repo
469 target=target_repo
467 )
470 )
468
471
469 description = _form['pullrequest_desc']
472 description = _form['pullrequest_desc']
470 try:
473 try:
471 pull_request = PullRequestModel().create(
474 pull_request = PullRequestModel().create(
472 c.rhodecode_user.user_id, source_repo, source_ref, target_repo,
475 c.rhodecode_user.user_id, source_repo, source_ref, target_repo,
473 target_ref, commit_ids, reviewers, pullrequest_title,
476 target_ref, commit_ids, reviewers, pullrequest_title,
474 description
477 description
475 )
478 )
476 Session().commit()
479 Session().commit()
477 h.flash(_('Successfully opened new pull request'),
480 h.flash(_('Successfully opened new pull request'),
478 category='success')
481 category='success')
479 except Exception as e:
482 except Exception as e:
480 msg = _('Error occurred during sending pull request')
483 msg = _('Error occurred during sending pull request')
481 log.exception(msg)
484 log.exception(msg)
482 h.flash(msg, category='error')
485 h.flash(msg, category='error')
483 return redirect(url('pullrequest_home', repo_name=repo_name))
486 return redirect(url('pullrequest_home', repo_name=repo_name))
484
487
485 return redirect(url('pullrequest_show', repo_name=target_repo,
488 return redirect(url('pullrequest_show', repo_name=target_repo,
486 pull_request_id=pull_request.pull_request_id))
489 pull_request_id=pull_request.pull_request_id))
487
490
488 @LoginRequired()
491 @LoginRequired()
489 @NotAnonymous()
492 @NotAnonymous()
490 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
493 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
491 'repository.admin')
494 'repository.admin')
492 @auth.CSRFRequired()
495 @auth.CSRFRequired()
493 @jsonify
496 @jsonify
494 def update(self, repo_name, pull_request_id):
497 def update(self, repo_name, pull_request_id):
495 pull_request_id = safe_int(pull_request_id)
498 pull_request_id = safe_int(pull_request_id)
496 pull_request = PullRequest.get_or_404(pull_request_id)
499 pull_request = PullRequest.get_or_404(pull_request_id)
497 # only owner or admin can update it
500 # only owner or admin can update it
498 allowed_to_update = PullRequestModel().check_user_update(
501 allowed_to_update = PullRequestModel().check_user_update(
499 pull_request, c.rhodecode_user)
502 pull_request, c.rhodecode_user)
500 if allowed_to_update:
503 if allowed_to_update:
501 controls = peppercorn.parse(request.POST.items())
504 controls = peppercorn.parse(request.POST.items())
502
505
503 if 'review_members' in controls:
506 if 'review_members' in controls:
504 self._update_reviewers(
507 self._update_reviewers(
505 pull_request_id, controls['review_members'])
508 pull_request_id, controls['review_members'])
506 elif str2bool(request.POST.get('update_commits', 'false')):
509 elif str2bool(request.POST.get('update_commits', 'false')):
507 self._update_commits(pull_request)
510 self._update_commits(pull_request)
508 elif str2bool(request.POST.get('close_pull_request', 'false')):
511 elif str2bool(request.POST.get('close_pull_request', 'false')):
509 self._reject_close(pull_request)
512 self._reject_close(pull_request)
510 elif str2bool(request.POST.get('edit_pull_request', 'false')):
513 elif str2bool(request.POST.get('edit_pull_request', 'false')):
511 self._edit_pull_request(pull_request)
514 self._edit_pull_request(pull_request)
512 else:
515 else:
513 raise HTTPBadRequest()
516 raise HTTPBadRequest()
514 return True
517 return True
515 raise HTTPForbidden()
518 raise HTTPForbidden()
516
519
517 def _edit_pull_request(self, pull_request):
520 def _edit_pull_request(self, pull_request):
518 try:
521 try:
519 PullRequestModel().edit(
522 PullRequestModel().edit(
520 pull_request, request.POST.get('title'),
523 pull_request, request.POST.get('title'),
521 request.POST.get('description'))
524 request.POST.get('description'))
522 except ValueError:
525 except ValueError:
523 msg = _(u'Cannot update closed pull requests.')
526 msg = _(u'Cannot update closed pull requests.')
524 h.flash(msg, category='error')
527 h.flash(msg, category='error')
525 return
528 return
526 else:
529 else:
527 Session().commit()
530 Session().commit()
528
531
529 msg = _(u'Pull request title & description updated.')
532 msg = _(u'Pull request title & description updated.')
530 h.flash(msg, category='success')
533 h.flash(msg, category='success')
531 return
534 return
532
535
533 def _update_commits(self, pull_request):
536 def _update_commits(self, pull_request):
534 resp = PullRequestModel().update_commits(pull_request)
537 resp = PullRequestModel().update_commits(pull_request)
535
538
536 if resp.executed:
539 if resp.executed:
537 msg = _(
540 msg = _(
538 u'Pull request updated to "{source_commit_id}" with '
541 u'Pull request updated to "{source_commit_id}" with '
539 u'{count_added} added, {count_removed} removed commits.')
542 u'{count_added} added, {count_removed} removed commits.')
540 msg = msg.format(
543 msg = msg.format(
541 source_commit_id=pull_request.source_ref_parts.commit_id,
544 source_commit_id=pull_request.source_ref_parts.commit_id,
542 count_added=len(resp.changes.added),
545 count_added=len(resp.changes.added),
543 count_removed=len(resp.changes.removed))
546 count_removed=len(resp.changes.removed))
544 h.flash(msg, category='success')
547 h.flash(msg, category='success')
545
548
546 registry = get_current_registry()
549 registry = get_current_registry()
547 rhodecode_plugins = getattr(registry, 'rhodecode_plugins', {})
550 rhodecode_plugins = getattr(registry, 'rhodecode_plugins', {})
548 channelstream_config = rhodecode_plugins.get('channelstream', {})
551 channelstream_config = rhodecode_plugins.get('channelstream', {})
549 if channelstream_config.get('enabled'):
552 if channelstream_config.get('enabled'):
550 message = msg + (
553 message = msg + (
551 ' - <a onclick="window.location.reload()">'
554 ' - <a onclick="window.location.reload()">'
552 '<strong>{}</strong></a>'.format(_('Reload page')))
555 '<strong>{}</strong></a>'.format(_('Reload page')))
553 channel = '/repo${}$/pr/{}'.format(
556 channel = '/repo${}$/pr/{}'.format(
554 pull_request.target_repo.repo_name,
557 pull_request.target_repo.repo_name,
555 pull_request.pull_request_id
558 pull_request.pull_request_id
556 )
559 )
557 payload = {
560 payload = {
558 'type': 'message',
561 'type': 'message',
559 'user': 'system',
562 'user': 'system',
560 'exclude_users': [request.user.username],
563 'exclude_users': [request.user.username],
561 'channel': channel,
564 'channel': channel,
562 'message': {
565 'message': {
563 'message': message,
566 'message': message,
564 'level': 'success',
567 'level': 'success',
565 'topic': '/notifications'
568 'topic': '/notifications'
566 }
569 }
567 }
570 }
568 channelstream_request(
571 channelstream_request(
569 channelstream_config, [payload], '/message',
572 channelstream_config, [payload], '/message',
570 raise_exc=False)
573 raise_exc=False)
571 else:
574 else:
572 msg = PullRequestModel.UPDATE_STATUS_MESSAGES[resp.reason]
575 msg = PullRequestModel.UPDATE_STATUS_MESSAGES[resp.reason]
573 warning_reasons = [
576 warning_reasons = [
574 UpdateFailureReason.NO_CHANGE,
577 UpdateFailureReason.NO_CHANGE,
575 UpdateFailureReason.WRONG_REF_TPYE,
578 UpdateFailureReason.WRONG_REF_TPYE,
576 ]
579 ]
577 category = 'warning' if resp.reason in warning_reasons else 'error'
580 category = 'warning' if resp.reason in warning_reasons else 'error'
578 h.flash(msg, category=category)
581 h.flash(msg, category=category)
579
582
580 @auth.CSRFRequired()
583 @auth.CSRFRequired()
581 @LoginRequired()
584 @LoginRequired()
582 @NotAnonymous()
585 @NotAnonymous()
583 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
586 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
584 'repository.admin')
587 'repository.admin')
585 def merge(self, repo_name, pull_request_id):
588 def merge(self, repo_name, pull_request_id):
586 """
589 """
587 POST /{repo_name}/pull-request/{pull_request_id}
590 POST /{repo_name}/pull-request/{pull_request_id}
588
591
589 Merge will perform a server-side merge of the specified
592 Merge will perform a server-side merge of the specified
590 pull request, if the pull request is approved and mergeable.
593 pull request, if the pull request is approved and mergeable.
591 After succesfull merging, the pull request is automatically
594 After succesfull merging, the pull request is automatically
592 closed, with a relevant comment.
595 closed, with a relevant comment.
593 """
596 """
594 pull_request_id = safe_int(pull_request_id)
597 pull_request_id = safe_int(pull_request_id)
595 pull_request = PullRequest.get_or_404(pull_request_id)
598 pull_request = PullRequest.get_or_404(pull_request_id)
596 user = c.rhodecode_user
599 user = c.rhodecode_user
597
600
598 if self._meets_merge_pre_conditions(pull_request, user):
601 if self._meets_merge_pre_conditions(pull_request, user):
599 log.debug("Pre-conditions checked, trying to merge.")
602 log.debug("Pre-conditions checked, trying to merge.")
600 extras = vcs_operation_context(
603 extras = vcs_operation_context(
601 request.environ, repo_name=pull_request.target_repo.repo_name,
604 request.environ, repo_name=pull_request.target_repo.repo_name,
602 username=user.username, action='push',
605 username=user.username, action='push',
603 scm=pull_request.target_repo.repo_type)
606 scm=pull_request.target_repo.repo_type)
604 self._merge_pull_request(pull_request, user, extras)
607 self._merge_pull_request(pull_request, user, extras)
605
608
606 return redirect(url(
609 return redirect(url(
607 'pullrequest_show',
610 'pullrequest_show',
608 repo_name=pull_request.target_repo.repo_name,
611 repo_name=pull_request.target_repo.repo_name,
609 pull_request_id=pull_request.pull_request_id))
612 pull_request_id=pull_request.pull_request_id))
610
613
611 def _meets_merge_pre_conditions(self, pull_request, user):
614 def _meets_merge_pre_conditions(self, pull_request, user):
612 if not PullRequestModel().check_user_merge(pull_request, user):
615 if not PullRequestModel().check_user_merge(pull_request, user):
613 raise HTTPForbidden()
616 raise HTTPForbidden()
614
617
615 merge_status, msg = PullRequestModel().merge_status(pull_request)
618 merge_status, msg = PullRequestModel().merge_status(pull_request)
616 if not merge_status:
619 if not merge_status:
617 log.debug("Cannot merge, not mergeable.")
620 log.debug("Cannot merge, not mergeable.")
618 h.flash(msg, category='error')
621 h.flash(msg, category='error')
619 return False
622 return False
620
623
621 if (pull_request.calculated_review_status()
624 if (pull_request.calculated_review_status()
622 is not ChangesetStatus.STATUS_APPROVED):
625 is not ChangesetStatus.STATUS_APPROVED):
623 log.debug("Cannot merge, approval is pending.")
626 log.debug("Cannot merge, approval is pending.")
624 msg = _('Pull request reviewer approval is pending.')
627 msg = _('Pull request reviewer approval is pending.')
625 h.flash(msg, category='error')
628 h.flash(msg, category='error')
626 return False
629 return False
627 return True
630 return True
628
631
629 def _merge_pull_request(self, pull_request, user, extras):
632 def _merge_pull_request(self, pull_request, user, extras):
630 merge_resp = PullRequestModel().merge(
633 merge_resp = PullRequestModel().merge(
631 pull_request, user, extras=extras)
634 pull_request, user, extras=extras)
632
635
633 if merge_resp.executed:
636 if merge_resp.executed:
634 log.debug("The merge was successful, closing the pull request.")
637 log.debug("The merge was successful, closing the pull request.")
635 PullRequestModel().close_pull_request(
638 PullRequestModel().close_pull_request(
636 pull_request.pull_request_id, user)
639 pull_request.pull_request_id, user)
637 Session().commit()
640 Session().commit()
638 msg = _('Pull request was successfully merged and closed.')
641 msg = _('Pull request was successfully merged and closed.')
639 h.flash(msg, category='success')
642 h.flash(msg, category='success')
640 else:
643 else:
641 log.debug(
644 log.debug(
642 "The merge was not successful. Merge response: %s",
645 "The merge was not successful. Merge response: %s",
643 merge_resp)
646 merge_resp)
644 msg = PullRequestModel().merge_status_message(
647 msg = PullRequestModel().merge_status_message(
645 merge_resp.failure_reason)
648 merge_resp.failure_reason)
646 h.flash(msg, category='error')
649 h.flash(msg, category='error')
647
650
648 def _update_reviewers(self, pull_request_id, review_members):
651 def _update_reviewers(self, pull_request_id, review_members):
649 reviewers = [
652 reviewers = [
650 (int(r['user_id']), r['reasons']) for r in review_members]
653 (int(r['user_id']), r['reasons']) for r in review_members]
651 PullRequestModel().update_reviewers(pull_request_id, reviewers)
654 PullRequestModel().update_reviewers(pull_request_id, reviewers)
652 Session().commit()
655 Session().commit()
653
656
654 def _reject_close(self, pull_request):
657 def _reject_close(self, pull_request):
655 if pull_request.is_closed():
658 if pull_request.is_closed():
656 raise HTTPForbidden()
659 raise HTTPForbidden()
657
660
658 PullRequestModel().close_pull_request_with_comment(
661 PullRequestModel().close_pull_request_with_comment(
659 pull_request, c.rhodecode_user, c.rhodecode_db_repo)
662 pull_request, c.rhodecode_user, c.rhodecode_db_repo)
660 Session().commit()
663 Session().commit()
661
664
662 @LoginRequired()
665 @LoginRequired()
663 @NotAnonymous()
666 @NotAnonymous()
664 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
667 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
665 'repository.admin')
668 'repository.admin')
666 @auth.CSRFRequired()
669 @auth.CSRFRequired()
667 @jsonify
670 @jsonify
668 def delete(self, repo_name, pull_request_id):
671 def delete(self, repo_name, pull_request_id):
669 pull_request_id = safe_int(pull_request_id)
672 pull_request_id = safe_int(pull_request_id)
670 pull_request = PullRequest.get_or_404(pull_request_id)
673 pull_request = PullRequest.get_or_404(pull_request_id)
671 # only owner can delete it !
674 # only owner can delete it !
672 if pull_request.author.user_id == c.rhodecode_user.user_id:
675 if pull_request.author.user_id == c.rhodecode_user.user_id:
673 PullRequestModel().delete(pull_request)
676 PullRequestModel().delete(pull_request)
674 Session().commit()
677 Session().commit()
675 h.flash(_('Successfully deleted pull request'),
678 h.flash(_('Successfully deleted pull request'),
676 category='success')
679 category='success')
677 return redirect(url('my_account_pullrequests'))
680 return redirect(url('my_account_pullrequests'))
678 raise HTTPForbidden()
681 raise HTTPForbidden()
679
682
680 def _get_pr_version(self, pull_request_id, version=None):
683 def _get_pr_version(self, pull_request_id, version=None):
681 pull_request_id = safe_int(pull_request_id)
684 pull_request_id = safe_int(pull_request_id)
682 at_version = None
685 at_version = None
683 if version:
686
687 if version and version == 'latest':
688 pull_request_ver = PullRequest.get(pull_request_id)
689 pull_request_obj = pull_request_ver
690 _org_pull_request_obj = pull_request_obj
691 at_version = 'latest'
692 elif version:
684 pull_request_ver = PullRequestVersion.get_or_404(version)
693 pull_request_ver = PullRequestVersion.get_or_404(version)
685 pull_request_obj = pull_request_ver
694 pull_request_obj = pull_request_ver
686 _org_pull_request_obj = pull_request_ver.pull_request
695 _org_pull_request_obj = pull_request_ver.pull_request
687 at_version = pull_request_ver.pull_request_version_id
696 at_version = pull_request_ver.pull_request_version_id
688 else:
697 else:
689 _org_pull_request_obj = pull_request_obj = PullRequest.get_or_404(pull_request_id)
698 _org_pull_request_obj = pull_request_obj = PullRequest.get_or_404(pull_request_id)
690
699
691 class PullRequestDisplay(object):
700 pull_request_display_obj = PullRequest.get_pr_display_object(
692 """
701 pull_request_obj, _org_pull_request_obj)
693 Special object wrapper for showing PullRequest data via Versions
694 It mimics PR object as close as possible. This is read only object
695 just for display
696 """
697 def __init__(self, attrs):
698 self.attrs = attrs
699 # internal have priority over the given ones via attrs
700 self.internal = ['versions']
701
702 def __getattr__(self, item):
703 if item in self.internal:
704 return getattr(self, item)
705 try:
706 return self.attrs[item]
707 except KeyError:
708 raise AttributeError(
709 '%s object has no attribute %s' % (self, item))
710
711 def versions(self):
712 return pull_request_obj.versions.order_by(
713 PullRequestVersion.pull_request_version_id).all()
714
715 def is_closed(self):
716 return pull_request_obj.is_closed()
717
718 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
719
720 attrs.author = StrictAttributeDict(
721 pull_request_obj.author.get_api_data())
722 if pull_request_obj.target_repo:
723 attrs.target_repo = StrictAttributeDict(
724 pull_request_obj.target_repo.get_api_data())
725 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
726
727 if pull_request_obj.source_repo:
728 attrs.source_repo = StrictAttributeDict(
729 pull_request_obj.source_repo.get_api_data())
730 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
731
732 attrs.source_ref_parts = pull_request_obj.source_ref_parts
733 attrs.target_ref_parts = pull_request_obj.target_ref_parts
734
735 attrs.shadow_merge_ref = _org_pull_request_obj.shadow_merge_ref
736
737 pull_request_display_obj = PullRequestDisplay(attrs)
738
739 return _org_pull_request_obj, pull_request_obj, \
702 return _org_pull_request_obj, pull_request_obj, \
740 pull_request_display_obj, at_version
703 pull_request_display_obj, at_version
741
704
705 def _get_pr_version_changes(self, version, pull_request_latest):
706 """
707 Generate changes commits, and diff data based on the current pr version
708 """
709
710 #TODO(marcink): save those changes as JSON metadata for chaching later.
711
712 # fake the version to add the "initial" state object
713 pull_request_initial = PullRequest.get_pr_display_object(
714 pull_request_latest, pull_request_latest,
715 internal_methods=['get_commit', 'versions'])
716 pull_request_initial.revisions = []
717 pull_request_initial.source_repo.get_commit = types.MethodType(
718 lambda *a, **k: EmptyCommit(), pull_request_initial)
719 pull_request_initial.source_repo.scm_instance = types.MethodType(
720 lambda *a, **k: EmptyRepository(), pull_request_initial)
721
722 _changes_versions = [pull_request_latest] + \
723 list(reversed(c.versions)) + \
724 [pull_request_initial]
725
726 if version == 'latest':
727 index = 0
728 else:
729 for pos, prver in enumerate(_changes_versions):
730 ver = getattr(prver, 'pull_request_version_id', -1)
731 if ver == safe_int(version):
732 index = pos
733 break
734 else:
735 index = 0
736
737 cur_obj = _changes_versions[index]
738 prev_obj = _changes_versions[index + 1]
739
740 old_commit_ids = set(prev_obj.revisions)
741 new_commit_ids = set(cur_obj.revisions)
742
743 changes = PullRequestModel()._calculate_commit_id_changes(
744 old_commit_ids, new_commit_ids)
745
746 old_diff_data, new_diff_data = PullRequestModel()._generate_update_diffs(
747 cur_obj, prev_obj)
748 file_changes = PullRequestModel()._calculate_file_changes(
749 old_diff_data, new_diff_data)
750 return changes, file_changes
751
742 @LoginRequired()
752 @LoginRequired()
743 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
753 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
744 'repository.admin')
754 'repository.admin')
745 def show(self, repo_name, pull_request_id):
755 def show(self, repo_name, pull_request_id):
746 pull_request_id = safe_int(pull_request_id)
756 pull_request_id = safe_int(pull_request_id)
747 version = request.GET.get('version')
757 version = request.GET.get('version')
748
758
749 (pull_request_latest,
759 (pull_request_latest,
750 pull_request_at_ver,
760 pull_request_at_ver,
751 pull_request_display_obj,
761 pull_request_display_obj,
752 at_version) = self._get_pr_version(pull_request_id, version=version)
762 at_version) = self._get_pr_version(pull_request_id, version=version)
753
763
754 c.template_context['pull_request_data']['pull_request_id'] = \
764 c.template_context['pull_request_data']['pull_request_id'] = \
755 pull_request_id
765 pull_request_id
756
766
757 # pull_requests repo_name we opened it against
767 # pull_requests repo_name we opened it against
758 # ie. target_repo must match
768 # ie. target_repo must match
759 if repo_name != pull_request_at_ver.target_repo.repo_name:
769 if repo_name != pull_request_at_ver.target_repo.repo_name:
760 raise HTTPNotFound
770 raise HTTPNotFound
761
771
762 c.shadow_clone_url = PullRequestModel().get_shadow_clone_url(
772 c.shadow_clone_url = PullRequestModel().get_shadow_clone_url(
763 pull_request_at_ver)
773 pull_request_at_ver)
764
774
765 pr_closed = pull_request_latest.is_closed()
775 pr_closed = pull_request_latest.is_closed()
766 if at_version:
776 if at_version and not at_version == 'latest':
767 c.allowed_to_change_status = False
777 c.allowed_to_change_status = False
768 c.allowed_to_update = False
778 c.allowed_to_update = False
769 c.allowed_to_merge = False
779 c.allowed_to_merge = False
770 c.allowed_to_delete = False
780 c.allowed_to_delete = False
771 c.allowed_to_comment = False
781 c.allowed_to_comment = False
772 else:
782 else:
773 c.allowed_to_change_status = PullRequestModel(). \
783 c.allowed_to_change_status = PullRequestModel(). \
774 check_user_change_status(pull_request_at_ver, c.rhodecode_user)
784 check_user_change_status(pull_request_at_ver, c.rhodecode_user)
775 c.allowed_to_update = PullRequestModel().check_user_update(
785 c.allowed_to_update = PullRequestModel().check_user_update(
776 pull_request_latest, c.rhodecode_user) and not pr_closed
786 pull_request_latest, c.rhodecode_user) and not pr_closed
777 c.allowed_to_merge = PullRequestModel().check_user_merge(
787 c.allowed_to_merge = PullRequestModel().check_user_merge(
778 pull_request_latest, c.rhodecode_user) and not pr_closed
788 pull_request_latest, c.rhodecode_user) and not pr_closed
779 c.allowed_to_delete = PullRequestModel().check_user_delete(
789 c.allowed_to_delete = PullRequestModel().check_user_delete(
780 pull_request_latest, c.rhodecode_user) and not pr_closed
790 pull_request_latest, c.rhodecode_user) and not pr_closed
781 c.allowed_to_comment = not pr_closed
791 c.allowed_to_comment = not pr_closed
782
792
783 cc_model = ChangesetCommentsModel()
793 cc_model = ChangesetCommentsModel()
784
794
785 c.pull_request_reviewers = pull_request_at_ver.reviewers_statuses()
795 c.pull_request_reviewers = pull_request_at_ver.reviewers_statuses()
786 c.pull_request_review_status = pull_request_at_ver.calculated_review_status()
796 c.pull_request_review_status = pull_request_at_ver.calculated_review_status()
787 c.pr_merge_status, c.pr_merge_msg = PullRequestModel().merge_status(
797 c.pr_merge_status, c.pr_merge_msg = PullRequestModel().merge_status(
788 pull_request_at_ver)
798 pull_request_at_ver)
789 c.approval_msg = None
799 c.approval_msg = None
790 if c.pull_request_review_status != ChangesetStatus.STATUS_APPROVED:
800 if c.pull_request_review_status != ChangesetStatus.STATUS_APPROVED:
791 c.approval_msg = _('Reviewer approval is pending.')
801 c.approval_msg = _('Reviewer approval is pending.')
792 c.pr_merge_status = False
802 c.pr_merge_status = False
793
803
794 # inline comments
804 # inline comments
795 c.inline_comments = cc_model.get_inline_comments(
805 c.inline_comments = cc_model.get_inline_comments(
796 c.rhodecode_db_repo.repo_id,
806 c.rhodecode_db_repo.repo_id,
797 pull_request=pull_request_id)
807 pull_request=pull_request_id)
798
808
799 c.inline_cnt = cc_model.get_inline_comments_count(
809 c.inline_cnt = cc_model.get_inline_comments_count(
800 c.inline_comments, version=at_version)
810 c.inline_comments, version=at_version)
801
811
802 # load compare data into template context
812 # load compare data into template context
803 enable_comments = not pr_closed
813 enable_comments = not pr_closed
804 self._load_compare_data(
814 self._load_compare_data(
805 pull_request_at_ver,
815 pull_request_at_ver,
806 c.inline_comments, enable_comments=enable_comments)
816 c.inline_comments, enable_comments=enable_comments)
807
817
808 # outdated comments
818 # outdated comments
809 c.outdated_comments = {}
819 c.outdated_comments = {}
810 c.outdated_cnt = 0
820 c.outdated_cnt = 0
811
821
812 if ChangesetCommentsModel.use_outdated_comments(pull_request_latest):
822 if ChangesetCommentsModel.use_outdated_comments(pull_request_latest):
813 c.outdated_comments = cc_model.get_outdated_comments(
823 c.outdated_comments = cc_model.get_outdated_comments(
814 c.rhodecode_db_repo.repo_id,
824 c.rhodecode_db_repo.repo_id,
815 pull_request=pull_request_at_ver)
825 pull_request=pull_request_at_ver)
816
826
817 # Count outdated comments and check for deleted files
827 # Count outdated comments and check for deleted files
818 for file_name, lines in c.outdated_comments.iteritems():
828 for file_name, lines in c.outdated_comments.iteritems():
819 for comments in lines.values():
829 for comments in lines.values():
820 comments = [comm for comm in comments
830 comments = [comm for comm in comments
821 if comm.outdated_at_version(at_version)]
831 if comm.outdated_at_version(at_version)]
822 c.outdated_cnt += len(comments)
832 c.outdated_cnt += len(comments)
823 if file_name not in c.included_files:
833 if file_name not in c.included_files:
824 c.deleted_files.append(file_name)
834 c.deleted_files.append(file_name)
825
835
826 # this is a hack to properly display links, when creating PR, the
836 # this is a hack to properly display links, when creating PR, the
827 # compare view and others uses different notation, and
837 # compare view and others uses different notation, and
828 # compare_commits.html renders links based on the target_repo.
838 # compare_commits.html renders links based on the target_repo.
829 # We need to swap that here to generate it properly on the html side
839 # We need to swap that here to generate it properly on the html side
830 c.target_repo = c.source_repo
840 c.target_repo = c.source_repo
831
841
832 # comments
842 # comments
833 c.comments = cc_model.get_comments(c.rhodecode_db_repo.repo_id,
843 c.comments = cc_model.get_comments(c.rhodecode_db_repo.repo_id,
834 pull_request=pull_request_id)
844 pull_request=pull_request_id)
835
845
836 if c.allowed_to_update:
846 if c.allowed_to_update:
837 force_close = ('forced_closed', _('Close Pull Request'))
847 force_close = ('forced_closed', _('Close Pull Request'))
838 statuses = ChangesetStatus.STATUSES + [force_close]
848 statuses = ChangesetStatus.STATUSES + [force_close]
839 else:
849 else:
840 statuses = ChangesetStatus.STATUSES
850 statuses = ChangesetStatus.STATUSES
841 c.commit_statuses = statuses
851 c.commit_statuses = statuses
842
852
843 c.ancestor = None # TODO: add ancestor here
853 c.ancestor = None # TODO: add ancestor here
844 c.pull_request = pull_request_display_obj
854 c.pull_request = pull_request_display_obj
845 c.pull_request_latest = pull_request_latest
855 c.pull_request_latest = pull_request_latest
846 c.at_version = at_version
856 c.at_version = at_version
847
857
858 c.versions = pull_request_display_obj.versions()
859 c.changes = None
860 c.file_changes = None
861
862 c.show_version_changes = 1
863
864 if at_version and c.show_version_changes:
865 c.changes, c.file_changes = self._get_pr_version_changes(
866 version, pull_request_latest)
867
848 return render('/pullrequests/pullrequest_show.html')
868 return render('/pullrequests/pullrequest_show.html')
849
869
850 @LoginRequired()
870 @LoginRequired()
851 @NotAnonymous()
871 @NotAnonymous()
852 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
872 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
853 'repository.admin')
873 'repository.admin')
854 @auth.CSRFRequired()
874 @auth.CSRFRequired()
855 @jsonify
875 @jsonify
856 def comment(self, repo_name, pull_request_id):
876 def comment(self, repo_name, pull_request_id):
857 pull_request_id = safe_int(pull_request_id)
877 pull_request_id = safe_int(pull_request_id)
858 pull_request = PullRequest.get_or_404(pull_request_id)
878 pull_request = PullRequest.get_or_404(pull_request_id)
859 if pull_request.is_closed():
879 if pull_request.is_closed():
860 raise HTTPForbidden()
880 raise HTTPForbidden()
861
881
862 # TODO: johbo: Re-think this bit, "approved_closed" does not exist
882 # TODO: johbo: Re-think this bit, "approved_closed" does not exist
863 # as a changeset status, still we want to send it in one value.
883 # as a changeset status, still we want to send it in one value.
864 status = request.POST.get('changeset_status', None)
884 status = request.POST.get('changeset_status', None)
865 text = request.POST.get('text')
885 text = request.POST.get('text')
866 if status and '_closed' in status:
886 if status and '_closed' in status:
867 close_pr = True
887 close_pr = True
868 status = status.replace('_closed', '')
888 status = status.replace('_closed', '')
869 else:
889 else:
870 close_pr = False
890 close_pr = False
871
891
872 forced = (status == 'forced')
892 forced = (status == 'forced')
873 if forced:
893 if forced:
874 status = 'rejected'
894 status = 'rejected'
875
895
876 allowed_to_change_status = PullRequestModel().check_user_change_status(
896 allowed_to_change_status = PullRequestModel().check_user_change_status(
877 pull_request, c.rhodecode_user)
897 pull_request, c.rhodecode_user)
878
898
879 if status and allowed_to_change_status:
899 if status and allowed_to_change_status:
880 message = (_('Status change %(transition_icon)s %(status)s')
900 message = (_('Status change %(transition_icon)s %(status)s')
881 % {'transition_icon': '>',
901 % {'transition_icon': '>',
882 'status': ChangesetStatus.get_status_lbl(status)})
902 'status': ChangesetStatus.get_status_lbl(status)})
883 if close_pr:
903 if close_pr:
884 message = _('Closing with') + ' ' + message
904 message = _('Closing with') + ' ' + message
885 text = text or message
905 text = text or message
886 comm = ChangesetCommentsModel().create(
906 comm = ChangesetCommentsModel().create(
887 text=text,
907 text=text,
888 repo=c.rhodecode_db_repo.repo_id,
908 repo=c.rhodecode_db_repo.repo_id,
889 user=c.rhodecode_user.user_id,
909 user=c.rhodecode_user.user_id,
890 pull_request=pull_request_id,
910 pull_request=pull_request_id,
891 f_path=request.POST.get('f_path'),
911 f_path=request.POST.get('f_path'),
892 line_no=request.POST.get('line'),
912 line_no=request.POST.get('line'),
893 status_change=(ChangesetStatus.get_status_lbl(status)
913 status_change=(ChangesetStatus.get_status_lbl(status)
894 if status and allowed_to_change_status else None),
914 if status and allowed_to_change_status else None),
895 status_change_type=(status
915 status_change_type=(status
896 if status and allowed_to_change_status else None),
916 if status and allowed_to_change_status else None),
897 closing_pr=close_pr
917 closing_pr=close_pr
898 )
918 )
899
919
900 if allowed_to_change_status:
920 if allowed_to_change_status:
901 old_calculated_status = pull_request.calculated_review_status()
921 old_calculated_status = pull_request.calculated_review_status()
902 # get status if set !
922 # get status if set !
903 if status:
923 if status:
904 ChangesetStatusModel().set_status(
924 ChangesetStatusModel().set_status(
905 c.rhodecode_db_repo.repo_id,
925 c.rhodecode_db_repo.repo_id,
906 status,
926 status,
907 c.rhodecode_user.user_id,
927 c.rhodecode_user.user_id,
908 comm,
928 comm,
909 pull_request=pull_request_id
929 pull_request=pull_request_id
910 )
930 )
911
931
912 Session().flush()
932 Session().flush()
913 events.trigger(events.PullRequestCommentEvent(pull_request, comm))
933 events.trigger(events.PullRequestCommentEvent(pull_request, comm))
914 # we now calculate the status of pull request, and based on that
934 # we now calculate the status of pull request, and based on that
915 # calculation we set the commits status
935 # calculation we set the commits status
916 calculated_status = pull_request.calculated_review_status()
936 calculated_status = pull_request.calculated_review_status()
917 if old_calculated_status != calculated_status:
937 if old_calculated_status != calculated_status:
918 PullRequestModel()._trigger_pull_request_hook(
938 PullRequestModel()._trigger_pull_request_hook(
919 pull_request, c.rhodecode_user, 'review_status_change')
939 pull_request, c.rhodecode_user, 'review_status_change')
920
940
921 calculated_status_lbl = ChangesetStatus.get_status_lbl(
941 calculated_status_lbl = ChangesetStatus.get_status_lbl(
922 calculated_status)
942 calculated_status)
923
943
924 if close_pr:
944 if close_pr:
925 status_completed = (
945 status_completed = (
926 calculated_status in [ChangesetStatus.STATUS_APPROVED,
946 calculated_status in [ChangesetStatus.STATUS_APPROVED,
927 ChangesetStatus.STATUS_REJECTED])
947 ChangesetStatus.STATUS_REJECTED])
928 if forced or status_completed:
948 if forced or status_completed:
929 PullRequestModel().close_pull_request(
949 PullRequestModel().close_pull_request(
930 pull_request_id, c.rhodecode_user)
950 pull_request_id, c.rhodecode_user)
931 else:
951 else:
932 h.flash(_('Closing pull request on other statuses than '
952 h.flash(_('Closing pull request on other statuses than '
933 'rejected or approved is forbidden. '
953 'rejected or approved is forbidden. '
934 'Calculated status from all reviewers '
954 'Calculated status from all reviewers '
935 'is currently: %s') % calculated_status_lbl,
955 'is currently: %s') % calculated_status_lbl,
936 category='warning')
956 category='warning')
937
957
938 Session().commit()
958 Session().commit()
939
959
940 if not request.is_xhr:
960 if not request.is_xhr:
941 return redirect(h.url('pullrequest_show', repo_name=repo_name,
961 return redirect(h.url('pullrequest_show', repo_name=repo_name,
942 pull_request_id=pull_request_id))
962 pull_request_id=pull_request_id))
943
963
944 data = {
964 data = {
945 'target_id': h.safeid(h.safe_unicode(request.POST.get('f_path'))),
965 'target_id': h.safeid(h.safe_unicode(request.POST.get('f_path'))),
946 }
966 }
947 if comm:
967 if comm:
948 c.co = comm
968 c.co = comm
949 data.update(comm.get_dict())
969 data.update(comm.get_dict())
950 data.update({'rendered_text':
970 data.update({'rendered_text':
951 render('changeset/changeset_comment_block.html')})
971 render('changeset/changeset_comment_block.html')})
952
972
953 return data
973 return data
954
974
955 @LoginRequired()
975 @LoginRequired()
956 @NotAnonymous()
976 @NotAnonymous()
957 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
977 @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
958 'repository.admin')
978 'repository.admin')
959 @auth.CSRFRequired()
979 @auth.CSRFRequired()
960 @jsonify
980 @jsonify
961 def delete_comment(self, repo_name, comment_id):
981 def delete_comment(self, repo_name, comment_id):
962 return self._delete_comment(comment_id)
982 return self._delete_comment(comment_id)
963
983
964 def _delete_comment(self, comment_id):
984 def _delete_comment(self, comment_id):
965 comment_id = safe_int(comment_id)
985 comment_id = safe_int(comment_id)
966 co = ChangesetComment.get_or_404(comment_id)
986 co = ChangesetComment.get_or_404(comment_id)
967 if co.pull_request.is_closed():
987 if co.pull_request.is_closed():
968 # don't allow deleting comments on closed pull request
988 # don't allow deleting comments on closed pull request
969 raise HTTPForbidden()
989 raise HTTPForbidden()
970
990
971 is_owner = co.author.user_id == c.rhodecode_user.user_id
991 is_owner = co.author.user_id == c.rhodecode_user.user_id
972 is_repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name)
992 is_repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name)
973 if h.HasPermissionAny('hg.admin')() or is_repo_admin or is_owner:
993 if h.HasPermissionAny('hg.admin')() or is_repo_admin or is_owner:
974 old_calculated_status = co.pull_request.calculated_review_status()
994 old_calculated_status = co.pull_request.calculated_review_status()
975 ChangesetCommentsModel().delete(comment=co)
995 ChangesetCommentsModel().delete(comment=co)
976 Session().commit()
996 Session().commit()
977 calculated_status = co.pull_request.calculated_review_status()
997 calculated_status = co.pull_request.calculated_review_status()
978 if old_calculated_status != calculated_status:
998 if old_calculated_status != calculated_status:
979 PullRequestModel()._trigger_pull_request_hook(
999 PullRequestModel()._trigger_pull_request_hook(
980 co.pull_request, c.rhodecode_user, 'review_status_change')
1000 co.pull_request, c.rhodecode_user, 'review_status_change')
981 return True
1001 return True
982 else:
1002 else:
983 raise HTTPForbidden()
1003 raise HTTPForbidden()
@@ -1,950 +1,951 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2016 RhodeCode GmbH
3 # Copyright (C) 2011-2016 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 """
22 """
23 Some simple helper functions
23 Some simple helper functions
24 """
24 """
25
25
26
26
27 import collections
27 import collections
28 import datetime
28 import datetime
29 import dateutil.relativedelta
29 import dateutil.relativedelta
30 import hashlib
30 import hashlib
31 import logging
31 import logging
32 import re
32 import re
33 import sys
33 import sys
34 import time
34 import time
35 import threading
35 import threading
36 import urllib
36 import urllib
37 import urlobject
37 import urlobject
38 import uuid
38 import uuid
39
39
40 import pygments.lexers
40 import pygments.lexers
41 import sqlalchemy
41 import sqlalchemy
42 import sqlalchemy.engine.url
42 import sqlalchemy.engine.url
43 import webob
43 import webob
44 import routes.util
44 import routes.util
45
45
46 import rhodecode
46 import rhodecode
47
47
48
48
49 def md5(s):
49 def md5(s):
50 return hashlib.md5(s).hexdigest()
50 return hashlib.md5(s).hexdigest()
51
51
52
52
53 def md5_safe(s):
53 def md5_safe(s):
54 return md5(safe_str(s))
54 return md5(safe_str(s))
55
55
56
56
57 def __get_lem(extra_mapping=None):
57 def __get_lem(extra_mapping=None):
58 """
58 """
59 Get language extension map based on what's inside pygments lexers
59 Get language extension map based on what's inside pygments lexers
60 """
60 """
61 d = collections.defaultdict(lambda: [])
61 d = collections.defaultdict(lambda: [])
62
62
63 def __clean(s):
63 def __clean(s):
64 s = s.lstrip('*')
64 s = s.lstrip('*')
65 s = s.lstrip('.')
65 s = s.lstrip('.')
66
66
67 if s.find('[') != -1:
67 if s.find('[') != -1:
68 exts = []
68 exts = []
69 start, stop = s.find('['), s.find(']')
69 start, stop = s.find('['), s.find(']')
70
70
71 for suffix in s[start + 1:stop]:
71 for suffix in s[start + 1:stop]:
72 exts.append(s[:s.find('[')] + suffix)
72 exts.append(s[:s.find('[')] + suffix)
73 return [e.lower() for e in exts]
73 return [e.lower() for e in exts]
74 else:
74 else:
75 return [s.lower()]
75 return [s.lower()]
76
76
77 for lx, t in sorted(pygments.lexers.LEXERS.items()):
77 for lx, t in sorted(pygments.lexers.LEXERS.items()):
78 m = map(__clean, t[-2])
78 m = map(__clean, t[-2])
79 if m:
79 if m:
80 m = reduce(lambda x, y: x + y, m)
80 m = reduce(lambda x, y: x + y, m)
81 for ext in m:
81 for ext in m:
82 desc = lx.replace('Lexer', '')
82 desc = lx.replace('Lexer', '')
83 d[ext].append(desc)
83 d[ext].append(desc)
84
84
85 data = dict(d)
85 data = dict(d)
86
86
87 extra_mapping = extra_mapping or {}
87 extra_mapping = extra_mapping or {}
88 if extra_mapping:
88 if extra_mapping:
89 for k, v in extra_mapping.items():
89 for k, v in extra_mapping.items():
90 if k not in data:
90 if k not in data:
91 # register new mapping2lexer
91 # register new mapping2lexer
92 data[k] = [v]
92 data[k] = [v]
93
93
94 return data
94 return data
95
95
96
96
97 def str2bool(_str):
97 def str2bool(_str):
98 """
98 """
99 returns True/False value from given string, it tries to translate the
99 returns True/False value from given string, it tries to translate the
100 string into boolean
100 string into boolean
101
101
102 :param _str: string value to translate into boolean
102 :param _str: string value to translate into boolean
103 :rtype: boolean
103 :rtype: boolean
104 :returns: boolean from given string
104 :returns: boolean from given string
105 """
105 """
106 if _str is None:
106 if _str is None:
107 return False
107 return False
108 if _str in (True, False):
108 if _str in (True, False):
109 return _str
109 return _str
110 _str = str(_str).strip().lower()
110 _str = str(_str).strip().lower()
111 return _str in ('t', 'true', 'y', 'yes', 'on', '1')
111 return _str in ('t', 'true', 'y', 'yes', 'on', '1')
112
112
113
113
114 def aslist(obj, sep=None, strip=True):
114 def aslist(obj, sep=None, strip=True):
115 """
115 """
116 Returns given string separated by sep as list
116 Returns given string separated by sep as list
117
117
118 :param obj:
118 :param obj:
119 :param sep:
119 :param sep:
120 :param strip:
120 :param strip:
121 """
121 """
122 if isinstance(obj, (basestring,)):
122 if isinstance(obj, (basestring,)):
123 lst = obj.split(sep)
123 lst = obj.split(sep)
124 if strip:
124 if strip:
125 lst = [v.strip() for v in lst]
125 lst = [v.strip() for v in lst]
126 return lst
126 return lst
127 elif isinstance(obj, (list, tuple)):
127 elif isinstance(obj, (list, tuple)):
128 return obj
128 return obj
129 elif obj is None:
129 elif obj is None:
130 return []
130 return []
131 else:
131 else:
132 return [obj]
132 return [obj]
133
133
134
134
135 def convert_line_endings(line, mode):
135 def convert_line_endings(line, mode):
136 """
136 """
137 Converts a given line "line end" accordingly to given mode
137 Converts a given line "line end" accordingly to given mode
138
138
139 Available modes are::
139 Available modes are::
140 0 - Unix
140 0 - Unix
141 1 - Mac
141 1 - Mac
142 2 - DOS
142 2 - DOS
143
143
144 :param line: given line to convert
144 :param line: given line to convert
145 :param mode: mode to convert to
145 :param mode: mode to convert to
146 :rtype: str
146 :rtype: str
147 :return: converted line according to mode
147 :return: converted line according to mode
148 """
148 """
149 if mode == 0:
149 if mode == 0:
150 line = line.replace('\r\n', '\n')
150 line = line.replace('\r\n', '\n')
151 line = line.replace('\r', '\n')
151 line = line.replace('\r', '\n')
152 elif mode == 1:
152 elif mode == 1:
153 line = line.replace('\r\n', '\r')
153 line = line.replace('\r\n', '\r')
154 line = line.replace('\n', '\r')
154 line = line.replace('\n', '\r')
155 elif mode == 2:
155 elif mode == 2:
156 line = re.sub('\r(?!\n)|(?<!\r)\n', '\r\n', line)
156 line = re.sub('\r(?!\n)|(?<!\r)\n', '\r\n', line)
157 return line
157 return line
158
158
159
159
160 def detect_mode(line, default):
160 def detect_mode(line, default):
161 """
161 """
162 Detects line break for given line, if line break couldn't be found
162 Detects line break for given line, if line break couldn't be found
163 given default value is returned
163 given default value is returned
164
164
165 :param line: str line
165 :param line: str line
166 :param default: default
166 :param default: default
167 :rtype: int
167 :rtype: int
168 :return: value of line end on of 0 - Unix, 1 - Mac, 2 - DOS
168 :return: value of line end on of 0 - Unix, 1 - Mac, 2 - DOS
169 """
169 """
170 if line.endswith('\r\n'):
170 if line.endswith('\r\n'):
171 return 2
171 return 2
172 elif line.endswith('\n'):
172 elif line.endswith('\n'):
173 return 0
173 return 0
174 elif line.endswith('\r'):
174 elif line.endswith('\r'):
175 return 1
175 return 1
176 else:
176 else:
177 return default
177 return default
178
178
179
179
180 def safe_int(val, default=None):
180 def safe_int(val, default=None):
181 """
181 """
182 Returns int() of val if val is not convertable to int use default
182 Returns int() of val if val is not convertable to int use default
183 instead
183 instead
184
184
185 :param val:
185 :param val:
186 :param default:
186 :param default:
187 """
187 """
188
188
189 try:
189 try:
190 val = int(val)
190 val = int(val)
191 except (ValueError, TypeError):
191 except (ValueError, TypeError):
192 val = default
192 val = default
193
193
194 return val
194 return val
195
195
196
196
197 def safe_unicode(str_, from_encoding=None):
197 def safe_unicode(str_, from_encoding=None):
198 """
198 """
199 safe unicode function. Does few trick to turn str_ into unicode
199 safe unicode function. Does few trick to turn str_ into unicode
200
200
201 In case of UnicodeDecode error, we try to return it with encoding detected
201 In case of UnicodeDecode error, we try to return it with encoding detected
202 by chardet library if it fails fallback to unicode with errors replaced
202 by chardet library if it fails fallback to unicode with errors replaced
203
203
204 :param str_: string to decode
204 :param str_: string to decode
205 :rtype: unicode
205 :rtype: unicode
206 :returns: unicode object
206 :returns: unicode object
207 """
207 """
208 if isinstance(str_, unicode):
208 if isinstance(str_, unicode):
209 return str_
209 return str_
210
210
211 if not from_encoding:
211 if not from_encoding:
212 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
212 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
213 'utf8'), sep=',')
213 'utf8'), sep=',')
214 from_encoding = DEFAULT_ENCODINGS
214 from_encoding = DEFAULT_ENCODINGS
215
215
216 if not isinstance(from_encoding, (list, tuple)):
216 if not isinstance(from_encoding, (list, tuple)):
217 from_encoding = [from_encoding]
217 from_encoding = [from_encoding]
218
218
219 try:
219 try:
220 return unicode(str_)
220 return unicode(str_)
221 except UnicodeDecodeError:
221 except UnicodeDecodeError:
222 pass
222 pass
223
223
224 for enc in from_encoding:
224 for enc in from_encoding:
225 try:
225 try:
226 return unicode(str_, enc)
226 return unicode(str_, enc)
227 except UnicodeDecodeError:
227 except UnicodeDecodeError:
228 pass
228 pass
229
229
230 try:
230 try:
231 import chardet
231 import chardet
232 encoding = chardet.detect(str_)['encoding']
232 encoding = chardet.detect(str_)['encoding']
233 if encoding is None:
233 if encoding is None:
234 raise Exception()
234 raise Exception()
235 return str_.decode(encoding)
235 return str_.decode(encoding)
236 except (ImportError, UnicodeDecodeError, Exception):
236 except (ImportError, UnicodeDecodeError, Exception):
237 return unicode(str_, from_encoding[0], 'replace')
237 return unicode(str_, from_encoding[0], 'replace')
238
238
239
239
240 def safe_str(unicode_, to_encoding=None):
240 def safe_str(unicode_, to_encoding=None):
241 """
241 """
242 safe str function. Does few trick to turn unicode_ into string
242 safe str function. Does few trick to turn unicode_ into string
243
243
244 In case of UnicodeEncodeError, we try to return it with encoding detected
244 In case of UnicodeEncodeError, we try to return it with encoding detected
245 by chardet library if it fails fallback to string with errors replaced
245 by chardet library if it fails fallback to string with errors replaced
246
246
247 :param unicode_: unicode to encode
247 :param unicode_: unicode to encode
248 :rtype: str
248 :rtype: str
249 :returns: str object
249 :returns: str object
250 """
250 """
251
251
252 # if it's not basestr cast to str
252 # if it's not basestr cast to str
253 if not isinstance(unicode_, basestring):
253 if not isinstance(unicode_, basestring):
254 return str(unicode_)
254 return str(unicode_)
255
255
256 if isinstance(unicode_, str):
256 if isinstance(unicode_, str):
257 return unicode_
257 return unicode_
258
258
259 if not to_encoding:
259 if not to_encoding:
260 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
260 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
261 'utf8'), sep=',')
261 'utf8'), sep=',')
262 to_encoding = DEFAULT_ENCODINGS
262 to_encoding = DEFAULT_ENCODINGS
263
263
264 if not isinstance(to_encoding, (list, tuple)):
264 if not isinstance(to_encoding, (list, tuple)):
265 to_encoding = [to_encoding]
265 to_encoding = [to_encoding]
266
266
267 for enc in to_encoding:
267 for enc in to_encoding:
268 try:
268 try:
269 return unicode_.encode(enc)
269 return unicode_.encode(enc)
270 except UnicodeEncodeError:
270 except UnicodeEncodeError:
271 pass
271 pass
272
272
273 try:
273 try:
274 import chardet
274 import chardet
275 encoding = chardet.detect(unicode_)['encoding']
275 encoding = chardet.detect(unicode_)['encoding']
276 if encoding is None:
276 if encoding is None:
277 raise UnicodeEncodeError()
277 raise UnicodeEncodeError()
278
278
279 return unicode_.encode(encoding)
279 return unicode_.encode(encoding)
280 except (ImportError, UnicodeEncodeError):
280 except (ImportError, UnicodeEncodeError):
281 return unicode_.encode(to_encoding[0], 'replace')
281 return unicode_.encode(to_encoding[0], 'replace')
282
282
283
283
284 def remove_suffix(s, suffix):
284 def remove_suffix(s, suffix):
285 if s.endswith(suffix):
285 if s.endswith(suffix):
286 s = s[:-1 * len(suffix)]
286 s = s[:-1 * len(suffix)]
287 return s
287 return s
288
288
289
289
290 def remove_prefix(s, prefix):
290 def remove_prefix(s, prefix):
291 if s.startswith(prefix):
291 if s.startswith(prefix):
292 s = s[len(prefix):]
292 s = s[len(prefix):]
293 return s
293 return s
294
294
295
295
296 def find_calling_context(ignore_modules=None):
296 def find_calling_context(ignore_modules=None):
297 """
297 """
298 Look through the calling stack and return the frame which called
298 Look through the calling stack and return the frame which called
299 this function and is part of core module ( ie. rhodecode.* )
299 this function and is part of core module ( ie. rhodecode.* )
300
300
301 :param ignore_modules: list of modules to ignore eg. ['rhodecode.lib']
301 :param ignore_modules: list of modules to ignore eg. ['rhodecode.lib']
302 """
302 """
303
303
304 ignore_modules = ignore_modules or []
304 ignore_modules = ignore_modules or []
305
305
306 f = sys._getframe(2)
306 f = sys._getframe(2)
307 while f.f_back is not None:
307 while f.f_back is not None:
308 name = f.f_globals.get('__name__')
308 name = f.f_globals.get('__name__')
309 if name and name.startswith(__name__.split('.')[0]):
309 if name and name.startswith(__name__.split('.')[0]):
310 if name not in ignore_modules:
310 if name not in ignore_modules:
311 return f
311 return f
312 f = f.f_back
312 f = f.f_back
313 return None
313 return None
314
314
315
315
316 def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs):
316 def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs):
317 """Custom engine_from_config functions."""
317 """Custom engine_from_config functions."""
318 log = logging.getLogger('sqlalchemy.engine')
318 log = logging.getLogger('sqlalchemy.engine')
319 engine = sqlalchemy.engine_from_config(configuration, prefix, **kwargs)
319 engine = sqlalchemy.engine_from_config(configuration, prefix, **kwargs)
320
320
321 def color_sql(sql):
321 def color_sql(sql):
322 color_seq = '\033[1;33m' # This is yellow: code 33
322 color_seq = '\033[1;33m' # This is yellow: code 33
323 normal = '\x1b[0m'
323 normal = '\x1b[0m'
324 return ''.join([color_seq, sql, normal])
324 return ''.join([color_seq, sql, normal])
325
325
326 if configuration['debug']:
326 if configuration['debug']:
327 # attach events only for debug configuration
327 # attach events only for debug configuration
328
328
329 def before_cursor_execute(conn, cursor, statement,
329 def before_cursor_execute(conn, cursor, statement,
330 parameters, context, executemany):
330 parameters, context, executemany):
331 setattr(conn, 'query_start_time', time.time())
331 setattr(conn, 'query_start_time', time.time())
332 log.info(color_sql(">>>>> STARTING QUERY >>>>>"))
332 log.info(color_sql(">>>>> STARTING QUERY >>>>>"))
333 calling_context = find_calling_context(ignore_modules=[
333 calling_context = find_calling_context(ignore_modules=[
334 'rhodecode.lib.caching_query',
334 'rhodecode.lib.caching_query',
335 'rhodecode.model.settings',
335 'rhodecode.model.settings',
336 ])
336 ])
337 if calling_context:
337 if calling_context:
338 log.info(color_sql('call context %s:%s' % (
338 log.info(color_sql('call context %s:%s' % (
339 calling_context.f_code.co_filename,
339 calling_context.f_code.co_filename,
340 calling_context.f_lineno,
340 calling_context.f_lineno,
341 )))
341 )))
342
342
343 def after_cursor_execute(conn, cursor, statement,
343 def after_cursor_execute(conn, cursor, statement,
344 parameters, context, executemany):
344 parameters, context, executemany):
345 delattr(conn, 'query_start_time')
345 delattr(conn, 'query_start_time')
346
346
347 sqlalchemy.event.listen(engine, "before_cursor_execute",
347 sqlalchemy.event.listen(engine, "before_cursor_execute",
348 before_cursor_execute)
348 before_cursor_execute)
349 sqlalchemy.event.listen(engine, "after_cursor_execute",
349 sqlalchemy.event.listen(engine, "after_cursor_execute",
350 after_cursor_execute)
350 after_cursor_execute)
351
351
352 return engine
352 return engine
353
353
354
354
355 def get_encryption_key(config):
355 def get_encryption_key(config):
356 secret = config.get('rhodecode.encrypted_values.secret')
356 secret = config.get('rhodecode.encrypted_values.secret')
357 default = config['beaker.session.secret']
357 default = config['beaker.session.secret']
358 return secret or default
358 return secret or default
359
359
360
360
361 def age(prevdate, now=None, show_short_version=False, show_suffix=True,
361 def age(prevdate, now=None, show_short_version=False, show_suffix=True,
362 short_format=False):
362 short_format=False):
363 """
363 """
364 Turns a datetime into an age string.
364 Turns a datetime into an age string.
365 If show_short_version is True, this generates a shorter string with
365 If show_short_version is True, this generates a shorter string with
366 an approximate age; ex. '1 day ago', rather than '1 day and 23 hours ago'.
366 an approximate age; ex. '1 day ago', rather than '1 day and 23 hours ago'.
367
367
368 * IMPORTANT*
368 * IMPORTANT*
369 Code of this function is written in special way so it's easier to
369 Code of this function is written in special way so it's easier to
370 backport it to javascript. If you mean to update it, please also update
370 backport it to javascript. If you mean to update it, please also update
371 `jquery.timeago-extension.js` file
371 `jquery.timeago-extension.js` file
372
372
373 :param prevdate: datetime object
373 :param prevdate: datetime object
374 :param now: get current time, if not define we use
374 :param now: get current time, if not define we use
375 `datetime.datetime.now()`
375 `datetime.datetime.now()`
376 :param show_short_version: if it should approximate the date and
376 :param show_short_version: if it should approximate the date and
377 return a shorter string
377 return a shorter string
378 :param show_suffix:
378 :param show_suffix:
379 :param short_format: show short format, eg 2D instead of 2 days
379 :param short_format: show short format, eg 2D instead of 2 days
380 :rtype: unicode
380 :rtype: unicode
381 :returns: unicode words describing age
381 :returns: unicode words describing age
382 """
382 """
383 from pylons.i18n.translation import _, ungettext
383 from pylons.i18n.translation import _, ungettext
384
384
385 def _get_relative_delta(now, prevdate):
385 def _get_relative_delta(now, prevdate):
386 base = dateutil.relativedelta.relativedelta(now, prevdate)
386 base = dateutil.relativedelta.relativedelta(now, prevdate)
387 return {
387 return {
388 'year': base.years,
388 'year': base.years,
389 'month': base.months,
389 'month': base.months,
390 'day': base.days,
390 'day': base.days,
391 'hour': base.hours,
391 'hour': base.hours,
392 'minute': base.minutes,
392 'minute': base.minutes,
393 'second': base.seconds,
393 'second': base.seconds,
394 }
394 }
395
395
396 def _is_leap_year(year):
396 def _is_leap_year(year):
397 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
397 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
398
398
399 def get_month(prevdate):
399 def get_month(prevdate):
400 return prevdate.month
400 return prevdate.month
401
401
402 def get_year(prevdate):
402 def get_year(prevdate):
403 return prevdate.year
403 return prevdate.year
404
404
405 now = now or datetime.datetime.now()
405 now = now or datetime.datetime.now()
406 order = ['year', 'month', 'day', 'hour', 'minute', 'second']
406 order = ['year', 'month', 'day', 'hour', 'minute', 'second']
407 deltas = {}
407 deltas = {}
408 future = False
408 future = False
409
409
410 if prevdate > now:
410 if prevdate > now:
411 now_old = now
411 now_old = now
412 now = prevdate
412 now = prevdate
413 prevdate = now_old
413 prevdate = now_old
414 future = True
414 future = True
415 if future:
415 if future:
416 prevdate = prevdate.replace(microsecond=0)
416 prevdate = prevdate.replace(microsecond=0)
417 # Get date parts deltas
417 # Get date parts deltas
418 for part in order:
418 for part in order:
419 rel_delta = _get_relative_delta(now, prevdate)
419 rel_delta = _get_relative_delta(now, prevdate)
420 deltas[part] = rel_delta[part]
420 deltas[part] = rel_delta[part]
421
421
422 # Fix negative offsets (there is 1 second between 10:59:59 and 11:00:00,
422 # Fix negative offsets (there is 1 second between 10:59:59 and 11:00:00,
423 # not 1 hour, -59 minutes and -59 seconds)
423 # not 1 hour, -59 minutes and -59 seconds)
424 offsets = [[5, 60], [4, 60], [3, 24]]
424 offsets = [[5, 60], [4, 60], [3, 24]]
425 for element in offsets: # seconds, minutes, hours
425 for element in offsets: # seconds, minutes, hours
426 num = element[0]
426 num = element[0]
427 length = element[1]
427 length = element[1]
428
428
429 part = order[num]
429 part = order[num]
430 carry_part = order[num - 1]
430 carry_part = order[num - 1]
431
431
432 if deltas[part] < 0:
432 if deltas[part] < 0:
433 deltas[part] += length
433 deltas[part] += length
434 deltas[carry_part] -= 1
434 deltas[carry_part] -= 1
435
435
436 # Same thing for days except that the increment depends on the (variable)
436 # Same thing for days except that the increment depends on the (variable)
437 # number of days in the month
437 # number of days in the month
438 month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
438 month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
439 if deltas['day'] < 0:
439 if deltas['day'] < 0:
440 if get_month(prevdate) == 2 and _is_leap_year(get_year(prevdate)):
440 if get_month(prevdate) == 2 and _is_leap_year(get_year(prevdate)):
441 deltas['day'] += 29
441 deltas['day'] += 29
442 else:
442 else:
443 deltas['day'] += month_lengths[get_month(prevdate) - 1]
443 deltas['day'] += month_lengths[get_month(prevdate) - 1]
444
444
445 deltas['month'] -= 1
445 deltas['month'] -= 1
446
446
447 if deltas['month'] < 0:
447 if deltas['month'] < 0:
448 deltas['month'] += 12
448 deltas['month'] += 12
449 deltas['year'] -= 1
449 deltas['year'] -= 1
450
450
451 # Format the result
451 # Format the result
452 if short_format:
452 if short_format:
453 fmt_funcs = {
453 fmt_funcs = {
454 'year': lambda d: u'%dy' % d,
454 'year': lambda d: u'%dy' % d,
455 'month': lambda d: u'%dm' % d,
455 'month': lambda d: u'%dm' % d,
456 'day': lambda d: u'%dd' % d,
456 'day': lambda d: u'%dd' % d,
457 'hour': lambda d: u'%dh' % d,
457 'hour': lambda d: u'%dh' % d,
458 'minute': lambda d: u'%dmin' % d,
458 'minute': lambda d: u'%dmin' % d,
459 'second': lambda d: u'%dsec' % d,
459 'second': lambda d: u'%dsec' % d,
460 }
460 }
461 else:
461 else:
462 fmt_funcs = {
462 fmt_funcs = {
463 'year': lambda d: ungettext(u'%d year', '%d years', d) % d,
463 'year': lambda d: ungettext(u'%d year', '%d years', d) % d,
464 'month': lambda d: ungettext(u'%d month', '%d months', d) % d,
464 'month': lambda d: ungettext(u'%d month', '%d months', d) % d,
465 'day': lambda d: ungettext(u'%d day', '%d days', d) % d,
465 'day': lambda d: ungettext(u'%d day', '%d days', d) % d,
466 'hour': lambda d: ungettext(u'%d hour', '%d hours', d) % d,
466 'hour': lambda d: ungettext(u'%d hour', '%d hours', d) % d,
467 'minute': lambda d: ungettext(u'%d minute', '%d minutes', d) % d,
467 'minute': lambda d: ungettext(u'%d minute', '%d minutes', d) % d,
468 'second': lambda d: ungettext(u'%d second', '%d seconds', d) % d,
468 'second': lambda d: ungettext(u'%d second', '%d seconds', d) % d,
469 }
469 }
470
470
471 i = 0
471 i = 0
472 for part in order:
472 for part in order:
473 value = deltas[part]
473 value = deltas[part]
474 if value != 0:
474 if value != 0:
475
475
476 if i < 5:
476 if i < 5:
477 sub_part = order[i + 1]
477 sub_part = order[i + 1]
478 sub_value = deltas[sub_part]
478 sub_value = deltas[sub_part]
479 else:
479 else:
480 sub_value = 0
480 sub_value = 0
481
481
482 if sub_value == 0 or show_short_version:
482 if sub_value == 0 or show_short_version:
483 _val = fmt_funcs[part](value)
483 _val = fmt_funcs[part](value)
484 if future:
484 if future:
485 if show_suffix:
485 if show_suffix:
486 return _(u'in %s') % _val
486 return _(u'in %s') % _val
487 else:
487 else:
488 return _val
488 return _val
489
489
490 else:
490 else:
491 if show_suffix:
491 if show_suffix:
492 return _(u'%s ago') % _val
492 return _(u'%s ago') % _val
493 else:
493 else:
494 return _val
494 return _val
495
495
496 val = fmt_funcs[part](value)
496 val = fmt_funcs[part](value)
497 val_detail = fmt_funcs[sub_part](sub_value)
497 val_detail = fmt_funcs[sub_part](sub_value)
498
498
499 if short_format:
499 if short_format:
500 datetime_tmpl = u'%s, %s'
500 datetime_tmpl = u'%s, %s'
501 if show_suffix:
501 if show_suffix:
502 datetime_tmpl = _(u'%s, %s ago')
502 datetime_tmpl = _(u'%s, %s ago')
503 if future:
503 if future:
504 datetime_tmpl = _(u'in %s, %s')
504 datetime_tmpl = _(u'in %s, %s')
505 else:
505 else:
506 datetime_tmpl = _(u'%s and %s')
506 datetime_tmpl = _(u'%s and %s')
507 if show_suffix:
507 if show_suffix:
508 datetime_tmpl = _(u'%s and %s ago')
508 datetime_tmpl = _(u'%s and %s ago')
509 if future:
509 if future:
510 datetime_tmpl = _(u'in %s and %s')
510 datetime_tmpl = _(u'in %s and %s')
511
511
512 return datetime_tmpl % (val, val_detail)
512 return datetime_tmpl % (val, val_detail)
513 i += 1
513 i += 1
514 return _(u'just now')
514 return _(u'just now')
515
515
516
516
517 def uri_filter(uri):
517 def uri_filter(uri):
518 """
518 """
519 Removes user:password from given url string
519 Removes user:password from given url string
520
520
521 :param uri:
521 :param uri:
522 :rtype: unicode
522 :rtype: unicode
523 :returns: filtered list of strings
523 :returns: filtered list of strings
524 """
524 """
525 if not uri:
525 if not uri:
526 return ''
526 return ''
527
527
528 proto = ''
528 proto = ''
529
529
530 for pat in ('https://', 'http://'):
530 for pat in ('https://', 'http://'):
531 if uri.startswith(pat):
531 if uri.startswith(pat):
532 uri = uri[len(pat):]
532 uri = uri[len(pat):]
533 proto = pat
533 proto = pat
534 break
534 break
535
535
536 # remove passwords and username
536 # remove passwords and username
537 uri = uri[uri.find('@') + 1:]
537 uri = uri[uri.find('@') + 1:]
538
538
539 # get the port
539 # get the port
540 cred_pos = uri.find(':')
540 cred_pos = uri.find(':')
541 if cred_pos == -1:
541 if cred_pos == -1:
542 host, port = uri, None
542 host, port = uri, None
543 else:
543 else:
544 host, port = uri[:cred_pos], uri[cred_pos + 1:]
544 host, port = uri[:cred_pos], uri[cred_pos + 1:]
545
545
546 return filter(None, [proto, host, port])
546 return filter(None, [proto, host, port])
547
547
548
548
549 def credentials_filter(uri):
549 def credentials_filter(uri):
550 """
550 """
551 Returns a url with removed credentials
551 Returns a url with removed credentials
552
552
553 :param uri:
553 :param uri:
554 """
554 """
555
555
556 uri = uri_filter(uri)
556 uri = uri_filter(uri)
557 # check if we have port
557 # check if we have port
558 if len(uri) > 2 and uri[2]:
558 if len(uri) > 2 and uri[2]:
559 uri[2] = ':' + uri[2]
559 uri[2] = ':' + uri[2]
560
560
561 return ''.join(uri)
561 return ''.join(uri)
562
562
563
563
564 def get_clone_url(uri_tmpl, qualifed_home_url, repo_name, repo_id, **override):
564 def get_clone_url(uri_tmpl, qualifed_home_url, repo_name, repo_id, **override):
565 parsed_url = urlobject.URLObject(qualifed_home_url)
565 parsed_url = urlobject.URLObject(qualifed_home_url)
566 decoded_path = safe_unicode(urllib.unquote(parsed_url.path.rstrip('/')))
566 decoded_path = safe_unicode(urllib.unquote(parsed_url.path.rstrip('/')))
567 args = {
567 args = {
568 'scheme': parsed_url.scheme,
568 'scheme': parsed_url.scheme,
569 'user': '',
569 'user': '',
570 # path if we use proxy-prefix
570 # path if we use proxy-prefix
571 'netloc': parsed_url.netloc+decoded_path,
571 'netloc': parsed_url.netloc+decoded_path,
572 'prefix': decoded_path,
572 'prefix': decoded_path,
573 'repo': repo_name,
573 'repo': repo_name,
574 'repoid': str(repo_id)
574 'repoid': str(repo_id)
575 }
575 }
576 args.update(override)
576 args.update(override)
577 args['user'] = urllib.quote(safe_str(args['user']))
577 args['user'] = urllib.quote(safe_str(args['user']))
578
578
579 for k, v in args.items():
579 for k, v in args.items():
580 uri_tmpl = uri_tmpl.replace('{%s}' % k, v)
580 uri_tmpl = uri_tmpl.replace('{%s}' % k, v)
581
581
582 # remove leading @ sign if it's present. Case of empty user
582 # remove leading @ sign if it's present. Case of empty user
583 url_obj = urlobject.URLObject(uri_tmpl)
583 url_obj = urlobject.URLObject(uri_tmpl)
584 url = url_obj.with_netloc(url_obj.netloc.lstrip('@'))
584 url = url_obj.with_netloc(url_obj.netloc.lstrip('@'))
585
585
586 return safe_unicode(url)
586 return safe_unicode(url)
587
587
588
588
589 def get_commit_safe(repo, commit_id=None, commit_idx=None, pre_load=None):
589 def get_commit_safe(repo, commit_id=None, commit_idx=None, pre_load=None):
590 """
590 """
591 Safe version of get_commit if this commit doesn't exists for a
591 Safe version of get_commit if this commit doesn't exists for a
592 repository it returns a Dummy one instead
592 repository it returns a Dummy one instead
593
593
594 :param repo: repository instance
594 :param repo: repository instance
595 :param commit_id: commit id as str
595 :param commit_id: commit id as str
596 :param pre_load: optional list of commit attributes to load
596 :param pre_load: optional list of commit attributes to load
597 """
597 """
598 # TODO(skreft): remove these circular imports
598 # TODO(skreft): remove these circular imports
599 from rhodecode.lib.vcs.backends.base import BaseRepository, EmptyCommit
599 from rhodecode.lib.vcs.backends.base import BaseRepository, EmptyCommit
600 from rhodecode.lib.vcs.exceptions import RepositoryError
600 from rhodecode.lib.vcs.exceptions import RepositoryError
601 if not isinstance(repo, BaseRepository):
601 if not isinstance(repo, BaseRepository):
602 raise Exception('You must pass an Repository '
602 raise Exception('You must pass an Repository '
603 'object as first argument got %s', type(repo))
603 'object as first argument got %s', type(repo))
604
604
605 try:
605 try:
606 commit = repo.get_commit(
606 commit = repo.get_commit(
607 commit_id=commit_id, commit_idx=commit_idx, pre_load=pre_load)
607 commit_id=commit_id, commit_idx=commit_idx, pre_load=pre_load)
608 except (RepositoryError, LookupError):
608 except (RepositoryError, LookupError):
609 commit = EmptyCommit()
609 commit = EmptyCommit()
610 return commit
610 return commit
611
611
612
612
613 def datetime_to_time(dt):
613 def datetime_to_time(dt):
614 if dt:
614 if dt:
615 return time.mktime(dt.timetuple())
615 return time.mktime(dt.timetuple())
616
616
617
617
618 def time_to_datetime(tm):
618 def time_to_datetime(tm):
619 if tm:
619 if tm:
620 if isinstance(tm, basestring):
620 if isinstance(tm, basestring):
621 try:
621 try:
622 tm = float(tm)
622 tm = float(tm)
623 except ValueError:
623 except ValueError:
624 return
624 return
625 return datetime.datetime.fromtimestamp(tm)
625 return datetime.datetime.fromtimestamp(tm)
626
626
627
627
628 def time_to_utcdatetime(tm):
628 def time_to_utcdatetime(tm):
629 if tm:
629 if tm:
630 if isinstance(tm, basestring):
630 if isinstance(tm, basestring):
631 try:
631 try:
632 tm = float(tm)
632 tm = float(tm)
633 except ValueError:
633 except ValueError:
634 return
634 return
635 return datetime.datetime.utcfromtimestamp(tm)
635 return datetime.datetime.utcfromtimestamp(tm)
636
636
637
637
638 MENTIONS_REGEX = re.compile(
638 MENTIONS_REGEX = re.compile(
639 # ^@ or @ without any special chars in front
639 # ^@ or @ without any special chars in front
640 r'(?:^@|[^a-zA-Z0-9\-\_\.]@)'
640 r'(?:^@|[^a-zA-Z0-9\-\_\.]@)'
641 # main body starts with letter, then can be . - _
641 # main body starts with letter, then can be . - _
642 r'([a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+)',
642 r'([a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+)',
643 re.VERBOSE | re.MULTILINE)
643 re.VERBOSE | re.MULTILINE)
644
644
645
645
646 def extract_mentioned_users(s):
646 def extract_mentioned_users(s):
647 """
647 """
648 Returns unique usernames from given string s that have @mention
648 Returns unique usernames from given string s that have @mention
649
649
650 :param s: string to get mentions
650 :param s: string to get mentions
651 """
651 """
652 usrs = set()
652 usrs = set()
653 for username in MENTIONS_REGEX.findall(s):
653 for username in MENTIONS_REGEX.findall(s):
654 usrs.add(username)
654 usrs.add(username)
655
655
656 return sorted(list(usrs), key=lambda k: k.lower())
656 return sorted(list(usrs), key=lambda k: k.lower())
657
657
658
658
659 class StrictAttributeDict(dict):
659 class StrictAttributeDict(dict):
660 """
660 """
661 Strict Version of Attribute dict which raises an Attribute error when
661 Strict Version of Attribute dict which raises an Attribute error when
662 requested attribute is not set
662 requested attribute is not set
663 """
663 """
664 def __getattr__(self, attr):
664 def __getattr__(self, attr):
665 try:
665 try:
666 return self[attr]
666 return self[attr]
667 except KeyError:
667 except KeyError:
668 raise AttributeError('%s object has no attribute %s' % (self, attr))
668 raise AttributeError('%s object has no attribute %s' % (
669 self.__class__, attr))
669 __setattr__ = dict.__setitem__
670 __setattr__ = dict.__setitem__
670 __delattr__ = dict.__delitem__
671 __delattr__ = dict.__delitem__
671
672
672
673
673 class AttributeDict(dict):
674 class AttributeDict(dict):
674 def __getattr__(self, attr):
675 def __getattr__(self, attr):
675 return self.get(attr, None)
676 return self.get(attr, None)
676 __setattr__ = dict.__setitem__
677 __setattr__ = dict.__setitem__
677 __delattr__ = dict.__delitem__
678 __delattr__ = dict.__delitem__
678
679
679
680
680 def fix_PATH(os_=None):
681 def fix_PATH(os_=None):
681 """
682 """
682 Get current active python path, and append it to PATH variable to fix
683 Get current active python path, and append it to PATH variable to fix
683 issues of subprocess calls and different python versions
684 issues of subprocess calls and different python versions
684 """
685 """
685 if os_ is None:
686 if os_ is None:
686 import os
687 import os
687 else:
688 else:
688 os = os_
689 os = os_
689
690
690 cur_path = os.path.split(sys.executable)[0]
691 cur_path = os.path.split(sys.executable)[0]
691 if not os.environ['PATH'].startswith(cur_path):
692 if not os.environ['PATH'].startswith(cur_path):
692 os.environ['PATH'] = '%s:%s' % (cur_path, os.environ['PATH'])
693 os.environ['PATH'] = '%s:%s' % (cur_path, os.environ['PATH'])
693
694
694
695
695 def obfuscate_url_pw(engine):
696 def obfuscate_url_pw(engine):
696 _url = engine or ''
697 _url = engine or ''
697 try:
698 try:
698 _url = sqlalchemy.engine.url.make_url(engine)
699 _url = sqlalchemy.engine.url.make_url(engine)
699 if _url.password:
700 if _url.password:
700 _url.password = 'XXXXX'
701 _url.password = 'XXXXX'
701 except Exception:
702 except Exception:
702 pass
703 pass
703 return unicode(_url)
704 return unicode(_url)
704
705
705
706
706 def get_server_url(environ):
707 def get_server_url(environ):
707 req = webob.Request(environ)
708 req = webob.Request(environ)
708 return req.host_url + req.script_name
709 return req.host_url + req.script_name
709
710
710
711
711 def unique_id(hexlen=32):
712 def unique_id(hexlen=32):
712 alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz"
713 alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz"
713 return suuid(truncate_to=hexlen, alphabet=alphabet)
714 return suuid(truncate_to=hexlen, alphabet=alphabet)
714
715
715
716
716 def suuid(url=None, truncate_to=22, alphabet=None):
717 def suuid(url=None, truncate_to=22, alphabet=None):
717 """
718 """
718 Generate and return a short URL safe UUID.
719 Generate and return a short URL safe UUID.
719
720
720 If the url parameter is provided, set the namespace to the provided
721 If the url parameter is provided, set the namespace to the provided
721 URL and generate a UUID.
722 URL and generate a UUID.
722
723
723 :param url to get the uuid for
724 :param url to get the uuid for
724 :truncate_to: truncate the basic 22 UUID to shorter version
725 :truncate_to: truncate the basic 22 UUID to shorter version
725
726
726 The IDs won't be universally unique any longer, but the probability of
727 The IDs won't be universally unique any longer, but the probability of
727 a collision will still be very low.
728 a collision will still be very low.
728 """
729 """
729 # Define our alphabet.
730 # Define our alphabet.
730 _ALPHABET = alphabet or "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
731 _ALPHABET = alphabet or "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
731
732
732 # If no URL is given, generate a random UUID.
733 # If no URL is given, generate a random UUID.
733 if url is None:
734 if url is None:
734 unique_id = uuid.uuid4().int
735 unique_id = uuid.uuid4().int
735 else:
736 else:
736 unique_id = uuid.uuid3(uuid.NAMESPACE_URL, url).int
737 unique_id = uuid.uuid3(uuid.NAMESPACE_URL, url).int
737
738
738 alphabet_length = len(_ALPHABET)
739 alphabet_length = len(_ALPHABET)
739 output = []
740 output = []
740 while unique_id > 0:
741 while unique_id > 0:
741 digit = unique_id % alphabet_length
742 digit = unique_id % alphabet_length
742 output.append(_ALPHABET[digit])
743 output.append(_ALPHABET[digit])
743 unique_id = int(unique_id / alphabet_length)
744 unique_id = int(unique_id / alphabet_length)
744 return "".join(output)[:truncate_to]
745 return "".join(output)[:truncate_to]
745
746
746
747
747 def get_current_rhodecode_user():
748 def get_current_rhodecode_user():
748 """
749 """
749 Gets rhodecode user from threadlocal tmpl_context variable if it's
750 Gets rhodecode user from threadlocal tmpl_context variable if it's
750 defined, else returns None.
751 defined, else returns None.
751 """
752 """
752 from pylons import tmpl_context as c
753 from pylons import tmpl_context as c
753 if hasattr(c, 'rhodecode_user'):
754 if hasattr(c, 'rhodecode_user'):
754 return c.rhodecode_user
755 return c.rhodecode_user
755
756
756 return None
757 return None
757
758
758
759
759 def action_logger_generic(action, namespace=''):
760 def action_logger_generic(action, namespace=''):
760 """
761 """
761 A generic logger for actions useful to the system overview, tries to find
762 A generic logger for actions useful to the system overview, tries to find
762 an acting user for the context of the call otherwise reports unknown user
763 an acting user for the context of the call otherwise reports unknown user
763
764
764 :param action: logging message eg 'comment 5 deleted'
765 :param action: logging message eg 'comment 5 deleted'
765 :param type: string
766 :param type: string
766
767
767 :param namespace: namespace of the logging message eg. 'repo.comments'
768 :param namespace: namespace of the logging message eg. 'repo.comments'
768 :param type: string
769 :param type: string
769
770
770 """
771 """
771
772
772 logger_name = 'rhodecode.actions'
773 logger_name = 'rhodecode.actions'
773
774
774 if namespace:
775 if namespace:
775 logger_name += '.' + namespace
776 logger_name += '.' + namespace
776
777
777 log = logging.getLogger(logger_name)
778 log = logging.getLogger(logger_name)
778
779
779 # get a user if we can
780 # get a user if we can
780 user = get_current_rhodecode_user()
781 user = get_current_rhodecode_user()
781
782
782 logfunc = log.info
783 logfunc = log.info
783
784
784 if not user:
785 if not user:
785 user = '<unknown user>'
786 user = '<unknown user>'
786 logfunc = log.warning
787 logfunc = log.warning
787
788
788 logfunc('Logging action by {}: {}'.format(user, action))
789 logfunc('Logging action by {}: {}'.format(user, action))
789
790
790
791
791 def escape_split(text, sep=',', maxsplit=-1):
792 def escape_split(text, sep=',', maxsplit=-1):
792 r"""
793 r"""
793 Allows for escaping of the separator: e.g. arg='foo\, bar'
794 Allows for escaping of the separator: e.g. arg='foo\, bar'
794
795
795 It should be noted that the way bash et. al. do command line parsing, those
796 It should be noted that the way bash et. al. do command line parsing, those
796 single quotes are required.
797 single quotes are required.
797 """
798 """
798 escaped_sep = r'\%s' % sep
799 escaped_sep = r'\%s' % sep
799
800
800 if escaped_sep not in text:
801 if escaped_sep not in text:
801 return text.split(sep, maxsplit)
802 return text.split(sep, maxsplit)
802
803
803 before, _mid, after = text.partition(escaped_sep)
804 before, _mid, after = text.partition(escaped_sep)
804 startlist = before.split(sep, maxsplit) # a regular split is fine here
805 startlist = before.split(sep, maxsplit) # a regular split is fine here
805 unfinished = startlist[-1]
806 unfinished = startlist[-1]
806 startlist = startlist[:-1]
807 startlist = startlist[:-1]
807
808
808 # recurse because there may be more escaped separators
809 # recurse because there may be more escaped separators
809 endlist = escape_split(after, sep, maxsplit)
810 endlist = escape_split(after, sep, maxsplit)
810
811
811 # finish building the escaped value. we use endlist[0] becaue the first
812 # finish building the escaped value. we use endlist[0] becaue the first
812 # part of the string sent in recursion is the rest of the escaped value.
813 # part of the string sent in recursion is the rest of the escaped value.
813 unfinished += sep + endlist[0]
814 unfinished += sep + endlist[0]
814
815
815 return startlist + [unfinished] + endlist[1:] # put together all the parts
816 return startlist + [unfinished] + endlist[1:] # put together all the parts
816
817
817
818
818 class OptionalAttr(object):
819 class OptionalAttr(object):
819 """
820 """
820 Special Optional Option that defines other attribute. Example::
821 Special Optional Option that defines other attribute. Example::
821
822
822 def test(apiuser, userid=Optional(OAttr('apiuser')):
823 def test(apiuser, userid=Optional(OAttr('apiuser')):
823 user = Optional.extract(userid)
824 user = Optional.extract(userid)
824 # calls
825 # calls
825
826
826 """
827 """
827
828
828 def __init__(self, attr_name):
829 def __init__(self, attr_name):
829 self.attr_name = attr_name
830 self.attr_name = attr_name
830
831
831 def __repr__(self):
832 def __repr__(self):
832 return '<OptionalAttr:%s>' % self.attr_name
833 return '<OptionalAttr:%s>' % self.attr_name
833
834
834 def __call__(self):
835 def __call__(self):
835 return self
836 return self
836
837
837
838
838 # alias
839 # alias
839 OAttr = OptionalAttr
840 OAttr = OptionalAttr
840
841
841
842
842 class Optional(object):
843 class Optional(object):
843 """
844 """
844 Defines an optional parameter::
845 Defines an optional parameter::
845
846
846 param = param.getval() if isinstance(param, Optional) else param
847 param = param.getval() if isinstance(param, Optional) else param
847 param = param() if isinstance(param, Optional) else param
848 param = param() if isinstance(param, Optional) else param
848
849
849 is equivalent of::
850 is equivalent of::
850
851
851 param = Optional.extract(param)
852 param = Optional.extract(param)
852
853
853 """
854 """
854
855
855 def __init__(self, type_):
856 def __init__(self, type_):
856 self.type_ = type_
857 self.type_ = type_
857
858
858 def __repr__(self):
859 def __repr__(self):
859 return '<Optional:%s>' % self.type_.__repr__()
860 return '<Optional:%s>' % self.type_.__repr__()
860
861
861 def __call__(self):
862 def __call__(self):
862 return self.getval()
863 return self.getval()
863
864
864 def getval(self):
865 def getval(self):
865 """
866 """
866 returns value from this Optional instance
867 returns value from this Optional instance
867 """
868 """
868 if isinstance(self.type_, OAttr):
869 if isinstance(self.type_, OAttr):
869 # use params name
870 # use params name
870 return self.type_.attr_name
871 return self.type_.attr_name
871 return self.type_
872 return self.type_
872
873
873 @classmethod
874 @classmethod
874 def extract(cls, val):
875 def extract(cls, val):
875 """
876 """
876 Extracts value from Optional() instance
877 Extracts value from Optional() instance
877
878
878 :param val:
879 :param val:
879 :return: original value if it's not Optional instance else
880 :return: original value if it's not Optional instance else
880 value of instance
881 value of instance
881 """
882 """
882 if isinstance(val, cls):
883 if isinstance(val, cls):
883 return val.getval()
884 return val.getval()
884 return val
885 return val
885
886
886
887
887 def get_routes_generator_for_server_url(server_url):
888 def get_routes_generator_for_server_url(server_url):
888 parsed_url = urlobject.URLObject(server_url)
889 parsed_url = urlobject.URLObject(server_url)
889 netloc = safe_str(parsed_url.netloc)
890 netloc = safe_str(parsed_url.netloc)
890 script_name = safe_str(parsed_url.path)
891 script_name = safe_str(parsed_url.path)
891
892
892 if ':' in netloc:
893 if ':' in netloc:
893 server_name, server_port = netloc.split(':')
894 server_name, server_port = netloc.split(':')
894 else:
895 else:
895 server_name = netloc
896 server_name = netloc
896 server_port = (parsed_url.scheme == 'https' and '443' or '80')
897 server_port = (parsed_url.scheme == 'https' and '443' or '80')
897
898
898 environ = {
899 environ = {
899 'REQUEST_METHOD': 'GET',
900 'REQUEST_METHOD': 'GET',
900 'PATH_INFO': '/',
901 'PATH_INFO': '/',
901 'SERVER_NAME': server_name,
902 'SERVER_NAME': server_name,
902 'SERVER_PORT': server_port,
903 'SERVER_PORT': server_port,
903 'SCRIPT_NAME': script_name,
904 'SCRIPT_NAME': script_name,
904 }
905 }
905 if parsed_url.scheme == 'https':
906 if parsed_url.scheme == 'https':
906 environ['HTTPS'] = 'on'
907 environ['HTTPS'] = 'on'
907 environ['wsgi.url_scheme'] = 'https'
908 environ['wsgi.url_scheme'] = 'https'
908
909
909 return routes.util.URLGenerator(rhodecode.CONFIG['routes.map'], environ)
910 return routes.util.URLGenerator(rhodecode.CONFIG['routes.map'], environ)
910
911
911
912
912 def glob2re(pat):
913 def glob2re(pat):
913 """
914 """
914 Translate a shell PATTERN to a regular expression.
915 Translate a shell PATTERN to a regular expression.
915
916
916 There is no way to quote meta-characters.
917 There is no way to quote meta-characters.
917 """
918 """
918
919
919 i, n = 0, len(pat)
920 i, n = 0, len(pat)
920 res = ''
921 res = ''
921 while i < n:
922 while i < n:
922 c = pat[i]
923 c = pat[i]
923 i = i+1
924 i = i+1
924 if c == '*':
925 if c == '*':
925 #res = res + '.*'
926 #res = res + '.*'
926 res = res + '[^/]*'
927 res = res + '[^/]*'
927 elif c == '?':
928 elif c == '?':
928 #res = res + '.'
929 #res = res + '.'
929 res = res + '[^/]'
930 res = res + '[^/]'
930 elif c == '[':
931 elif c == '[':
931 j = i
932 j = i
932 if j < n and pat[j] == '!':
933 if j < n and pat[j] == '!':
933 j = j+1
934 j = j+1
934 if j < n and pat[j] == ']':
935 if j < n and pat[j] == ']':
935 j = j+1
936 j = j+1
936 while j < n and pat[j] != ']':
937 while j < n and pat[j] != ']':
937 j = j+1
938 j = j+1
938 if j >= n:
939 if j >= n:
939 res = res + '\\['
940 res = res + '\\['
940 else:
941 else:
941 stuff = pat[i:j].replace('\\','\\\\')
942 stuff = pat[i:j].replace('\\','\\\\')
942 i = j+1
943 i = j+1
943 if stuff[0] == '!':
944 if stuff[0] == '!':
944 stuff = '^' + stuff[1:]
945 stuff = '^' + stuff[1:]
945 elif stuff[0] == '^':
946 elif stuff[0] == '^':
946 stuff = '\\' + stuff
947 stuff = '\\' + stuff
947 res = '%s[%s]' % (res, stuff)
948 res = '%s[%s]' % (res, stuff)
948 else:
949 else:
949 res = res + re.escape(c)
950 res = res + re.escape(c)
950 return res + '\Z(?ms)'
951 return res + '\Z(?ms)'
@@ -1,1567 +1,1576 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2014-2016 RhodeCode GmbH
3 # Copyright (C) 2014-2016 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 Base module for all VCS systems
22 Base module for all VCS systems
23 """
23 """
24
24
25 import collections
25 import collections
26 import datetime
26 import datetime
27 import itertools
27 import itertools
28 import logging
28 import logging
29 import os
29 import os
30 import time
30 import time
31 import warnings
31 import warnings
32
32
33 from zope.cachedescriptors.property import Lazy as LazyProperty
33 from zope.cachedescriptors.property import Lazy as LazyProperty
34
34
35 from rhodecode.lib.utils2 import safe_str, safe_unicode
35 from rhodecode.lib.utils2 import safe_str, safe_unicode
36 from rhodecode.lib.vcs import connection
36 from rhodecode.lib.vcs import connection
37 from rhodecode.lib.vcs.utils import author_name, author_email
37 from rhodecode.lib.vcs.utils import author_name, author_email
38 from rhodecode.lib.vcs.conf import settings
38 from rhodecode.lib.vcs.conf import settings
39 from rhodecode.lib.vcs.exceptions import (
39 from rhodecode.lib.vcs.exceptions import (
40 CommitError, EmptyRepositoryError, NodeAlreadyAddedError,
40 CommitError, EmptyRepositoryError, NodeAlreadyAddedError,
41 NodeAlreadyChangedError, NodeAlreadyExistsError, NodeAlreadyRemovedError,
41 NodeAlreadyChangedError, NodeAlreadyExistsError, NodeAlreadyRemovedError,
42 NodeDoesNotExistError, NodeNotChangedError, VCSError,
42 NodeDoesNotExistError, NodeNotChangedError, VCSError,
43 ImproperArchiveTypeError, BranchDoesNotExistError, CommitDoesNotExistError,
43 ImproperArchiveTypeError, BranchDoesNotExistError, CommitDoesNotExistError,
44 RepositoryError)
44 RepositoryError)
45
45
46
46
47 log = logging.getLogger(__name__)
47 log = logging.getLogger(__name__)
48
48
49
49
50 FILEMODE_DEFAULT = 0100644
50 FILEMODE_DEFAULT = 0100644
51 FILEMODE_EXECUTABLE = 0100755
51 FILEMODE_EXECUTABLE = 0100755
52
52
53 Reference = collections.namedtuple('Reference', ('type', 'name', 'commit_id'))
53 Reference = collections.namedtuple('Reference', ('type', 'name', 'commit_id'))
54 MergeResponse = collections.namedtuple(
54 MergeResponse = collections.namedtuple(
55 'MergeResponse',
55 'MergeResponse',
56 ('possible', 'executed', 'merge_ref', 'failure_reason'))
56 ('possible', 'executed', 'merge_ref', 'failure_reason'))
57
57
58
58
59 class MergeFailureReason(object):
59 class MergeFailureReason(object):
60 """
60 """
61 Enumeration with all the reasons why the server side merge could fail.
61 Enumeration with all the reasons why the server side merge could fail.
62
62
63 DO NOT change the number of the reasons, as they may be stored in the
63 DO NOT change the number of the reasons, as they may be stored in the
64 database.
64 database.
65
65
66 Changing the name of a reason is acceptable and encouraged to deprecate old
66 Changing the name of a reason is acceptable and encouraged to deprecate old
67 reasons.
67 reasons.
68 """
68 """
69
69
70 # Everything went well.
70 # Everything went well.
71 NONE = 0
71 NONE = 0
72
72
73 # An unexpected exception was raised. Check the logs for more details.
73 # An unexpected exception was raised. Check the logs for more details.
74 UNKNOWN = 1
74 UNKNOWN = 1
75
75
76 # The merge was not successful, there are conflicts.
76 # The merge was not successful, there are conflicts.
77 MERGE_FAILED = 2
77 MERGE_FAILED = 2
78
78
79 # The merge succeeded but we could not push it to the target repository.
79 # The merge succeeded but we could not push it to the target repository.
80 PUSH_FAILED = 3
80 PUSH_FAILED = 3
81
81
82 # The specified target is not a head in the target repository.
82 # The specified target is not a head in the target repository.
83 TARGET_IS_NOT_HEAD = 4
83 TARGET_IS_NOT_HEAD = 4
84
84
85 # The source repository contains more branches than the target. Pushing
85 # The source repository contains more branches than the target. Pushing
86 # the merge will create additional branches in the target.
86 # the merge will create additional branches in the target.
87 HG_SOURCE_HAS_MORE_BRANCHES = 5
87 HG_SOURCE_HAS_MORE_BRANCHES = 5
88
88
89 # The target reference has multiple heads. That does not allow to correctly
89 # The target reference has multiple heads. That does not allow to correctly
90 # identify the target location. This could only happen for mercurial
90 # identify the target location. This could only happen for mercurial
91 # branches.
91 # branches.
92 HG_TARGET_HAS_MULTIPLE_HEADS = 6
92 HG_TARGET_HAS_MULTIPLE_HEADS = 6
93
93
94 # The target repository is locked
94 # The target repository is locked
95 TARGET_IS_LOCKED = 7
95 TARGET_IS_LOCKED = 7
96
96
97 # Deprecated, use MISSING_TARGET_REF or MISSING_SOURCE_REF instead.
97 # Deprecated, use MISSING_TARGET_REF or MISSING_SOURCE_REF instead.
98 # A involved commit could not be found.
98 # A involved commit could not be found.
99 _DEPRECATED_MISSING_COMMIT = 8
99 _DEPRECATED_MISSING_COMMIT = 8
100
100
101 # The target repo reference is missing.
101 # The target repo reference is missing.
102 MISSING_TARGET_REF = 9
102 MISSING_TARGET_REF = 9
103
103
104 # The source repo reference is missing.
104 # The source repo reference is missing.
105 MISSING_SOURCE_REF = 10
105 MISSING_SOURCE_REF = 10
106
106
107 # The merge was not successful, there are conflicts related to sub
107 # The merge was not successful, there are conflicts related to sub
108 # repositories.
108 # repositories.
109 SUBREPO_MERGE_FAILED = 11
109 SUBREPO_MERGE_FAILED = 11
110
110
111
111
112 class UpdateFailureReason(object):
112 class UpdateFailureReason(object):
113 """
113 """
114 Enumeration with all the reasons why the pull request update could fail.
114 Enumeration with all the reasons why the pull request update could fail.
115
115
116 DO NOT change the number of the reasons, as they may be stored in the
116 DO NOT change the number of the reasons, as they may be stored in the
117 database.
117 database.
118
118
119 Changing the name of a reason is acceptable and encouraged to deprecate old
119 Changing the name of a reason is acceptable and encouraged to deprecate old
120 reasons.
120 reasons.
121 """
121 """
122
122
123 # Everything went well.
123 # Everything went well.
124 NONE = 0
124 NONE = 0
125
125
126 # An unexpected exception was raised. Check the logs for more details.
126 # An unexpected exception was raised. Check the logs for more details.
127 UNKNOWN = 1
127 UNKNOWN = 1
128
128
129 # The pull request is up to date.
129 # The pull request is up to date.
130 NO_CHANGE = 2
130 NO_CHANGE = 2
131
131
132 # The pull request has a reference type that is not supported for update.
132 # The pull request has a reference type that is not supported for update.
133 WRONG_REF_TPYE = 3
133 WRONG_REF_TPYE = 3
134
134
135 # Update failed because the target reference is missing.
135 # Update failed because the target reference is missing.
136 MISSING_TARGET_REF = 4
136 MISSING_TARGET_REF = 4
137
137
138 # Update failed because the source reference is missing.
138 # Update failed because the source reference is missing.
139 MISSING_SOURCE_REF = 5
139 MISSING_SOURCE_REF = 5
140
140
141
141
142 class BaseRepository(object):
142 class BaseRepository(object):
143 """
143 """
144 Base Repository for final backends
144 Base Repository for final backends
145
145
146 .. attribute:: DEFAULT_BRANCH_NAME
146 .. attribute:: DEFAULT_BRANCH_NAME
147
147
148 name of default branch (i.e. "trunk" for svn, "master" for git etc.
148 name of default branch (i.e. "trunk" for svn, "master" for git etc.
149
149
150 .. attribute:: commit_ids
150 .. attribute:: commit_ids
151
151
152 list of all available commit ids, in ascending order
152 list of all available commit ids, in ascending order
153
153
154 .. attribute:: path
154 .. attribute:: path
155
155
156 absolute path to the repository
156 absolute path to the repository
157
157
158 .. attribute:: bookmarks
158 .. attribute:: bookmarks
159
159
160 Mapping from name to :term:`Commit ID` of the bookmark. Empty in case
160 Mapping from name to :term:`Commit ID` of the bookmark. Empty in case
161 there are no bookmarks or the backend implementation does not support
161 there are no bookmarks or the backend implementation does not support
162 bookmarks.
162 bookmarks.
163
163
164 .. attribute:: tags
164 .. attribute:: tags
165
165
166 Mapping from name to :term:`Commit ID` of the tag.
166 Mapping from name to :term:`Commit ID` of the tag.
167
167
168 """
168 """
169
169
170 DEFAULT_BRANCH_NAME = None
170 DEFAULT_BRANCH_NAME = None
171 DEFAULT_CONTACT = u"Unknown"
171 DEFAULT_CONTACT = u"Unknown"
172 DEFAULT_DESCRIPTION = u"unknown"
172 DEFAULT_DESCRIPTION = u"unknown"
173 EMPTY_COMMIT_ID = '0' * 40
173 EMPTY_COMMIT_ID = '0' * 40
174
174
175 path = None
175 path = None
176
176
177 def __init__(self, repo_path, config=None, create=False, **kwargs):
177 def __init__(self, repo_path, config=None, create=False, **kwargs):
178 """
178 """
179 Initializes repository. Raises RepositoryError if repository could
179 Initializes repository. Raises RepositoryError if repository could
180 not be find at the given ``repo_path`` or directory at ``repo_path``
180 not be find at the given ``repo_path`` or directory at ``repo_path``
181 exists and ``create`` is set to True.
181 exists and ``create`` is set to True.
182
182
183 :param repo_path: local path of the repository
183 :param repo_path: local path of the repository
184 :param config: repository configuration
184 :param config: repository configuration
185 :param create=False: if set to True, would try to create repository.
185 :param create=False: if set to True, would try to create repository.
186 :param src_url=None: if set, should be proper url from which repository
186 :param src_url=None: if set, should be proper url from which repository
187 would be cloned; requires ``create`` parameter to be set to True -
187 would be cloned; requires ``create`` parameter to be set to True -
188 raises RepositoryError if src_url is set and create evaluates to
188 raises RepositoryError if src_url is set and create evaluates to
189 False
189 False
190 """
190 """
191 raise NotImplementedError
191 raise NotImplementedError
192
192
193 def __repr__(self):
193 def __repr__(self):
194 return '<%s at %s>' % (self.__class__.__name__, self.path)
194 return '<%s at %s>' % (self.__class__.__name__, self.path)
195
195
196 def __len__(self):
196 def __len__(self):
197 return self.count()
197 return self.count()
198
198
199 def __eq__(self, other):
199 def __eq__(self, other):
200 same_instance = isinstance(other, self.__class__)
200 same_instance = isinstance(other, self.__class__)
201 return same_instance and other.path == self.path
201 return same_instance and other.path == self.path
202
202
203 def __ne__(self, other):
203 def __ne__(self, other):
204 return not self.__eq__(other)
204 return not self.__eq__(other)
205
205
206 @LazyProperty
206 @LazyProperty
207 def EMPTY_COMMIT(self):
207 def EMPTY_COMMIT(self):
208 return EmptyCommit(self.EMPTY_COMMIT_ID)
208 return EmptyCommit(self.EMPTY_COMMIT_ID)
209
209
210 @LazyProperty
210 @LazyProperty
211 def alias(self):
211 def alias(self):
212 for k, v in settings.BACKENDS.items():
212 for k, v in settings.BACKENDS.items():
213 if v.split('.')[-1] == str(self.__class__.__name__):
213 if v.split('.')[-1] == str(self.__class__.__name__):
214 return k
214 return k
215
215
216 @LazyProperty
216 @LazyProperty
217 def name(self):
217 def name(self):
218 return safe_unicode(os.path.basename(self.path))
218 return safe_unicode(os.path.basename(self.path))
219
219
220 @LazyProperty
220 @LazyProperty
221 def description(self):
221 def description(self):
222 raise NotImplementedError
222 raise NotImplementedError
223
223
224 def refs(self):
224 def refs(self):
225 """
225 """
226 returns a `dict` with branches, bookmarks, tags, and closed_branches
226 returns a `dict` with branches, bookmarks, tags, and closed_branches
227 for this repository
227 for this repository
228 """
228 """
229 return dict(
229 return dict(
230 branches=self.branches,
230 branches=self.branches,
231 branches_closed=self.branches_closed,
231 branches_closed=self.branches_closed,
232 tags=self.tags,
232 tags=self.tags,
233 bookmarks=self.bookmarks
233 bookmarks=self.bookmarks
234 )
234 )
235
235
236 @LazyProperty
236 @LazyProperty
237 def branches(self):
237 def branches(self):
238 """
238 """
239 A `dict` which maps branch names to commit ids.
239 A `dict` which maps branch names to commit ids.
240 """
240 """
241 raise NotImplementedError
241 raise NotImplementedError
242
242
243 @LazyProperty
243 @LazyProperty
244 def tags(self):
244 def tags(self):
245 """
245 """
246 A `dict` which maps tags names to commit ids.
246 A `dict` which maps tags names to commit ids.
247 """
247 """
248 raise NotImplementedError
248 raise NotImplementedError
249
249
250 @LazyProperty
250 @LazyProperty
251 def size(self):
251 def size(self):
252 """
252 """
253 Returns combined size in bytes for all repository files
253 Returns combined size in bytes for all repository files
254 """
254 """
255 tip = self.get_commit()
255 tip = self.get_commit()
256 return tip.size
256 return tip.size
257
257
258 def size_at_commit(self, commit_id):
258 def size_at_commit(self, commit_id):
259 commit = self.get_commit(commit_id)
259 commit = self.get_commit(commit_id)
260 return commit.size
260 return commit.size
261
261
262 def is_empty(self):
262 def is_empty(self):
263 return not bool(self.commit_ids)
263 return not bool(self.commit_ids)
264
264
265 @staticmethod
265 @staticmethod
266 def check_url(url, config):
266 def check_url(url, config):
267 """
267 """
268 Function will check given url and try to verify if it's a valid
268 Function will check given url and try to verify if it's a valid
269 link.
269 link.
270 """
270 """
271 raise NotImplementedError
271 raise NotImplementedError
272
272
273 @staticmethod
273 @staticmethod
274 def is_valid_repository(path):
274 def is_valid_repository(path):
275 """
275 """
276 Check if given `path` contains a valid repository of this backend
276 Check if given `path` contains a valid repository of this backend
277 """
277 """
278 raise NotImplementedError
278 raise NotImplementedError
279
279
280 # ==========================================================================
280 # ==========================================================================
281 # COMMITS
281 # COMMITS
282 # ==========================================================================
282 # ==========================================================================
283
283
284 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
284 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
285 """
285 """
286 Returns instance of `BaseCommit` class. If `commit_id` and `commit_idx`
286 Returns instance of `BaseCommit` class. If `commit_id` and `commit_idx`
287 are both None, most recent commit is returned.
287 are both None, most recent commit is returned.
288
288
289 :param pre_load: Optional. List of commit attributes to load.
289 :param pre_load: Optional. List of commit attributes to load.
290
290
291 :raises ``EmptyRepositoryError``: if there are no commits
291 :raises ``EmptyRepositoryError``: if there are no commits
292 """
292 """
293 raise NotImplementedError
293 raise NotImplementedError
294
294
295 def __iter__(self):
295 def __iter__(self):
296 for commit_id in self.commit_ids:
296 for commit_id in self.commit_ids:
297 yield self.get_commit(commit_id=commit_id)
297 yield self.get_commit(commit_id=commit_id)
298
298
299 def get_commits(
299 def get_commits(
300 self, start_id=None, end_id=None, start_date=None, end_date=None,
300 self, start_id=None, end_id=None, start_date=None, end_date=None,
301 branch_name=None, pre_load=None):
301 branch_name=None, pre_load=None):
302 """
302 """
303 Returns iterator of `BaseCommit` objects from start to end
303 Returns iterator of `BaseCommit` objects from start to end
304 not inclusive. This should behave just like a list, ie. end is not
304 not inclusive. This should behave just like a list, ie. end is not
305 inclusive.
305 inclusive.
306
306
307 :param start_id: None or str, must be a valid commit id
307 :param start_id: None or str, must be a valid commit id
308 :param end_id: None or str, must be a valid commit id
308 :param end_id: None or str, must be a valid commit id
309 :param start_date:
309 :param start_date:
310 :param end_date:
310 :param end_date:
311 :param branch_name:
311 :param branch_name:
312 :param pre_load:
312 :param pre_load:
313 """
313 """
314 raise NotImplementedError
314 raise NotImplementedError
315
315
316 def __getitem__(self, key):
316 def __getitem__(self, key):
317 """
317 """
318 Allows index based access to the commit objects of this repository.
318 Allows index based access to the commit objects of this repository.
319 """
319 """
320 pre_load = ["author", "branch", "date", "message", "parents"]
320 pre_load = ["author", "branch", "date", "message", "parents"]
321 if isinstance(key, slice):
321 if isinstance(key, slice):
322 return self._get_range(key, pre_load)
322 return self._get_range(key, pre_load)
323 return self.get_commit(commit_idx=key, pre_load=pre_load)
323 return self.get_commit(commit_idx=key, pre_load=pre_load)
324
324
325 def _get_range(self, slice_obj, pre_load):
325 def _get_range(self, slice_obj, pre_load):
326 for commit_id in self.commit_ids.__getitem__(slice_obj):
326 for commit_id in self.commit_ids.__getitem__(slice_obj):
327 yield self.get_commit(commit_id=commit_id, pre_load=pre_load)
327 yield self.get_commit(commit_id=commit_id, pre_load=pre_load)
328
328
329 def count(self):
329 def count(self):
330 return len(self.commit_ids)
330 return len(self.commit_ids)
331
331
332 def tag(self, name, user, commit_id=None, message=None, date=None, **opts):
332 def tag(self, name, user, commit_id=None, message=None, date=None, **opts):
333 """
333 """
334 Creates and returns a tag for the given ``commit_id``.
334 Creates and returns a tag for the given ``commit_id``.
335
335
336 :param name: name for new tag
336 :param name: name for new tag
337 :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>"
337 :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>"
338 :param commit_id: commit id for which new tag would be created
338 :param commit_id: commit id for which new tag would be created
339 :param message: message of the tag's commit
339 :param message: message of the tag's commit
340 :param date: date of tag's commit
340 :param date: date of tag's commit
341
341
342 :raises TagAlreadyExistError: if tag with same name already exists
342 :raises TagAlreadyExistError: if tag with same name already exists
343 """
343 """
344 raise NotImplementedError
344 raise NotImplementedError
345
345
346 def remove_tag(self, name, user, message=None, date=None):
346 def remove_tag(self, name, user, message=None, date=None):
347 """
347 """
348 Removes tag with the given ``name``.
348 Removes tag with the given ``name``.
349
349
350 :param name: name of the tag to be removed
350 :param name: name of the tag to be removed
351 :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>"
351 :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>"
352 :param message: message of the tag's removal commit
352 :param message: message of the tag's removal commit
353 :param date: date of tag's removal commit
353 :param date: date of tag's removal commit
354
354
355 :raises TagDoesNotExistError: if tag with given name does not exists
355 :raises TagDoesNotExistError: if tag with given name does not exists
356 """
356 """
357 raise NotImplementedError
357 raise NotImplementedError
358
358
359 def get_diff(
359 def get_diff(
360 self, commit1, commit2, path=None, ignore_whitespace=False,
360 self, commit1, commit2, path=None, ignore_whitespace=False,
361 context=3, path1=None):
361 context=3, path1=None):
362 """
362 """
363 Returns (git like) *diff*, as plain text. Shows changes introduced by
363 Returns (git like) *diff*, as plain text. Shows changes introduced by
364 `commit2` since `commit1`.
364 `commit2` since `commit1`.
365
365
366 :param commit1: Entry point from which diff is shown. Can be
366 :param commit1: Entry point from which diff is shown. Can be
367 ``self.EMPTY_COMMIT`` - in this case, patch showing all
367 ``self.EMPTY_COMMIT`` - in this case, patch showing all
368 the changes since empty state of the repository until `commit2`
368 the changes since empty state of the repository until `commit2`
369 :param commit2: Until which commit changes should be shown.
369 :param commit2: Until which commit changes should be shown.
370 :param path: Can be set to a path of a file to create a diff of that
370 :param path: Can be set to a path of a file to create a diff of that
371 file. If `path1` is also set, this value is only associated to
371 file. If `path1` is also set, this value is only associated to
372 `commit2`.
372 `commit2`.
373 :param ignore_whitespace: If set to ``True``, would not show whitespace
373 :param ignore_whitespace: If set to ``True``, would not show whitespace
374 changes. Defaults to ``False``.
374 changes. Defaults to ``False``.
375 :param context: How many lines before/after changed lines should be
375 :param context: How many lines before/after changed lines should be
376 shown. Defaults to ``3``.
376 shown. Defaults to ``3``.
377 :param path1: Can be set to a path to associate with `commit1`. This
377 :param path1: Can be set to a path to associate with `commit1`. This
378 parameter works only for backends which support diff generation for
378 parameter works only for backends which support diff generation for
379 different paths. Other backends will raise a `ValueError` if `path1`
379 different paths. Other backends will raise a `ValueError` if `path1`
380 is set and has a different value than `path`.
380 is set and has a different value than `path`.
381 """
381 """
382 raise NotImplementedError
382 raise NotImplementedError
383
383
384 def strip(self, commit_id, branch=None):
384 def strip(self, commit_id, branch=None):
385 """
385 """
386 Strip given commit_id from the repository
386 Strip given commit_id from the repository
387 """
387 """
388 raise NotImplementedError
388 raise NotImplementedError
389
389
390 def get_common_ancestor(self, commit_id1, commit_id2, repo2):
390 def get_common_ancestor(self, commit_id1, commit_id2, repo2):
391 """
391 """
392 Return a latest common ancestor commit if one exists for this repo
392 Return a latest common ancestor commit if one exists for this repo
393 `commit_id1` vs `commit_id2` from `repo2`.
393 `commit_id1` vs `commit_id2` from `repo2`.
394
394
395 :param commit_id1: Commit it from this repository to use as a
395 :param commit_id1: Commit it from this repository to use as a
396 target for the comparison.
396 target for the comparison.
397 :param commit_id2: Source commit id to use for comparison.
397 :param commit_id2: Source commit id to use for comparison.
398 :param repo2: Source repository to use for comparison.
398 :param repo2: Source repository to use for comparison.
399 """
399 """
400 raise NotImplementedError
400 raise NotImplementedError
401
401
402 def compare(self, commit_id1, commit_id2, repo2, merge, pre_load=None):
402 def compare(self, commit_id1, commit_id2, repo2, merge, pre_load=None):
403 """
403 """
404 Compare this repository's revision `commit_id1` with `commit_id2`.
404 Compare this repository's revision `commit_id1` with `commit_id2`.
405
405
406 Returns a tuple(commits, ancestor) that would be merged from
406 Returns a tuple(commits, ancestor) that would be merged from
407 `commit_id2`. Doing a normal compare (``merge=False``), ``None``
407 `commit_id2`. Doing a normal compare (``merge=False``), ``None``
408 will be returned as ancestor.
408 will be returned as ancestor.
409
409
410 :param commit_id1: Commit it from this repository to use as a
410 :param commit_id1: Commit it from this repository to use as a
411 target for the comparison.
411 target for the comparison.
412 :param commit_id2: Source commit id to use for comparison.
412 :param commit_id2: Source commit id to use for comparison.
413 :param repo2: Source repository to use for comparison.
413 :param repo2: Source repository to use for comparison.
414 :param merge: If set to ``True`` will do a merge compare which also
414 :param merge: If set to ``True`` will do a merge compare which also
415 returns the common ancestor.
415 returns the common ancestor.
416 :param pre_load: Optional. List of commit attributes to load.
416 :param pre_load: Optional. List of commit attributes to load.
417 """
417 """
418 raise NotImplementedError
418 raise NotImplementedError
419
419
420 def merge(self, target_ref, source_repo, source_ref, workspace_id,
420 def merge(self, target_ref, source_repo, source_ref, workspace_id,
421 user_name='', user_email='', message='', dry_run=False,
421 user_name='', user_email='', message='', dry_run=False,
422 use_rebase=False):
422 use_rebase=False):
423 """
423 """
424 Merge the revisions specified in `source_ref` from `source_repo`
424 Merge the revisions specified in `source_ref` from `source_repo`
425 onto the `target_ref` of this repository.
425 onto the `target_ref` of this repository.
426
426
427 `source_ref` and `target_ref` are named tupls with the following
427 `source_ref` and `target_ref` are named tupls with the following
428 fields `type`, `name` and `commit_id`.
428 fields `type`, `name` and `commit_id`.
429
429
430 Returns a MergeResponse named tuple with the following fields
430 Returns a MergeResponse named tuple with the following fields
431 'possible', 'executed', 'source_commit', 'target_commit',
431 'possible', 'executed', 'source_commit', 'target_commit',
432 'merge_commit'.
432 'merge_commit'.
433
433
434 :param target_ref: `target_ref` points to the commit on top of which
434 :param target_ref: `target_ref` points to the commit on top of which
435 the `source_ref` should be merged.
435 the `source_ref` should be merged.
436 :param source_repo: The repository that contains the commits to be
436 :param source_repo: The repository that contains the commits to be
437 merged.
437 merged.
438 :param source_ref: `source_ref` points to the topmost commit from
438 :param source_ref: `source_ref` points to the topmost commit from
439 the `source_repo` which should be merged.
439 the `source_repo` which should be merged.
440 :param workspace_id: `workspace_id` unique identifier.
440 :param workspace_id: `workspace_id` unique identifier.
441 :param user_name: Merge commit `user_name`.
441 :param user_name: Merge commit `user_name`.
442 :param user_email: Merge commit `user_email`.
442 :param user_email: Merge commit `user_email`.
443 :param message: Merge commit `message`.
443 :param message: Merge commit `message`.
444 :param dry_run: If `True` the merge will not take place.
444 :param dry_run: If `True` the merge will not take place.
445 :param use_rebase: If `True` commits from the source will be rebased
445 :param use_rebase: If `True` commits from the source will be rebased
446 on top of the target instead of being merged.
446 on top of the target instead of being merged.
447 """
447 """
448 if dry_run:
448 if dry_run:
449 message = message or 'dry_run_merge_message'
449 message = message or 'dry_run_merge_message'
450 user_email = user_email or 'dry-run-merge@rhodecode.com'
450 user_email = user_email or 'dry-run-merge@rhodecode.com'
451 user_name = user_name or 'Dry-Run User'
451 user_name = user_name or 'Dry-Run User'
452 else:
452 else:
453 if not user_name:
453 if not user_name:
454 raise ValueError('user_name cannot be empty')
454 raise ValueError('user_name cannot be empty')
455 if not user_email:
455 if not user_email:
456 raise ValueError('user_email cannot be empty')
456 raise ValueError('user_email cannot be empty')
457 if not message:
457 if not message:
458 raise ValueError('message cannot be empty')
458 raise ValueError('message cannot be empty')
459
459
460 shadow_repository_path = self._maybe_prepare_merge_workspace(
460 shadow_repository_path = self._maybe_prepare_merge_workspace(
461 workspace_id, target_ref)
461 workspace_id, target_ref)
462
462
463 try:
463 try:
464 return self._merge_repo(
464 return self._merge_repo(
465 shadow_repository_path, target_ref, source_repo,
465 shadow_repository_path, target_ref, source_repo,
466 source_ref, message, user_name, user_email, dry_run=dry_run,
466 source_ref, message, user_name, user_email, dry_run=dry_run,
467 use_rebase=use_rebase)
467 use_rebase=use_rebase)
468 except RepositoryError:
468 except RepositoryError:
469 log.exception(
469 log.exception(
470 'Unexpected failure when running merge, dry-run=%s',
470 'Unexpected failure when running merge, dry-run=%s',
471 dry_run)
471 dry_run)
472 return MergeResponse(
472 return MergeResponse(
473 False, False, None, MergeFailureReason.UNKNOWN)
473 False, False, None, MergeFailureReason.UNKNOWN)
474
474
475 def _merge_repo(self, shadow_repository_path, target_ref,
475 def _merge_repo(self, shadow_repository_path, target_ref,
476 source_repo, source_ref, merge_message,
476 source_repo, source_ref, merge_message,
477 merger_name, merger_email, dry_run=False, use_rebase=False):
477 merger_name, merger_email, dry_run=False, use_rebase=False):
478 """Internal implementation of merge."""
478 """Internal implementation of merge."""
479 raise NotImplementedError
479 raise NotImplementedError
480
480
481 def _maybe_prepare_merge_workspace(self, workspace_id, target_ref):
481 def _maybe_prepare_merge_workspace(self, workspace_id, target_ref):
482 """
482 """
483 Create the merge workspace.
483 Create the merge workspace.
484
484
485 :param workspace_id: `workspace_id` unique identifier.
485 :param workspace_id: `workspace_id` unique identifier.
486 """
486 """
487 raise NotImplementedError
487 raise NotImplementedError
488
488
489 def cleanup_merge_workspace(self, workspace_id):
489 def cleanup_merge_workspace(self, workspace_id):
490 """
490 """
491 Remove merge workspace.
491 Remove merge workspace.
492
492
493 This function MUST not fail in case there is no workspace associated to
493 This function MUST not fail in case there is no workspace associated to
494 the given `workspace_id`.
494 the given `workspace_id`.
495
495
496 :param workspace_id: `workspace_id` unique identifier.
496 :param workspace_id: `workspace_id` unique identifier.
497 """
497 """
498 raise NotImplementedError
498 raise NotImplementedError
499
499
500 # ========== #
500 # ========== #
501 # COMMIT API #
501 # COMMIT API #
502 # ========== #
502 # ========== #
503
503
504 @LazyProperty
504 @LazyProperty
505 def in_memory_commit(self):
505 def in_memory_commit(self):
506 """
506 """
507 Returns :class:`InMemoryCommit` object for this repository.
507 Returns :class:`InMemoryCommit` object for this repository.
508 """
508 """
509 raise NotImplementedError
509 raise NotImplementedError
510
510
511 # ======================== #
511 # ======================== #
512 # UTILITIES FOR SUBCLASSES #
512 # UTILITIES FOR SUBCLASSES #
513 # ======================== #
513 # ======================== #
514
514
515 def _validate_diff_commits(self, commit1, commit2):
515 def _validate_diff_commits(self, commit1, commit2):
516 """
516 """
517 Validates that the given commits are related to this repository.
517 Validates that the given commits are related to this repository.
518
518
519 Intended as a utility for sub classes to have a consistent validation
519 Intended as a utility for sub classes to have a consistent validation
520 of input parameters in methods like :meth:`get_diff`.
520 of input parameters in methods like :meth:`get_diff`.
521 """
521 """
522 self._validate_commit(commit1)
522 self._validate_commit(commit1)
523 self._validate_commit(commit2)
523 self._validate_commit(commit2)
524 if (isinstance(commit1, EmptyCommit) and
524 if (isinstance(commit1, EmptyCommit) and
525 isinstance(commit2, EmptyCommit)):
525 isinstance(commit2, EmptyCommit)):
526 raise ValueError("Cannot compare two empty commits")
526 raise ValueError("Cannot compare two empty commits")
527
527
528 def _validate_commit(self, commit):
528 def _validate_commit(self, commit):
529 if not isinstance(commit, BaseCommit):
529 if not isinstance(commit, BaseCommit):
530 raise TypeError(
530 raise TypeError(
531 "%s is not of type BaseCommit" % repr(commit))
531 "%s is not of type BaseCommit" % repr(commit))
532 if commit.repository != self and not isinstance(commit, EmptyCommit):
532 if commit.repository != self and not isinstance(commit, EmptyCommit):
533 raise ValueError(
533 raise ValueError(
534 "Commit %s must be a valid commit from this repository %s, "
534 "Commit %s must be a valid commit from this repository %s, "
535 "related to this repository instead %s." %
535 "related to this repository instead %s." %
536 (commit, self, commit.repository))
536 (commit, self, commit.repository))
537
537
538 def _validate_commit_id(self, commit_id):
538 def _validate_commit_id(self, commit_id):
539 if not isinstance(commit_id, basestring):
539 if not isinstance(commit_id, basestring):
540 raise TypeError("commit_id must be a string value")
540 raise TypeError("commit_id must be a string value")
541
541
542 def _validate_commit_idx(self, commit_idx):
542 def _validate_commit_idx(self, commit_idx):
543 if not isinstance(commit_idx, (int, long)):
543 if not isinstance(commit_idx, (int, long)):
544 raise TypeError("commit_idx must be a numeric value")
544 raise TypeError("commit_idx must be a numeric value")
545
545
546 def _validate_branch_name(self, branch_name):
546 def _validate_branch_name(self, branch_name):
547 if branch_name and branch_name not in self.branches_all:
547 if branch_name and branch_name not in self.branches_all:
548 msg = ("Branch %s not found in %s" % (branch_name, self))
548 msg = ("Branch %s not found in %s" % (branch_name, self))
549 raise BranchDoesNotExistError(msg)
549 raise BranchDoesNotExistError(msg)
550
550
551 #
551 #
552 # Supporting deprecated API parts
552 # Supporting deprecated API parts
553 # TODO: johbo: consider to move this into a mixin
553 # TODO: johbo: consider to move this into a mixin
554 #
554 #
555
555
556 @property
556 @property
557 def EMPTY_CHANGESET(self):
557 def EMPTY_CHANGESET(self):
558 warnings.warn(
558 warnings.warn(
559 "Use EMPTY_COMMIT or EMPTY_COMMIT_ID instead", DeprecationWarning)
559 "Use EMPTY_COMMIT or EMPTY_COMMIT_ID instead", DeprecationWarning)
560 return self.EMPTY_COMMIT_ID
560 return self.EMPTY_COMMIT_ID
561
561
562 @property
562 @property
563 def revisions(self):
563 def revisions(self):
564 warnings.warn("Use commits attribute instead", DeprecationWarning)
564 warnings.warn("Use commits attribute instead", DeprecationWarning)
565 return self.commit_ids
565 return self.commit_ids
566
566
567 @revisions.setter
567 @revisions.setter
568 def revisions(self, value):
568 def revisions(self, value):
569 warnings.warn("Use commits attribute instead", DeprecationWarning)
569 warnings.warn("Use commits attribute instead", DeprecationWarning)
570 self.commit_ids = value
570 self.commit_ids = value
571
571
572 def get_changeset(self, revision=None, pre_load=None):
572 def get_changeset(self, revision=None, pre_load=None):
573 warnings.warn("Use get_commit instead", DeprecationWarning)
573 warnings.warn("Use get_commit instead", DeprecationWarning)
574 commit_id = None
574 commit_id = None
575 commit_idx = None
575 commit_idx = None
576 if isinstance(revision, basestring):
576 if isinstance(revision, basestring):
577 commit_id = revision
577 commit_id = revision
578 else:
578 else:
579 commit_idx = revision
579 commit_idx = revision
580 return self.get_commit(
580 return self.get_commit(
581 commit_id=commit_id, commit_idx=commit_idx, pre_load=pre_load)
581 commit_id=commit_id, commit_idx=commit_idx, pre_load=pre_load)
582
582
583 def get_changesets(
583 def get_changesets(
584 self, start=None, end=None, start_date=None, end_date=None,
584 self, start=None, end=None, start_date=None, end_date=None,
585 branch_name=None, pre_load=None):
585 branch_name=None, pre_load=None):
586 warnings.warn("Use get_commits instead", DeprecationWarning)
586 warnings.warn("Use get_commits instead", DeprecationWarning)
587 start_id = self._revision_to_commit(start)
587 start_id = self._revision_to_commit(start)
588 end_id = self._revision_to_commit(end)
588 end_id = self._revision_to_commit(end)
589 return self.get_commits(
589 return self.get_commits(
590 start_id=start_id, end_id=end_id, start_date=start_date,
590 start_id=start_id, end_id=end_id, start_date=start_date,
591 end_date=end_date, branch_name=branch_name, pre_load=pre_load)
591 end_date=end_date, branch_name=branch_name, pre_load=pre_load)
592
592
593 def _revision_to_commit(self, revision):
593 def _revision_to_commit(self, revision):
594 """
594 """
595 Translates a revision to a commit_id
595 Translates a revision to a commit_id
596
596
597 Helps to support the old changeset based API which allows to use
597 Helps to support the old changeset based API which allows to use
598 commit ids and commit indices interchangeable.
598 commit ids and commit indices interchangeable.
599 """
599 """
600 if revision is None:
600 if revision is None:
601 return revision
601 return revision
602
602
603 if isinstance(revision, basestring):
603 if isinstance(revision, basestring):
604 commit_id = revision
604 commit_id = revision
605 else:
605 else:
606 commit_id = self.commit_ids[revision]
606 commit_id = self.commit_ids[revision]
607 return commit_id
607 return commit_id
608
608
609 @property
609 @property
610 def in_memory_changeset(self):
610 def in_memory_changeset(self):
611 warnings.warn("Use in_memory_commit instead", DeprecationWarning)
611 warnings.warn("Use in_memory_commit instead", DeprecationWarning)
612 return self.in_memory_commit
612 return self.in_memory_commit
613
613
614
614
615 class BaseCommit(object):
615 class BaseCommit(object):
616 """
616 """
617 Each backend should implement it's commit representation.
617 Each backend should implement it's commit representation.
618
618
619 **Attributes**
619 **Attributes**
620
620
621 ``repository``
621 ``repository``
622 repository object within which commit exists
622 repository object within which commit exists
623
623
624 ``id``
624 ``id``
625 The commit id, may be ``raw_id`` or i.e. for mercurial's tip
625 The commit id, may be ``raw_id`` or i.e. for mercurial's tip
626 just ``tip``.
626 just ``tip``.
627
627
628 ``raw_id``
628 ``raw_id``
629 raw commit representation (i.e. full 40 length sha for git
629 raw commit representation (i.e. full 40 length sha for git
630 backend)
630 backend)
631
631
632 ``short_id``
632 ``short_id``
633 shortened (if apply) version of ``raw_id``; it would be simple
633 shortened (if apply) version of ``raw_id``; it would be simple
634 shortcut for ``raw_id[:12]`` for git/mercurial backends or same
634 shortcut for ``raw_id[:12]`` for git/mercurial backends or same
635 as ``raw_id`` for subversion
635 as ``raw_id`` for subversion
636
636
637 ``idx``
637 ``idx``
638 commit index
638 commit index
639
639
640 ``files``
640 ``files``
641 list of ``FileNode`` (``Node`` with NodeKind.FILE) objects
641 list of ``FileNode`` (``Node`` with NodeKind.FILE) objects
642
642
643 ``dirs``
643 ``dirs``
644 list of ``DirNode`` (``Node`` with NodeKind.DIR) objects
644 list of ``DirNode`` (``Node`` with NodeKind.DIR) objects
645
645
646 ``nodes``
646 ``nodes``
647 combined list of ``Node`` objects
647 combined list of ``Node`` objects
648
648
649 ``author``
649 ``author``
650 author of the commit, as unicode
650 author of the commit, as unicode
651
651
652 ``message``
652 ``message``
653 message of the commit, as unicode
653 message of the commit, as unicode
654
654
655 ``parents``
655 ``parents``
656 list of parent commits
656 list of parent commits
657
657
658 """
658 """
659
659
660 branch = None
660 branch = None
661 """
661 """
662 Depending on the backend this should be set to the branch name of the
662 Depending on the backend this should be set to the branch name of the
663 commit. Backends not supporting branches on commits should leave this
663 commit. Backends not supporting branches on commits should leave this
664 value as ``None``.
664 value as ``None``.
665 """
665 """
666
666
667 _ARCHIVE_PREFIX_TEMPLATE = b'{repo_name}-{short_id}'
667 _ARCHIVE_PREFIX_TEMPLATE = b'{repo_name}-{short_id}'
668 """
668 """
669 This template is used to generate a default prefix for repository archives
669 This template is used to generate a default prefix for repository archives
670 if no prefix has been specified.
670 if no prefix has been specified.
671 """
671 """
672
672
673 def __str__(self):
673 def __str__(self):
674 return '<%s at %s:%s>' % (
674 return '<%s at %s:%s>' % (
675 self.__class__.__name__, self.idx, self.short_id)
675 self.__class__.__name__, self.idx, self.short_id)
676
676
677 def __repr__(self):
677 def __repr__(self):
678 return self.__str__()
678 return self.__str__()
679
679
680 def __unicode__(self):
680 def __unicode__(self):
681 return u'%s:%s' % (self.idx, self.short_id)
681 return u'%s:%s' % (self.idx, self.short_id)
682
682
683 def __eq__(self, other):
683 def __eq__(self, other):
684 same_instance = isinstance(other, self.__class__)
684 same_instance = isinstance(other, self.__class__)
685 return same_instance and self.raw_id == other.raw_id
685 return same_instance and self.raw_id == other.raw_id
686
686
687 def __json__(self):
687 def __json__(self):
688 parents = []
688 parents = []
689 try:
689 try:
690 for parent in self.parents:
690 for parent in self.parents:
691 parents.append({'raw_id': parent.raw_id})
691 parents.append({'raw_id': parent.raw_id})
692 except NotImplementedError:
692 except NotImplementedError:
693 # empty commit doesn't have parents implemented
693 # empty commit doesn't have parents implemented
694 pass
694 pass
695
695
696 return {
696 return {
697 'short_id': self.short_id,
697 'short_id': self.short_id,
698 'raw_id': self.raw_id,
698 'raw_id': self.raw_id,
699 'revision': self.idx,
699 'revision': self.idx,
700 'message': self.message,
700 'message': self.message,
701 'date': self.date,
701 'date': self.date,
702 'author': self.author,
702 'author': self.author,
703 'parents': parents,
703 'parents': parents,
704 'branch': self.branch
704 'branch': self.branch
705 }
705 }
706
706
707 @LazyProperty
707 @LazyProperty
708 def last(self):
708 def last(self):
709 """
709 """
710 ``True`` if this is last commit in repository, ``False``
710 ``True`` if this is last commit in repository, ``False``
711 otherwise; trying to access this attribute while there is no
711 otherwise; trying to access this attribute while there is no
712 commits would raise `EmptyRepositoryError`
712 commits would raise `EmptyRepositoryError`
713 """
713 """
714 if self.repository is None:
714 if self.repository is None:
715 raise CommitError("Cannot check if it's most recent commit")
715 raise CommitError("Cannot check if it's most recent commit")
716 return self.raw_id == self.repository.commit_ids[-1]
716 return self.raw_id == self.repository.commit_ids[-1]
717
717
718 @LazyProperty
718 @LazyProperty
719 def parents(self):
719 def parents(self):
720 """
720 """
721 Returns list of parent commits.
721 Returns list of parent commits.
722 """
722 """
723 raise NotImplementedError
723 raise NotImplementedError
724
724
725 @property
725 @property
726 def merge(self):
726 def merge(self):
727 """
727 """
728 Returns boolean if commit is a merge.
728 Returns boolean if commit is a merge.
729 """
729 """
730 return len(self.parents) > 1
730 return len(self.parents) > 1
731
731
732 @LazyProperty
732 @LazyProperty
733 def children(self):
733 def children(self):
734 """
734 """
735 Returns list of child commits.
735 Returns list of child commits.
736 """
736 """
737 raise NotImplementedError
737 raise NotImplementedError
738
738
739 @LazyProperty
739 @LazyProperty
740 def id(self):
740 def id(self):
741 """
741 """
742 Returns string identifying this commit.
742 Returns string identifying this commit.
743 """
743 """
744 raise NotImplementedError
744 raise NotImplementedError
745
745
746 @LazyProperty
746 @LazyProperty
747 def raw_id(self):
747 def raw_id(self):
748 """
748 """
749 Returns raw string identifying this commit.
749 Returns raw string identifying this commit.
750 """
750 """
751 raise NotImplementedError
751 raise NotImplementedError
752
752
753 @LazyProperty
753 @LazyProperty
754 def short_id(self):
754 def short_id(self):
755 """
755 """
756 Returns shortened version of ``raw_id`` attribute, as string,
756 Returns shortened version of ``raw_id`` attribute, as string,
757 identifying this commit, useful for presentation to users.
757 identifying this commit, useful for presentation to users.
758 """
758 """
759 raise NotImplementedError
759 raise NotImplementedError
760
760
761 @LazyProperty
761 @LazyProperty
762 def idx(self):
762 def idx(self):
763 """
763 """
764 Returns integer identifying this commit.
764 Returns integer identifying this commit.
765 """
765 """
766 raise NotImplementedError
766 raise NotImplementedError
767
767
768 @LazyProperty
768 @LazyProperty
769 def committer(self):
769 def committer(self):
770 """
770 """
771 Returns committer for this commit
771 Returns committer for this commit
772 """
772 """
773 raise NotImplementedError
773 raise NotImplementedError
774
774
775 @LazyProperty
775 @LazyProperty
776 def committer_name(self):
776 def committer_name(self):
777 """
777 """
778 Returns committer name for this commit
778 Returns committer name for this commit
779 """
779 """
780
780
781 return author_name(self.committer)
781 return author_name(self.committer)
782
782
783 @LazyProperty
783 @LazyProperty
784 def committer_email(self):
784 def committer_email(self):
785 """
785 """
786 Returns committer email address for this commit
786 Returns committer email address for this commit
787 """
787 """
788
788
789 return author_email(self.committer)
789 return author_email(self.committer)
790
790
791 @LazyProperty
791 @LazyProperty
792 def author(self):
792 def author(self):
793 """
793 """
794 Returns author for this commit
794 Returns author for this commit
795 """
795 """
796
796
797 raise NotImplementedError
797 raise NotImplementedError
798
798
799 @LazyProperty
799 @LazyProperty
800 def author_name(self):
800 def author_name(self):
801 """
801 """
802 Returns author name for this commit
802 Returns author name for this commit
803 """
803 """
804
804
805 return author_name(self.author)
805 return author_name(self.author)
806
806
807 @LazyProperty
807 @LazyProperty
808 def author_email(self):
808 def author_email(self):
809 """
809 """
810 Returns author email address for this commit
810 Returns author email address for this commit
811 """
811 """
812
812
813 return author_email(self.author)
813 return author_email(self.author)
814
814
815 def get_file_mode(self, path):
815 def get_file_mode(self, path):
816 """
816 """
817 Returns stat mode of the file at `path`.
817 Returns stat mode of the file at `path`.
818 """
818 """
819 raise NotImplementedError
819 raise NotImplementedError
820
820
821 def is_link(self, path):
821 def is_link(self, path):
822 """
822 """
823 Returns ``True`` if given `path` is a symlink
823 Returns ``True`` if given `path` is a symlink
824 """
824 """
825 raise NotImplementedError
825 raise NotImplementedError
826
826
827 def get_file_content(self, path):
827 def get_file_content(self, path):
828 """
828 """
829 Returns content of the file at the given `path`.
829 Returns content of the file at the given `path`.
830 """
830 """
831 raise NotImplementedError
831 raise NotImplementedError
832
832
833 def get_file_size(self, path):
833 def get_file_size(self, path):
834 """
834 """
835 Returns size of the file at the given `path`.
835 Returns size of the file at the given `path`.
836 """
836 """
837 raise NotImplementedError
837 raise NotImplementedError
838
838
839 def get_file_commit(self, path, pre_load=None):
839 def get_file_commit(self, path, pre_load=None):
840 """
840 """
841 Returns last commit of the file at the given `path`.
841 Returns last commit of the file at the given `path`.
842
842
843 :param pre_load: Optional. List of commit attributes to load.
843 :param pre_load: Optional. List of commit attributes to load.
844 """
844 """
845 commits = self.get_file_history(path, limit=1, pre_load=pre_load)
845 commits = self.get_file_history(path, limit=1, pre_load=pre_load)
846 if not commits:
846 if not commits:
847 raise RepositoryError(
847 raise RepositoryError(
848 'Failed to fetch history for path {}. '
848 'Failed to fetch history for path {}. '
849 'Please check if such path exists in your repository'.format(
849 'Please check if such path exists in your repository'.format(
850 path))
850 path))
851 return commits[0]
851 return commits[0]
852
852
853 def get_file_history(self, path, limit=None, pre_load=None):
853 def get_file_history(self, path, limit=None, pre_load=None):
854 """
854 """
855 Returns history of file as reversed list of :class:`BaseCommit`
855 Returns history of file as reversed list of :class:`BaseCommit`
856 objects for which file at given `path` has been modified.
856 objects for which file at given `path` has been modified.
857
857
858 :param limit: Optional. Allows to limit the size of the returned
858 :param limit: Optional. Allows to limit the size of the returned
859 history. This is intended as a hint to the underlying backend, so
859 history. This is intended as a hint to the underlying backend, so
860 that it can apply optimizations depending on the limit.
860 that it can apply optimizations depending on the limit.
861 :param pre_load: Optional. List of commit attributes to load.
861 :param pre_load: Optional. List of commit attributes to load.
862 """
862 """
863 raise NotImplementedError
863 raise NotImplementedError
864
864
865 def get_file_annotate(self, path, pre_load=None):
865 def get_file_annotate(self, path, pre_load=None):
866 """
866 """
867 Returns a generator of four element tuples with
867 Returns a generator of four element tuples with
868 lineno, sha, commit lazy loader and line
868 lineno, sha, commit lazy loader and line
869
869
870 :param pre_load: Optional. List of commit attributes to load.
870 :param pre_load: Optional. List of commit attributes to load.
871 """
871 """
872 raise NotImplementedError
872 raise NotImplementedError
873
873
874 def get_nodes(self, path):
874 def get_nodes(self, path):
875 """
875 """
876 Returns combined ``DirNode`` and ``FileNode`` objects list representing
876 Returns combined ``DirNode`` and ``FileNode`` objects list representing
877 state of commit at the given ``path``.
877 state of commit at the given ``path``.
878
878
879 :raises ``CommitError``: if node at the given ``path`` is not
879 :raises ``CommitError``: if node at the given ``path`` is not
880 instance of ``DirNode``
880 instance of ``DirNode``
881 """
881 """
882 raise NotImplementedError
882 raise NotImplementedError
883
883
884 def get_node(self, path):
884 def get_node(self, path):
885 """
885 """
886 Returns ``Node`` object from the given ``path``.
886 Returns ``Node`` object from the given ``path``.
887
887
888 :raises ``NodeDoesNotExistError``: if there is no node at the given
888 :raises ``NodeDoesNotExistError``: if there is no node at the given
889 ``path``
889 ``path``
890 """
890 """
891 raise NotImplementedError
891 raise NotImplementedError
892
892
893 def get_largefile_node(self, path):
893 def get_largefile_node(self, path):
894 """
894 """
895 Returns the path to largefile from Mercurial storage.
895 Returns the path to largefile from Mercurial storage.
896 """
896 """
897 raise NotImplementedError
897 raise NotImplementedError
898
898
899 def archive_repo(self, file_path, kind='tgz', subrepos=None,
899 def archive_repo(self, file_path, kind='tgz', subrepos=None,
900 prefix=None, write_metadata=False, mtime=None):
900 prefix=None, write_metadata=False, mtime=None):
901 """
901 """
902 Creates an archive containing the contents of the repository.
902 Creates an archive containing the contents of the repository.
903
903
904 :param file_path: path to the file which to create the archive.
904 :param file_path: path to the file which to create the archive.
905 :param kind: one of following: ``"tbz2"``, ``"tgz"``, ``"zip"``.
905 :param kind: one of following: ``"tbz2"``, ``"tgz"``, ``"zip"``.
906 :param prefix: name of root directory in archive.
906 :param prefix: name of root directory in archive.
907 Default is repository name and commit's short_id joined with dash:
907 Default is repository name and commit's short_id joined with dash:
908 ``"{repo_name}-{short_id}"``.
908 ``"{repo_name}-{short_id}"``.
909 :param write_metadata: write a metadata file into archive.
909 :param write_metadata: write a metadata file into archive.
910 :param mtime: custom modification time for archive creation, defaults
910 :param mtime: custom modification time for archive creation, defaults
911 to time.time() if not given.
911 to time.time() if not given.
912
912
913 :raise VCSError: If prefix has a problem.
913 :raise VCSError: If prefix has a problem.
914 """
914 """
915 allowed_kinds = settings.ARCHIVE_SPECS.keys()
915 allowed_kinds = settings.ARCHIVE_SPECS.keys()
916 if kind not in allowed_kinds:
916 if kind not in allowed_kinds:
917 raise ImproperArchiveTypeError(
917 raise ImproperArchiveTypeError(
918 'Archive kind (%s) not supported use one of %s' %
918 'Archive kind (%s) not supported use one of %s' %
919 (kind, allowed_kinds))
919 (kind, allowed_kinds))
920
920
921 prefix = self._validate_archive_prefix(prefix)
921 prefix = self._validate_archive_prefix(prefix)
922
922
923 mtime = mtime or time.mktime(self.date.timetuple())
923 mtime = mtime or time.mktime(self.date.timetuple())
924
924
925 file_info = []
925 file_info = []
926 cur_rev = self.repository.get_commit(commit_id=self.raw_id)
926 cur_rev = self.repository.get_commit(commit_id=self.raw_id)
927 for _r, _d, files in cur_rev.walk('/'):
927 for _r, _d, files in cur_rev.walk('/'):
928 for f in files:
928 for f in files:
929 f_path = os.path.join(prefix, f.path)
929 f_path = os.path.join(prefix, f.path)
930 file_info.append(
930 file_info.append(
931 (f_path, f.mode, f.is_link(), f.raw_bytes))
931 (f_path, f.mode, f.is_link(), f.raw_bytes))
932
932
933 if write_metadata:
933 if write_metadata:
934 metadata = [
934 metadata = [
935 ('repo_name', self.repository.name),
935 ('repo_name', self.repository.name),
936 ('rev', self.raw_id),
936 ('rev', self.raw_id),
937 ('create_time', mtime),
937 ('create_time', mtime),
938 ('branch', self.branch),
938 ('branch', self.branch),
939 ('tags', ','.join(self.tags)),
939 ('tags', ','.join(self.tags)),
940 ]
940 ]
941 meta = ["%s:%s" % (f_name, value) for f_name, value in metadata]
941 meta = ["%s:%s" % (f_name, value) for f_name, value in metadata]
942 file_info.append(('.archival.txt', 0644, False, '\n'.join(meta)))
942 file_info.append(('.archival.txt', 0644, False, '\n'.join(meta)))
943
943
944 connection.Hg.archive_repo(file_path, mtime, file_info, kind)
944 connection.Hg.archive_repo(file_path, mtime, file_info, kind)
945
945
946 def _validate_archive_prefix(self, prefix):
946 def _validate_archive_prefix(self, prefix):
947 if prefix is None:
947 if prefix is None:
948 prefix = self._ARCHIVE_PREFIX_TEMPLATE.format(
948 prefix = self._ARCHIVE_PREFIX_TEMPLATE.format(
949 repo_name=safe_str(self.repository.name),
949 repo_name=safe_str(self.repository.name),
950 short_id=self.short_id)
950 short_id=self.short_id)
951 elif not isinstance(prefix, str):
951 elif not isinstance(prefix, str):
952 raise ValueError("prefix not a bytes object: %s" % repr(prefix))
952 raise ValueError("prefix not a bytes object: %s" % repr(prefix))
953 elif prefix.startswith('/'):
953 elif prefix.startswith('/'):
954 raise VCSError("Prefix cannot start with leading slash")
954 raise VCSError("Prefix cannot start with leading slash")
955 elif prefix.strip() == '':
955 elif prefix.strip() == '':
956 raise VCSError("Prefix cannot be empty")
956 raise VCSError("Prefix cannot be empty")
957 return prefix
957 return prefix
958
958
959 @LazyProperty
959 @LazyProperty
960 def root(self):
960 def root(self):
961 """
961 """
962 Returns ``RootNode`` object for this commit.
962 Returns ``RootNode`` object for this commit.
963 """
963 """
964 return self.get_node('')
964 return self.get_node('')
965
965
966 def next(self, branch=None):
966 def next(self, branch=None):
967 """
967 """
968 Returns next commit from current, if branch is gives it will return
968 Returns next commit from current, if branch is gives it will return
969 next commit belonging to this branch
969 next commit belonging to this branch
970
970
971 :param branch: show commits within the given named branch
971 :param branch: show commits within the given named branch
972 """
972 """
973 indexes = xrange(self.idx + 1, self.repository.count())
973 indexes = xrange(self.idx + 1, self.repository.count())
974 return self._find_next(indexes, branch)
974 return self._find_next(indexes, branch)
975
975
976 def prev(self, branch=None):
976 def prev(self, branch=None):
977 """
977 """
978 Returns previous commit from current, if branch is gives it will
978 Returns previous commit from current, if branch is gives it will
979 return previous commit belonging to this branch
979 return previous commit belonging to this branch
980
980
981 :param branch: show commit within the given named branch
981 :param branch: show commit within the given named branch
982 """
982 """
983 indexes = xrange(self.idx - 1, -1, -1)
983 indexes = xrange(self.idx - 1, -1, -1)
984 return self._find_next(indexes, branch)
984 return self._find_next(indexes, branch)
985
985
986 def _find_next(self, indexes, branch=None):
986 def _find_next(self, indexes, branch=None):
987 if branch and self.branch != branch:
987 if branch and self.branch != branch:
988 raise VCSError('Branch option used on commit not belonging '
988 raise VCSError('Branch option used on commit not belonging '
989 'to that branch')
989 'to that branch')
990
990
991 for next_idx in indexes:
991 for next_idx in indexes:
992 commit = self.repository.get_commit(commit_idx=next_idx)
992 commit = self.repository.get_commit(commit_idx=next_idx)
993 if branch and branch != commit.branch:
993 if branch and branch != commit.branch:
994 continue
994 continue
995 return commit
995 return commit
996 raise CommitDoesNotExistError
996 raise CommitDoesNotExistError
997
997
998 def diff(self, ignore_whitespace=True, context=3):
998 def diff(self, ignore_whitespace=True, context=3):
999 """
999 """
1000 Returns a `Diff` object representing the change made by this commit.
1000 Returns a `Diff` object representing the change made by this commit.
1001 """
1001 """
1002 parent = (
1002 parent = (
1003 self.parents[0] if self.parents else self.repository.EMPTY_COMMIT)
1003 self.parents[0] if self.parents else self.repository.EMPTY_COMMIT)
1004 diff = self.repository.get_diff(
1004 diff = self.repository.get_diff(
1005 parent, self,
1005 parent, self,
1006 ignore_whitespace=ignore_whitespace,
1006 ignore_whitespace=ignore_whitespace,
1007 context=context)
1007 context=context)
1008 return diff
1008 return diff
1009
1009
1010 @LazyProperty
1010 @LazyProperty
1011 def added(self):
1011 def added(self):
1012 """
1012 """
1013 Returns list of added ``FileNode`` objects.
1013 Returns list of added ``FileNode`` objects.
1014 """
1014 """
1015 raise NotImplementedError
1015 raise NotImplementedError
1016
1016
1017 @LazyProperty
1017 @LazyProperty
1018 def changed(self):
1018 def changed(self):
1019 """
1019 """
1020 Returns list of modified ``FileNode`` objects.
1020 Returns list of modified ``FileNode`` objects.
1021 """
1021 """
1022 raise NotImplementedError
1022 raise NotImplementedError
1023
1023
1024 @LazyProperty
1024 @LazyProperty
1025 def removed(self):
1025 def removed(self):
1026 """
1026 """
1027 Returns list of removed ``FileNode`` objects.
1027 Returns list of removed ``FileNode`` objects.
1028 """
1028 """
1029 raise NotImplementedError
1029 raise NotImplementedError
1030
1030
1031 @LazyProperty
1031 @LazyProperty
1032 def size(self):
1032 def size(self):
1033 """
1033 """
1034 Returns total number of bytes from contents of all filenodes.
1034 Returns total number of bytes from contents of all filenodes.
1035 """
1035 """
1036 return sum((node.size for node in self.get_filenodes_generator()))
1036 return sum((node.size for node in self.get_filenodes_generator()))
1037
1037
1038 def walk(self, topurl=''):
1038 def walk(self, topurl=''):
1039 """
1039 """
1040 Similar to os.walk method. Insted of filesystem it walks through
1040 Similar to os.walk method. Insted of filesystem it walks through
1041 commit starting at given ``topurl``. Returns generator of tuples
1041 commit starting at given ``topurl``. Returns generator of tuples
1042 (topnode, dirnodes, filenodes).
1042 (topnode, dirnodes, filenodes).
1043 """
1043 """
1044 topnode = self.get_node(topurl)
1044 topnode = self.get_node(topurl)
1045 if not topnode.is_dir():
1045 if not topnode.is_dir():
1046 return
1046 return
1047 yield (topnode, topnode.dirs, topnode.files)
1047 yield (topnode, topnode.dirs, topnode.files)
1048 for dirnode in topnode.dirs:
1048 for dirnode in topnode.dirs:
1049 for tup in self.walk(dirnode.path):
1049 for tup in self.walk(dirnode.path):
1050 yield tup
1050 yield tup
1051
1051
1052 def get_filenodes_generator(self):
1052 def get_filenodes_generator(self):
1053 """
1053 """
1054 Returns generator that yields *all* file nodes.
1054 Returns generator that yields *all* file nodes.
1055 """
1055 """
1056 for topnode, dirs, files in self.walk():
1056 for topnode, dirs, files in self.walk():
1057 for node in files:
1057 for node in files:
1058 yield node
1058 yield node
1059
1059
1060 #
1060 #
1061 # Utilities for sub classes to support consistent behavior
1061 # Utilities for sub classes to support consistent behavior
1062 #
1062 #
1063
1063
1064 def no_node_at_path(self, path):
1064 def no_node_at_path(self, path):
1065 return NodeDoesNotExistError(
1065 return NodeDoesNotExistError(
1066 "There is no file nor directory at the given path: "
1066 "There is no file nor directory at the given path: "
1067 "'%s' at commit %s" % (path, self.short_id))
1067 "'%s' at commit %s" % (path, self.short_id))
1068
1068
1069 def _fix_path(self, path):
1069 def _fix_path(self, path):
1070 """
1070 """
1071 Paths are stored without trailing slash so we need to get rid off it if
1071 Paths are stored without trailing slash so we need to get rid off it if
1072 needed.
1072 needed.
1073 """
1073 """
1074 return path.rstrip('/')
1074 return path.rstrip('/')
1075
1075
1076 #
1076 #
1077 # Deprecated API based on changesets
1077 # Deprecated API based on changesets
1078 #
1078 #
1079
1079
1080 @property
1080 @property
1081 def revision(self):
1081 def revision(self):
1082 warnings.warn("Use idx instead", DeprecationWarning)
1082 warnings.warn("Use idx instead", DeprecationWarning)
1083 return self.idx
1083 return self.idx
1084
1084
1085 @revision.setter
1085 @revision.setter
1086 def revision(self, value):
1086 def revision(self, value):
1087 warnings.warn("Use idx instead", DeprecationWarning)
1087 warnings.warn("Use idx instead", DeprecationWarning)
1088 self.idx = value
1088 self.idx = value
1089
1089
1090 def get_file_changeset(self, path):
1090 def get_file_changeset(self, path):
1091 warnings.warn("Use get_file_commit instead", DeprecationWarning)
1091 warnings.warn("Use get_file_commit instead", DeprecationWarning)
1092 return self.get_file_commit(path)
1092 return self.get_file_commit(path)
1093
1093
1094
1094
1095 class BaseChangesetClass(type):
1095 class BaseChangesetClass(type):
1096
1096
1097 def __instancecheck__(self, instance):
1097 def __instancecheck__(self, instance):
1098 return isinstance(instance, BaseCommit)
1098 return isinstance(instance, BaseCommit)
1099
1099
1100
1100
1101 class BaseChangeset(BaseCommit):
1101 class BaseChangeset(BaseCommit):
1102
1102
1103 __metaclass__ = BaseChangesetClass
1103 __metaclass__ = BaseChangesetClass
1104
1104
1105 def __new__(cls, *args, **kwargs):
1105 def __new__(cls, *args, **kwargs):
1106 warnings.warn(
1106 warnings.warn(
1107 "Use BaseCommit instead of BaseChangeset", DeprecationWarning)
1107 "Use BaseCommit instead of BaseChangeset", DeprecationWarning)
1108 return super(BaseChangeset, cls).__new__(cls, *args, **kwargs)
1108 return super(BaseChangeset, cls).__new__(cls, *args, **kwargs)
1109
1109
1110
1110
1111 class BaseInMemoryCommit(object):
1111 class BaseInMemoryCommit(object):
1112 """
1112 """
1113 Represents differences between repository's state (most recent head) and
1113 Represents differences between repository's state (most recent head) and
1114 changes made *in place*.
1114 changes made *in place*.
1115
1115
1116 **Attributes**
1116 **Attributes**
1117
1117
1118 ``repository``
1118 ``repository``
1119 repository object for this in-memory-commit
1119 repository object for this in-memory-commit
1120
1120
1121 ``added``
1121 ``added``
1122 list of ``FileNode`` objects marked as *added*
1122 list of ``FileNode`` objects marked as *added*
1123
1123
1124 ``changed``
1124 ``changed``
1125 list of ``FileNode`` objects marked as *changed*
1125 list of ``FileNode`` objects marked as *changed*
1126
1126
1127 ``removed``
1127 ``removed``
1128 list of ``FileNode`` or ``RemovedFileNode`` objects marked to be
1128 list of ``FileNode`` or ``RemovedFileNode`` objects marked to be
1129 *removed*
1129 *removed*
1130
1130
1131 ``parents``
1131 ``parents``
1132 list of :class:`BaseCommit` instances representing parents of
1132 list of :class:`BaseCommit` instances representing parents of
1133 in-memory commit. Should always be 2-element sequence.
1133 in-memory commit. Should always be 2-element sequence.
1134
1134
1135 """
1135 """
1136
1136
1137 def __init__(self, repository):
1137 def __init__(self, repository):
1138 self.repository = repository
1138 self.repository = repository
1139 self.added = []
1139 self.added = []
1140 self.changed = []
1140 self.changed = []
1141 self.removed = []
1141 self.removed = []
1142 self.parents = []
1142 self.parents = []
1143
1143
1144 def add(self, *filenodes):
1144 def add(self, *filenodes):
1145 """
1145 """
1146 Marks given ``FileNode`` objects as *to be committed*.
1146 Marks given ``FileNode`` objects as *to be committed*.
1147
1147
1148 :raises ``NodeAlreadyExistsError``: if node with same path exists at
1148 :raises ``NodeAlreadyExistsError``: if node with same path exists at
1149 latest commit
1149 latest commit
1150 :raises ``NodeAlreadyAddedError``: if node with same path is already
1150 :raises ``NodeAlreadyAddedError``: if node with same path is already
1151 marked as *added*
1151 marked as *added*
1152 """
1152 """
1153 # Check if not already marked as *added* first
1153 # Check if not already marked as *added* first
1154 for node in filenodes:
1154 for node in filenodes:
1155 if node.path in (n.path for n in self.added):
1155 if node.path in (n.path for n in self.added):
1156 raise NodeAlreadyAddedError(
1156 raise NodeAlreadyAddedError(
1157 "Such FileNode %s is already marked for addition"
1157 "Such FileNode %s is already marked for addition"
1158 % node.path)
1158 % node.path)
1159 for node in filenodes:
1159 for node in filenodes:
1160 self.added.append(node)
1160 self.added.append(node)
1161
1161
1162 def change(self, *filenodes):
1162 def change(self, *filenodes):
1163 """
1163 """
1164 Marks given ``FileNode`` objects to be *changed* in next commit.
1164 Marks given ``FileNode`` objects to be *changed* in next commit.
1165
1165
1166 :raises ``EmptyRepositoryError``: if there are no commits yet
1166 :raises ``EmptyRepositoryError``: if there are no commits yet
1167 :raises ``NodeAlreadyExistsError``: if node with same path is already
1167 :raises ``NodeAlreadyExistsError``: if node with same path is already
1168 marked to be *changed*
1168 marked to be *changed*
1169 :raises ``NodeAlreadyRemovedError``: if node with same path is already
1169 :raises ``NodeAlreadyRemovedError``: if node with same path is already
1170 marked to be *removed*
1170 marked to be *removed*
1171 :raises ``NodeDoesNotExistError``: if node doesn't exist in latest
1171 :raises ``NodeDoesNotExistError``: if node doesn't exist in latest
1172 commit
1172 commit
1173 :raises ``NodeNotChangedError``: if node hasn't really be changed
1173 :raises ``NodeNotChangedError``: if node hasn't really be changed
1174 """
1174 """
1175 for node in filenodes:
1175 for node in filenodes:
1176 if node.path in (n.path for n in self.removed):
1176 if node.path in (n.path for n in self.removed):
1177 raise NodeAlreadyRemovedError(
1177 raise NodeAlreadyRemovedError(
1178 "Node at %s is already marked as removed" % node.path)
1178 "Node at %s is already marked as removed" % node.path)
1179 try:
1179 try:
1180 self.repository.get_commit()
1180 self.repository.get_commit()
1181 except EmptyRepositoryError:
1181 except EmptyRepositoryError:
1182 raise EmptyRepositoryError(
1182 raise EmptyRepositoryError(
1183 "Nothing to change - try to *add* new nodes rather than "
1183 "Nothing to change - try to *add* new nodes rather than "
1184 "changing them")
1184 "changing them")
1185 for node in filenodes:
1185 for node in filenodes:
1186 if node.path in (n.path for n in self.changed):
1186 if node.path in (n.path for n in self.changed):
1187 raise NodeAlreadyChangedError(
1187 raise NodeAlreadyChangedError(
1188 "Node at '%s' is already marked as changed" % node.path)
1188 "Node at '%s' is already marked as changed" % node.path)
1189 self.changed.append(node)
1189 self.changed.append(node)
1190
1190
1191 def remove(self, *filenodes):
1191 def remove(self, *filenodes):
1192 """
1192 """
1193 Marks given ``FileNode`` (or ``RemovedFileNode``) objects to be
1193 Marks given ``FileNode`` (or ``RemovedFileNode``) objects to be
1194 *removed* in next commit.
1194 *removed* in next commit.
1195
1195
1196 :raises ``NodeAlreadyRemovedError``: if node has been already marked to
1196 :raises ``NodeAlreadyRemovedError``: if node has been already marked to
1197 be *removed*
1197 be *removed*
1198 :raises ``NodeAlreadyChangedError``: if node has been already marked to
1198 :raises ``NodeAlreadyChangedError``: if node has been already marked to
1199 be *changed*
1199 be *changed*
1200 """
1200 """
1201 for node in filenodes:
1201 for node in filenodes:
1202 if node.path in (n.path for n in self.removed):
1202 if node.path in (n.path for n in self.removed):
1203 raise NodeAlreadyRemovedError(
1203 raise NodeAlreadyRemovedError(
1204 "Node is already marked to for removal at %s" % node.path)
1204 "Node is already marked to for removal at %s" % node.path)
1205 if node.path in (n.path for n in self.changed):
1205 if node.path in (n.path for n in self.changed):
1206 raise NodeAlreadyChangedError(
1206 raise NodeAlreadyChangedError(
1207 "Node is already marked to be changed at %s" % node.path)
1207 "Node is already marked to be changed at %s" % node.path)
1208 # We only mark node as *removed* - real removal is done by
1208 # We only mark node as *removed* - real removal is done by
1209 # commit method
1209 # commit method
1210 self.removed.append(node)
1210 self.removed.append(node)
1211
1211
1212 def reset(self):
1212 def reset(self):
1213 """
1213 """
1214 Resets this instance to initial state (cleans ``added``, ``changed``
1214 Resets this instance to initial state (cleans ``added``, ``changed``
1215 and ``removed`` lists).
1215 and ``removed`` lists).
1216 """
1216 """
1217 self.added = []
1217 self.added = []
1218 self.changed = []
1218 self.changed = []
1219 self.removed = []
1219 self.removed = []
1220 self.parents = []
1220 self.parents = []
1221
1221
1222 def get_ipaths(self):
1222 def get_ipaths(self):
1223 """
1223 """
1224 Returns generator of paths from nodes marked as added, changed or
1224 Returns generator of paths from nodes marked as added, changed or
1225 removed.
1225 removed.
1226 """
1226 """
1227 for node in itertools.chain(self.added, self.changed, self.removed):
1227 for node in itertools.chain(self.added, self.changed, self.removed):
1228 yield node.path
1228 yield node.path
1229
1229
1230 def get_paths(self):
1230 def get_paths(self):
1231 """
1231 """
1232 Returns list of paths from nodes marked as added, changed or removed.
1232 Returns list of paths from nodes marked as added, changed or removed.
1233 """
1233 """
1234 return list(self.get_ipaths())
1234 return list(self.get_ipaths())
1235
1235
1236 def check_integrity(self, parents=None):
1236 def check_integrity(self, parents=None):
1237 """
1237 """
1238 Checks in-memory commit's integrity. Also, sets parents if not
1238 Checks in-memory commit's integrity. Also, sets parents if not
1239 already set.
1239 already set.
1240
1240
1241 :raises CommitError: if any error occurs (i.e.
1241 :raises CommitError: if any error occurs (i.e.
1242 ``NodeDoesNotExistError``).
1242 ``NodeDoesNotExistError``).
1243 """
1243 """
1244 if not self.parents:
1244 if not self.parents:
1245 parents = parents or []
1245 parents = parents or []
1246 if len(parents) == 0:
1246 if len(parents) == 0:
1247 try:
1247 try:
1248 parents = [self.repository.get_commit(), None]
1248 parents = [self.repository.get_commit(), None]
1249 except EmptyRepositoryError:
1249 except EmptyRepositoryError:
1250 parents = [None, None]
1250 parents = [None, None]
1251 elif len(parents) == 1:
1251 elif len(parents) == 1:
1252 parents += [None]
1252 parents += [None]
1253 self.parents = parents
1253 self.parents = parents
1254
1254
1255 # Local parents, only if not None
1255 # Local parents, only if not None
1256 parents = [p for p in self.parents if p]
1256 parents = [p for p in self.parents if p]
1257
1257
1258 # Check nodes marked as added
1258 # Check nodes marked as added
1259 for p in parents:
1259 for p in parents:
1260 for node in self.added:
1260 for node in self.added:
1261 try:
1261 try:
1262 p.get_node(node.path)
1262 p.get_node(node.path)
1263 except NodeDoesNotExistError:
1263 except NodeDoesNotExistError:
1264 pass
1264 pass
1265 else:
1265 else:
1266 raise NodeAlreadyExistsError(
1266 raise NodeAlreadyExistsError(
1267 "Node `%s` already exists at %s" % (node.path, p))
1267 "Node `%s` already exists at %s" % (node.path, p))
1268
1268
1269 # Check nodes marked as changed
1269 # Check nodes marked as changed
1270 missing = set(self.changed)
1270 missing = set(self.changed)
1271 not_changed = set(self.changed)
1271 not_changed = set(self.changed)
1272 if self.changed and not parents:
1272 if self.changed and not parents:
1273 raise NodeDoesNotExistError(str(self.changed[0].path))
1273 raise NodeDoesNotExistError(str(self.changed[0].path))
1274 for p in parents:
1274 for p in parents:
1275 for node in self.changed:
1275 for node in self.changed:
1276 try:
1276 try:
1277 old = p.get_node(node.path)
1277 old = p.get_node(node.path)
1278 missing.remove(node)
1278 missing.remove(node)
1279 # if content actually changed, remove node from not_changed
1279 # if content actually changed, remove node from not_changed
1280 if old.content != node.content:
1280 if old.content != node.content:
1281 not_changed.remove(node)
1281 not_changed.remove(node)
1282 except NodeDoesNotExistError:
1282 except NodeDoesNotExistError:
1283 pass
1283 pass
1284 if self.changed and missing:
1284 if self.changed and missing:
1285 raise NodeDoesNotExistError(
1285 raise NodeDoesNotExistError(
1286 "Node `%s` marked as modified but missing in parents: %s"
1286 "Node `%s` marked as modified but missing in parents: %s"
1287 % (node.path, parents))
1287 % (node.path, parents))
1288
1288
1289 if self.changed and not_changed:
1289 if self.changed and not_changed:
1290 raise NodeNotChangedError(
1290 raise NodeNotChangedError(
1291 "Node `%s` wasn't actually changed (parents: %s)"
1291 "Node `%s` wasn't actually changed (parents: %s)"
1292 % (not_changed.pop().path, parents))
1292 % (not_changed.pop().path, parents))
1293
1293
1294 # Check nodes marked as removed
1294 # Check nodes marked as removed
1295 if self.removed and not parents:
1295 if self.removed and not parents:
1296 raise NodeDoesNotExistError(
1296 raise NodeDoesNotExistError(
1297 "Cannot remove node at %s as there "
1297 "Cannot remove node at %s as there "
1298 "were no parents specified" % self.removed[0].path)
1298 "were no parents specified" % self.removed[0].path)
1299 really_removed = set()
1299 really_removed = set()
1300 for p in parents:
1300 for p in parents:
1301 for node in self.removed:
1301 for node in self.removed:
1302 try:
1302 try:
1303 p.get_node(node.path)
1303 p.get_node(node.path)
1304 really_removed.add(node)
1304 really_removed.add(node)
1305 except CommitError:
1305 except CommitError:
1306 pass
1306 pass
1307 not_removed = set(self.removed) - really_removed
1307 not_removed = set(self.removed) - really_removed
1308 if not_removed:
1308 if not_removed:
1309 # TODO: johbo: This code branch does not seem to be covered
1309 # TODO: johbo: This code branch does not seem to be covered
1310 raise NodeDoesNotExistError(
1310 raise NodeDoesNotExistError(
1311 "Cannot remove node at %s from "
1311 "Cannot remove node at %s from "
1312 "following parents: %s" % (not_removed, parents))
1312 "following parents: %s" % (not_removed, parents))
1313
1313
1314 def commit(
1314 def commit(
1315 self, message, author, parents=None, branch=None, date=None,
1315 self, message, author, parents=None, branch=None, date=None,
1316 **kwargs):
1316 **kwargs):
1317 """
1317 """
1318 Performs in-memory commit (doesn't check workdir in any way) and
1318 Performs in-memory commit (doesn't check workdir in any way) and
1319 returns newly created :class:`BaseCommit`. Updates repository's
1319 returns newly created :class:`BaseCommit`. Updates repository's
1320 attribute `commits`.
1320 attribute `commits`.
1321
1321
1322 .. note::
1322 .. note::
1323
1323
1324 While overriding this method each backend's should call
1324 While overriding this method each backend's should call
1325 ``self.check_integrity(parents)`` in the first place.
1325 ``self.check_integrity(parents)`` in the first place.
1326
1326
1327 :param message: message of the commit
1327 :param message: message of the commit
1328 :param author: full username, i.e. "Joe Doe <joe.doe@example.com>"
1328 :param author: full username, i.e. "Joe Doe <joe.doe@example.com>"
1329 :param parents: single parent or sequence of parents from which commit
1329 :param parents: single parent or sequence of parents from which commit
1330 would be derived
1330 would be derived
1331 :param date: ``datetime.datetime`` instance. Defaults to
1331 :param date: ``datetime.datetime`` instance. Defaults to
1332 ``datetime.datetime.now()``.
1332 ``datetime.datetime.now()``.
1333 :param branch: branch name, as string. If none given, default backend's
1333 :param branch: branch name, as string. If none given, default backend's
1334 branch would be used.
1334 branch would be used.
1335
1335
1336 :raises ``CommitError``: if any error occurs while committing
1336 :raises ``CommitError``: if any error occurs while committing
1337 """
1337 """
1338 raise NotImplementedError
1338 raise NotImplementedError
1339
1339
1340
1340
1341 class BaseInMemoryChangesetClass(type):
1341 class BaseInMemoryChangesetClass(type):
1342
1342
1343 def __instancecheck__(self, instance):
1343 def __instancecheck__(self, instance):
1344 return isinstance(instance, BaseInMemoryCommit)
1344 return isinstance(instance, BaseInMemoryCommit)
1345
1345
1346
1346
1347 class BaseInMemoryChangeset(BaseInMemoryCommit):
1347 class BaseInMemoryChangeset(BaseInMemoryCommit):
1348
1348
1349 __metaclass__ = BaseInMemoryChangesetClass
1349 __metaclass__ = BaseInMemoryChangesetClass
1350
1350
1351 def __new__(cls, *args, **kwargs):
1351 def __new__(cls, *args, **kwargs):
1352 warnings.warn(
1352 warnings.warn(
1353 "Use BaseCommit instead of BaseInMemoryCommit", DeprecationWarning)
1353 "Use BaseCommit instead of BaseInMemoryCommit", DeprecationWarning)
1354 return super(BaseInMemoryChangeset, cls).__new__(cls, *args, **kwargs)
1354 return super(BaseInMemoryChangeset, cls).__new__(cls, *args, **kwargs)
1355
1355
1356
1356
1357 class EmptyCommit(BaseCommit):
1357 class EmptyCommit(BaseCommit):
1358 """
1358 """
1359 An dummy empty commit. It's possible to pass hash when creating
1359 An dummy empty commit. It's possible to pass hash when creating
1360 an EmptyCommit
1360 an EmptyCommit
1361 """
1361 """
1362
1362
1363 def __init__(
1363 def __init__(
1364 self, commit_id='0' * 40, repo=None, alias=None, idx=-1,
1364 self, commit_id='0' * 40, repo=None, alias=None, idx=-1,
1365 message='', author='', date=None):
1365 message='', author='', date=None):
1366 self._empty_commit_id = commit_id
1366 self._empty_commit_id = commit_id
1367 # TODO: johbo: Solve idx parameter, default value does not make
1367 # TODO: johbo: Solve idx parameter, default value does not make
1368 # too much sense
1368 # too much sense
1369 self.idx = idx
1369 self.idx = idx
1370 self.message = message
1370 self.message = message
1371 self.author = author
1371 self.author = author
1372 self.date = date or datetime.datetime.fromtimestamp(0)
1372 self.date = date or datetime.datetime.fromtimestamp(0)
1373 self.repository = repo
1373 self.repository = repo
1374 self.alias = alias
1374 self.alias = alias
1375
1375
1376 @LazyProperty
1376 @LazyProperty
1377 def raw_id(self):
1377 def raw_id(self):
1378 """
1378 """
1379 Returns raw string identifying this commit, useful for web
1379 Returns raw string identifying this commit, useful for web
1380 representation.
1380 representation.
1381 """
1381 """
1382
1382
1383 return self._empty_commit_id
1383 return self._empty_commit_id
1384
1384
1385 @LazyProperty
1385 @LazyProperty
1386 def branch(self):
1386 def branch(self):
1387 if self.alias:
1387 if self.alias:
1388 from rhodecode.lib.vcs.backends import get_backend
1388 from rhodecode.lib.vcs.backends import get_backend
1389 return get_backend(self.alias).DEFAULT_BRANCH_NAME
1389 return get_backend(self.alias).DEFAULT_BRANCH_NAME
1390
1390
1391 @LazyProperty
1391 @LazyProperty
1392 def short_id(self):
1392 def short_id(self):
1393 return self.raw_id[:12]
1393 return self.raw_id[:12]
1394
1394
1395 @LazyProperty
1395 @LazyProperty
1396 def id(self):
1396 def id(self):
1397 return self.raw_id
1397 return self.raw_id
1398
1398
1399 def get_file_commit(self, path):
1399 def get_file_commit(self, path):
1400 return self
1400 return self
1401
1401
1402 def get_file_content(self, path):
1402 def get_file_content(self, path):
1403 return u''
1403 return u''
1404
1404
1405 def get_file_size(self, path):
1405 def get_file_size(self, path):
1406 return 0
1406 return 0
1407
1407
1408
1408
1409 class EmptyChangesetClass(type):
1409 class EmptyChangesetClass(type):
1410
1410
1411 def __instancecheck__(self, instance):
1411 def __instancecheck__(self, instance):
1412 return isinstance(instance, EmptyCommit)
1412 return isinstance(instance, EmptyCommit)
1413
1413
1414
1414
1415 class EmptyChangeset(EmptyCommit):
1415 class EmptyChangeset(EmptyCommit):
1416
1416
1417 __metaclass__ = EmptyChangesetClass
1417 __metaclass__ = EmptyChangesetClass
1418
1418
1419 def __new__(cls, *args, **kwargs):
1419 def __new__(cls, *args, **kwargs):
1420 warnings.warn(
1420 warnings.warn(
1421 "Use EmptyCommit instead of EmptyChangeset", DeprecationWarning)
1421 "Use EmptyCommit instead of EmptyChangeset", DeprecationWarning)
1422 return super(EmptyCommit, cls).__new__(cls, *args, **kwargs)
1422 return super(EmptyCommit, cls).__new__(cls, *args, **kwargs)
1423
1423
1424 def __init__(self, cs='0' * 40, repo=None, requested_revision=None,
1424 def __init__(self, cs='0' * 40, repo=None, requested_revision=None,
1425 alias=None, revision=-1, message='', author='', date=None):
1425 alias=None, revision=-1, message='', author='', date=None):
1426 if requested_revision is not None:
1426 if requested_revision is not None:
1427 warnings.warn(
1427 warnings.warn(
1428 "Parameter requested_revision not supported anymore",
1428 "Parameter requested_revision not supported anymore",
1429 DeprecationWarning)
1429 DeprecationWarning)
1430 super(EmptyChangeset, self).__init__(
1430 super(EmptyChangeset, self).__init__(
1431 commit_id=cs, repo=repo, alias=alias, idx=revision,
1431 commit_id=cs, repo=repo, alias=alias, idx=revision,
1432 message=message, author=author, date=date)
1432 message=message, author=author, date=date)
1433
1433
1434 @property
1434 @property
1435 def revision(self):
1435 def revision(self):
1436 warnings.warn("Use idx instead", DeprecationWarning)
1436 warnings.warn("Use idx instead", DeprecationWarning)
1437 return self.idx
1437 return self.idx
1438
1438
1439 @revision.setter
1439 @revision.setter
1440 def revision(self, value):
1440 def revision(self, value):
1441 warnings.warn("Use idx instead", DeprecationWarning)
1441 warnings.warn("Use idx instead", DeprecationWarning)
1442 self.idx = value
1442 self.idx = value
1443
1443
1444
1444
1445 class EmptyRepository(BaseRepository):
1446 def __init__(self, repo_path=None, config=None, create=False, **kwargs):
1447 pass
1448
1449 def get_diff(self, *args, **kwargs):
1450 from rhodecode.lib.vcs.backends.git.diff import GitDiff
1451 return GitDiff('')
1452
1453
1445 class CollectionGenerator(object):
1454 class CollectionGenerator(object):
1446
1455
1447 def __init__(self, repo, commit_ids, collection_size=None, pre_load=None):
1456 def __init__(self, repo, commit_ids, collection_size=None, pre_load=None):
1448 self.repo = repo
1457 self.repo = repo
1449 self.commit_ids = commit_ids
1458 self.commit_ids = commit_ids
1450 # TODO: (oliver) this isn't currently hooked up
1459 # TODO: (oliver) this isn't currently hooked up
1451 self.collection_size = None
1460 self.collection_size = None
1452 self.pre_load = pre_load
1461 self.pre_load = pre_load
1453
1462
1454 def __len__(self):
1463 def __len__(self):
1455 if self.collection_size is not None:
1464 if self.collection_size is not None:
1456 return self.collection_size
1465 return self.collection_size
1457 return self.commit_ids.__len__()
1466 return self.commit_ids.__len__()
1458
1467
1459 def __iter__(self):
1468 def __iter__(self):
1460 for commit_id in self.commit_ids:
1469 for commit_id in self.commit_ids:
1461 # TODO: johbo: Mercurial passes in commit indices or commit ids
1470 # TODO: johbo: Mercurial passes in commit indices or commit ids
1462 yield self._commit_factory(commit_id)
1471 yield self._commit_factory(commit_id)
1463
1472
1464 def _commit_factory(self, commit_id):
1473 def _commit_factory(self, commit_id):
1465 """
1474 """
1466 Allows backends to override the way commits are generated.
1475 Allows backends to override the way commits are generated.
1467 """
1476 """
1468 return self.repo.get_commit(commit_id=commit_id,
1477 return self.repo.get_commit(commit_id=commit_id,
1469 pre_load=self.pre_load)
1478 pre_load=self.pre_load)
1470
1479
1471 def __getslice__(self, i, j):
1480 def __getslice__(self, i, j):
1472 """
1481 """
1473 Returns an iterator of sliced repository
1482 Returns an iterator of sliced repository
1474 """
1483 """
1475 commit_ids = self.commit_ids[i:j]
1484 commit_ids = self.commit_ids[i:j]
1476 return self.__class__(
1485 return self.__class__(
1477 self.repo, commit_ids, pre_load=self.pre_load)
1486 self.repo, commit_ids, pre_load=self.pre_load)
1478
1487
1479 def __repr__(self):
1488 def __repr__(self):
1480 return '<CollectionGenerator[len:%s]>' % (self.__len__())
1489 return '<CollectionGenerator[len:%s]>' % (self.__len__())
1481
1490
1482
1491
1483 class Config(object):
1492 class Config(object):
1484 """
1493 """
1485 Represents the configuration for a repository.
1494 Represents the configuration for a repository.
1486
1495
1487 The API is inspired by :class:`ConfigParser.ConfigParser` from the
1496 The API is inspired by :class:`ConfigParser.ConfigParser` from the
1488 standard library. It implements only the needed subset.
1497 standard library. It implements only the needed subset.
1489 """
1498 """
1490
1499
1491 def __init__(self):
1500 def __init__(self):
1492 self._values = {}
1501 self._values = {}
1493
1502
1494 def copy(self):
1503 def copy(self):
1495 clone = Config()
1504 clone = Config()
1496 for section, values in self._values.items():
1505 for section, values in self._values.items():
1497 clone._values[section] = values.copy()
1506 clone._values[section] = values.copy()
1498 return clone
1507 return clone
1499
1508
1500 def __repr__(self):
1509 def __repr__(self):
1501 return '<Config(%s sections) at %s>' % (
1510 return '<Config(%s sections) at %s>' % (
1502 len(self._values), hex(id(self)))
1511 len(self._values), hex(id(self)))
1503
1512
1504 def items(self, section):
1513 def items(self, section):
1505 return self._values.get(section, {}).iteritems()
1514 return self._values.get(section, {}).iteritems()
1506
1515
1507 def get(self, section, option):
1516 def get(self, section, option):
1508 return self._values.get(section, {}).get(option)
1517 return self._values.get(section, {}).get(option)
1509
1518
1510 def set(self, section, option, value):
1519 def set(self, section, option, value):
1511 section_values = self._values.setdefault(section, {})
1520 section_values = self._values.setdefault(section, {})
1512 section_values[option] = value
1521 section_values[option] = value
1513
1522
1514 def clear_section(self, section):
1523 def clear_section(self, section):
1515 self._values[section] = {}
1524 self._values[section] = {}
1516
1525
1517 def serialize(self):
1526 def serialize(self):
1518 """
1527 """
1519 Creates a list of three tuples (section, key, value) representing
1528 Creates a list of three tuples (section, key, value) representing
1520 this config object.
1529 this config object.
1521 """
1530 """
1522 items = []
1531 items = []
1523 for section in self._values:
1532 for section in self._values:
1524 for option, value in self._values[section].items():
1533 for option, value in self._values[section].items():
1525 items.append(
1534 items.append(
1526 (safe_str(section), safe_str(option), safe_str(value)))
1535 (safe_str(section), safe_str(option), safe_str(value)))
1527 return items
1536 return items
1528
1537
1529
1538
1530 class Diff(object):
1539 class Diff(object):
1531 """
1540 """
1532 Represents a diff result from a repository backend.
1541 Represents a diff result from a repository backend.
1533
1542
1534 Subclasses have to provide a backend specific value for :attr:`_header_re`.
1543 Subclasses have to provide a backend specific value for :attr:`_header_re`.
1535 """
1544 """
1536
1545
1537 _header_re = None
1546 _header_re = None
1538
1547
1539 def __init__(self, raw_diff):
1548 def __init__(self, raw_diff):
1540 self.raw = raw_diff
1549 self.raw = raw_diff
1541
1550
1542 def chunks(self):
1551 def chunks(self):
1543 """
1552 """
1544 split the diff in chunks of separate --git a/file b/file chunks
1553 split the diff in chunks of separate --git a/file b/file chunks
1545 to make diffs consistent we must prepend with \n, and make sure
1554 to make diffs consistent we must prepend with \n, and make sure
1546 we can detect last chunk as this was also has special rule
1555 we can detect last chunk as this was also has special rule
1547 """
1556 """
1548 chunks = ('\n' + self.raw).split('\ndiff --git')[1:]
1557 chunks = ('\n' + self.raw).split('\ndiff --git')[1:]
1549 total_chunks = len(chunks)
1558 total_chunks = len(chunks)
1550 return (DiffChunk(chunk, self, cur_chunk == total_chunks)
1559 return (DiffChunk(chunk, self, cur_chunk == total_chunks)
1551 for cur_chunk, chunk in enumerate(chunks, start=1))
1560 for cur_chunk, chunk in enumerate(chunks, start=1))
1552
1561
1553
1562
1554 class DiffChunk(object):
1563 class DiffChunk(object):
1555
1564
1556 def __init__(self, chunk, diff, last_chunk):
1565 def __init__(self, chunk, diff, last_chunk):
1557 self._diff = diff
1566 self._diff = diff
1558
1567
1559 # since we split by \ndiff --git that part is lost from original diff
1568 # since we split by \ndiff --git that part is lost from original diff
1560 # we need to re-apply it at the end, EXCEPT ! if it's last chunk
1569 # we need to re-apply it at the end, EXCEPT ! if it's last chunk
1561 if not last_chunk:
1570 if not last_chunk:
1562 chunk += '\n'
1571 chunk += '\n'
1563
1572
1564 match = self._diff._header_re.match(chunk)
1573 match = self._diff._header_re.match(chunk)
1565 self.header = match.groupdict()
1574 self.header = match.groupdict()
1566 self.diff = chunk[match.end():]
1575 self.diff = chunk[match.end():]
1567 self.raw = chunk
1576 self.raw = chunk
@@ -1,3730 +1,3788 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2016 RhodeCode GmbH
3 # Copyright (C) 2010-2016 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 hashlib
28 import hashlib
29 import logging
29 import logging
30 import datetime
30 import datetime
31 import warnings
31 import warnings
32 import ipaddress
32 import ipaddress
33 import functools
33 import functools
34 import traceback
34 import traceback
35 import collections
35 import collections
36
36
37
37
38 from sqlalchemy import *
38 from sqlalchemy import *
39 from sqlalchemy.ext.declarative import declared_attr
39 from sqlalchemy.ext.declarative import declared_attr
40 from sqlalchemy.ext.hybrid import hybrid_property
40 from sqlalchemy.ext.hybrid import hybrid_property
41 from sqlalchemy.orm import (
41 from sqlalchemy.orm import (
42 relationship, joinedload, class_mapper, validates, aliased)
42 relationship, joinedload, class_mapper, validates, aliased)
43 from sqlalchemy.sql.expression import true
43 from sqlalchemy.sql.expression import true
44 from beaker.cache import cache_region
44 from beaker.cache import cache_region
45 from webob.exc import HTTPNotFound
45 from webob.exc import HTTPNotFound
46 from zope.cachedescriptors.property import Lazy as LazyProperty
46 from zope.cachedescriptors.property import Lazy as LazyProperty
47
47
48 from pylons import url
48 from pylons import url
49 from pylons.i18n.translation import lazy_ugettext as _
49 from pylons.i18n.translation import lazy_ugettext as _
50
50
51 from rhodecode.lib.vcs import get_vcs_instance
51 from rhodecode.lib.vcs import get_vcs_instance
52 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
52 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
53 from rhodecode.lib.utils2 import (
53 from rhodecode.lib.utils2 import (
54 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
54 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
55 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
55 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
56 glob2re)
56 glob2re, StrictAttributeDict)
57 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType
57 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType
58 from rhodecode.lib.ext_json import json
58 from rhodecode.lib.ext_json import json
59 from rhodecode.lib.caching_query import FromCache
59 from rhodecode.lib.caching_query import FromCache
60 from rhodecode.lib.encrypt import AESCipher
60 from rhodecode.lib.encrypt import AESCipher
61
61
62 from rhodecode.model.meta import Base, Session
62 from rhodecode.model.meta import Base, Session
63
63
64 URL_SEP = '/'
64 URL_SEP = '/'
65 log = logging.getLogger(__name__)
65 log = logging.getLogger(__name__)
66
66
67 # =============================================================================
67 # =============================================================================
68 # BASE CLASSES
68 # BASE CLASSES
69 # =============================================================================
69 # =============================================================================
70
70
71 # this is propagated from .ini file rhodecode.encrypted_values.secret or
71 # this is propagated from .ini file rhodecode.encrypted_values.secret or
72 # beaker.session.secret if first is not set.
72 # beaker.session.secret if first is not set.
73 # and initialized at environment.py
73 # and initialized at environment.py
74 ENCRYPTION_KEY = None
74 ENCRYPTION_KEY = None
75
75
76 # used to sort permissions by types, '#' used here is not allowed to be in
76 # used to sort permissions by types, '#' used here is not allowed to be in
77 # usernames, and it's very early in sorted string.printable table.
77 # usernames, and it's very early in sorted string.printable table.
78 PERMISSION_TYPE_SORT = {
78 PERMISSION_TYPE_SORT = {
79 'admin': '####',
79 'admin': '####',
80 'write': '###',
80 'write': '###',
81 'read': '##',
81 'read': '##',
82 'none': '#',
82 'none': '#',
83 }
83 }
84
84
85
85
86 def display_sort(obj):
86 def display_sort(obj):
87 """
87 """
88 Sort function used to sort permissions in .permissions() function of
88 Sort function used to sort permissions in .permissions() function of
89 Repository, RepoGroup, UserGroup. Also it put the default user in front
89 Repository, RepoGroup, UserGroup. Also it put the default user in front
90 of all other resources
90 of all other resources
91 """
91 """
92
92
93 if obj.username == User.DEFAULT_USER:
93 if obj.username == User.DEFAULT_USER:
94 return '#####'
94 return '#####'
95 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
95 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
96 return prefix + obj.username
96 return prefix + obj.username
97
97
98
98
99 def _hash_key(k):
99 def _hash_key(k):
100 return md5_safe(k)
100 return md5_safe(k)
101
101
102
102
103 class EncryptedTextValue(TypeDecorator):
103 class EncryptedTextValue(TypeDecorator):
104 """
104 """
105 Special column for encrypted long text data, use like::
105 Special column for encrypted long text data, use like::
106
106
107 value = Column("encrypted_value", EncryptedValue(), nullable=False)
107 value = Column("encrypted_value", EncryptedValue(), nullable=False)
108
108
109 This column is intelligent so if value is in unencrypted form it return
109 This column is intelligent so if value is in unencrypted form it return
110 unencrypted form, but on save it always encrypts
110 unencrypted form, but on save it always encrypts
111 """
111 """
112 impl = Text
112 impl = Text
113
113
114 def process_bind_param(self, value, dialect):
114 def process_bind_param(self, value, dialect):
115 if not value:
115 if not value:
116 return value
116 return value
117 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
117 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
118 # protect against double encrypting if someone manually starts
118 # protect against double encrypting if someone manually starts
119 # doing
119 # doing
120 raise ValueError('value needs to be in unencrypted format, ie. '
120 raise ValueError('value needs to be in unencrypted format, ie. '
121 'not starting with enc$aes')
121 'not starting with enc$aes')
122 return 'enc$aes_hmac$%s' % AESCipher(
122 return 'enc$aes_hmac$%s' % AESCipher(
123 ENCRYPTION_KEY, hmac=True).encrypt(value)
123 ENCRYPTION_KEY, hmac=True).encrypt(value)
124
124
125 def process_result_value(self, value, dialect):
125 def process_result_value(self, value, dialect):
126 import rhodecode
126 import rhodecode
127
127
128 if not value:
128 if not value:
129 return value
129 return value
130
130
131 parts = value.split('$', 3)
131 parts = value.split('$', 3)
132 if not len(parts) == 3:
132 if not len(parts) == 3:
133 # probably not encrypted values
133 # probably not encrypted values
134 return value
134 return value
135 else:
135 else:
136 if parts[0] != 'enc':
136 if parts[0] != 'enc':
137 # parts ok but without our header ?
137 # parts ok but without our header ?
138 return value
138 return value
139 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
139 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
140 'rhodecode.encrypted_values.strict') or True)
140 'rhodecode.encrypted_values.strict') or True)
141 # at that stage we know it's our encryption
141 # at that stage we know it's our encryption
142 if parts[1] == 'aes':
142 if parts[1] == 'aes':
143 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
143 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
144 elif parts[1] == 'aes_hmac':
144 elif parts[1] == 'aes_hmac':
145 decrypted_data = AESCipher(
145 decrypted_data = AESCipher(
146 ENCRYPTION_KEY, hmac=True,
146 ENCRYPTION_KEY, hmac=True,
147 strict_verification=enc_strict_mode).decrypt(parts[2])
147 strict_verification=enc_strict_mode).decrypt(parts[2])
148 else:
148 else:
149 raise ValueError(
149 raise ValueError(
150 'Encryption type part is wrong, must be `aes` '
150 'Encryption type part is wrong, must be `aes` '
151 'or `aes_hmac`, got `%s` instead' % (parts[1]))
151 'or `aes_hmac`, got `%s` instead' % (parts[1]))
152 return decrypted_data
152 return decrypted_data
153
153
154
154
155 class BaseModel(object):
155 class BaseModel(object):
156 """
156 """
157 Base Model for all classes
157 Base Model for all classes
158 """
158 """
159
159
160 @classmethod
160 @classmethod
161 def _get_keys(cls):
161 def _get_keys(cls):
162 """return column names for this model """
162 """return column names for this model """
163 return class_mapper(cls).c.keys()
163 return class_mapper(cls).c.keys()
164
164
165 def get_dict(self):
165 def get_dict(self):
166 """
166 """
167 return dict with keys and values corresponding
167 return dict with keys and values corresponding
168 to this model data """
168 to this model data """
169
169
170 d = {}
170 d = {}
171 for k in self._get_keys():
171 for k in self._get_keys():
172 d[k] = getattr(self, k)
172 d[k] = getattr(self, k)
173
173
174 # also use __json__() if present to get additional fields
174 # also use __json__() if present to get additional fields
175 _json_attr = getattr(self, '__json__', None)
175 _json_attr = getattr(self, '__json__', None)
176 if _json_attr:
176 if _json_attr:
177 # update with attributes from __json__
177 # update with attributes from __json__
178 if callable(_json_attr):
178 if callable(_json_attr):
179 _json_attr = _json_attr()
179 _json_attr = _json_attr()
180 for k, val in _json_attr.iteritems():
180 for k, val in _json_attr.iteritems():
181 d[k] = val
181 d[k] = val
182 return d
182 return d
183
183
184 def get_appstruct(self):
184 def get_appstruct(self):
185 """return list with keys and values tuples corresponding
185 """return list with keys and values tuples corresponding
186 to this model data """
186 to this model data """
187
187
188 l = []
188 l = []
189 for k in self._get_keys():
189 for k in self._get_keys():
190 l.append((k, getattr(self, k),))
190 l.append((k, getattr(self, k),))
191 return l
191 return l
192
192
193 def populate_obj(self, populate_dict):
193 def populate_obj(self, populate_dict):
194 """populate model with data from given populate_dict"""
194 """populate model with data from given populate_dict"""
195
195
196 for k in self._get_keys():
196 for k in self._get_keys():
197 if k in populate_dict:
197 if k in populate_dict:
198 setattr(self, k, populate_dict[k])
198 setattr(self, k, populate_dict[k])
199
199
200 @classmethod
200 @classmethod
201 def query(cls):
201 def query(cls):
202 return Session().query(cls)
202 return Session().query(cls)
203
203
204 @classmethod
204 @classmethod
205 def get(cls, id_):
205 def get(cls, id_):
206 if id_:
206 if id_:
207 return cls.query().get(id_)
207 return cls.query().get(id_)
208
208
209 @classmethod
209 @classmethod
210 def get_or_404(cls, id_):
210 def get_or_404(cls, id_):
211 try:
211 try:
212 id_ = int(id_)
212 id_ = int(id_)
213 except (TypeError, ValueError):
213 except (TypeError, ValueError):
214 raise HTTPNotFound
214 raise HTTPNotFound
215
215
216 res = cls.query().get(id_)
216 res = cls.query().get(id_)
217 if not res:
217 if not res:
218 raise HTTPNotFound
218 raise HTTPNotFound
219 return res
219 return res
220
220
221 @classmethod
221 @classmethod
222 def getAll(cls):
222 def getAll(cls):
223 # deprecated and left for backward compatibility
223 # deprecated and left for backward compatibility
224 return cls.get_all()
224 return cls.get_all()
225
225
226 @classmethod
226 @classmethod
227 def get_all(cls):
227 def get_all(cls):
228 return cls.query().all()
228 return cls.query().all()
229
229
230 @classmethod
230 @classmethod
231 def delete(cls, id_):
231 def delete(cls, id_):
232 obj = cls.query().get(id_)
232 obj = cls.query().get(id_)
233 Session().delete(obj)
233 Session().delete(obj)
234
234
235 @classmethod
235 @classmethod
236 def identity_cache(cls, session, attr_name, value):
236 def identity_cache(cls, session, attr_name, value):
237 exist_in_session = []
237 exist_in_session = []
238 for (item_cls, pkey), instance in session.identity_map.items():
238 for (item_cls, pkey), instance in session.identity_map.items():
239 if cls == item_cls and getattr(instance, attr_name) == value:
239 if cls == item_cls and getattr(instance, attr_name) == value:
240 exist_in_session.append(instance)
240 exist_in_session.append(instance)
241 if exist_in_session:
241 if exist_in_session:
242 if len(exist_in_session) == 1:
242 if len(exist_in_session) == 1:
243 return exist_in_session[0]
243 return exist_in_session[0]
244 log.exception(
244 log.exception(
245 'multiple objects with attr %s and '
245 'multiple objects with attr %s and '
246 'value %s found with same name: %r',
246 'value %s found with same name: %r',
247 attr_name, value, exist_in_session)
247 attr_name, value, exist_in_session)
248
248
249 def __repr__(self):
249 def __repr__(self):
250 if hasattr(self, '__unicode__'):
250 if hasattr(self, '__unicode__'):
251 # python repr needs to return str
251 # python repr needs to return str
252 try:
252 try:
253 return safe_str(self.__unicode__())
253 return safe_str(self.__unicode__())
254 except UnicodeDecodeError:
254 except UnicodeDecodeError:
255 pass
255 pass
256 return '<DB:%s>' % (self.__class__.__name__)
256 return '<DB:%s>' % (self.__class__.__name__)
257
257
258
258
259 class RhodeCodeSetting(Base, BaseModel):
259 class RhodeCodeSetting(Base, BaseModel):
260 __tablename__ = 'rhodecode_settings'
260 __tablename__ = 'rhodecode_settings'
261 __table_args__ = (
261 __table_args__ = (
262 UniqueConstraint('app_settings_name'),
262 UniqueConstraint('app_settings_name'),
263 {'extend_existing': True, 'mysql_engine': 'InnoDB',
263 {'extend_existing': True, 'mysql_engine': 'InnoDB',
264 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
264 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
265 )
265 )
266
266
267 SETTINGS_TYPES = {
267 SETTINGS_TYPES = {
268 'str': safe_str,
268 'str': safe_str,
269 'int': safe_int,
269 'int': safe_int,
270 'unicode': safe_unicode,
270 'unicode': safe_unicode,
271 'bool': str2bool,
271 'bool': str2bool,
272 'list': functools.partial(aslist, sep=',')
272 'list': functools.partial(aslist, sep=',')
273 }
273 }
274 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
274 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
275 GLOBAL_CONF_KEY = 'app_settings'
275 GLOBAL_CONF_KEY = 'app_settings'
276
276
277 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
277 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
278 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
278 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
279 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
279 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
280 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
280 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
281
281
282 def __init__(self, key='', val='', type='unicode'):
282 def __init__(self, key='', val='', type='unicode'):
283 self.app_settings_name = key
283 self.app_settings_name = key
284 self.app_settings_type = type
284 self.app_settings_type = type
285 self.app_settings_value = val
285 self.app_settings_value = val
286
286
287 @validates('_app_settings_value')
287 @validates('_app_settings_value')
288 def validate_settings_value(self, key, val):
288 def validate_settings_value(self, key, val):
289 assert type(val) == unicode
289 assert type(val) == unicode
290 return val
290 return val
291
291
292 @hybrid_property
292 @hybrid_property
293 def app_settings_value(self):
293 def app_settings_value(self):
294 v = self._app_settings_value
294 v = self._app_settings_value
295 _type = self.app_settings_type
295 _type = self.app_settings_type
296 if _type:
296 if _type:
297 _type = self.app_settings_type.split('.')[0]
297 _type = self.app_settings_type.split('.')[0]
298 # decode the encrypted value
298 # decode the encrypted value
299 if 'encrypted' in self.app_settings_type:
299 if 'encrypted' in self.app_settings_type:
300 cipher = EncryptedTextValue()
300 cipher = EncryptedTextValue()
301 v = safe_unicode(cipher.process_result_value(v, None))
301 v = safe_unicode(cipher.process_result_value(v, None))
302
302
303 converter = self.SETTINGS_TYPES.get(_type) or \
303 converter = self.SETTINGS_TYPES.get(_type) or \
304 self.SETTINGS_TYPES['unicode']
304 self.SETTINGS_TYPES['unicode']
305 return converter(v)
305 return converter(v)
306
306
307 @app_settings_value.setter
307 @app_settings_value.setter
308 def app_settings_value(self, val):
308 def app_settings_value(self, val):
309 """
309 """
310 Setter that will always make sure we use unicode in app_settings_value
310 Setter that will always make sure we use unicode in app_settings_value
311
311
312 :param val:
312 :param val:
313 """
313 """
314 val = safe_unicode(val)
314 val = safe_unicode(val)
315 # encode the encrypted value
315 # encode the encrypted value
316 if 'encrypted' in self.app_settings_type:
316 if 'encrypted' in self.app_settings_type:
317 cipher = EncryptedTextValue()
317 cipher = EncryptedTextValue()
318 val = safe_unicode(cipher.process_bind_param(val, None))
318 val = safe_unicode(cipher.process_bind_param(val, None))
319 self._app_settings_value = val
319 self._app_settings_value = val
320
320
321 @hybrid_property
321 @hybrid_property
322 def app_settings_type(self):
322 def app_settings_type(self):
323 return self._app_settings_type
323 return self._app_settings_type
324
324
325 @app_settings_type.setter
325 @app_settings_type.setter
326 def app_settings_type(self, val):
326 def app_settings_type(self, val):
327 if val.split('.')[0] not in self.SETTINGS_TYPES:
327 if val.split('.')[0] not in self.SETTINGS_TYPES:
328 raise Exception('type must be one of %s got %s'
328 raise Exception('type must be one of %s got %s'
329 % (self.SETTINGS_TYPES.keys(), val))
329 % (self.SETTINGS_TYPES.keys(), val))
330 self._app_settings_type = val
330 self._app_settings_type = val
331
331
332 def __unicode__(self):
332 def __unicode__(self):
333 return u"<%s('%s:%s[%s]')>" % (
333 return u"<%s('%s:%s[%s]')>" % (
334 self.__class__.__name__,
334 self.__class__.__name__,
335 self.app_settings_name, self.app_settings_value,
335 self.app_settings_name, self.app_settings_value,
336 self.app_settings_type
336 self.app_settings_type
337 )
337 )
338
338
339
339
340 class RhodeCodeUi(Base, BaseModel):
340 class RhodeCodeUi(Base, BaseModel):
341 __tablename__ = 'rhodecode_ui'
341 __tablename__ = 'rhodecode_ui'
342 __table_args__ = (
342 __table_args__ = (
343 UniqueConstraint('ui_key'),
343 UniqueConstraint('ui_key'),
344 {'extend_existing': True, 'mysql_engine': 'InnoDB',
344 {'extend_existing': True, 'mysql_engine': 'InnoDB',
345 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
345 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
346 )
346 )
347
347
348 HOOK_REPO_SIZE = 'changegroup.repo_size'
348 HOOK_REPO_SIZE = 'changegroup.repo_size'
349 # HG
349 # HG
350 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
350 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
351 HOOK_PULL = 'outgoing.pull_logger'
351 HOOK_PULL = 'outgoing.pull_logger'
352 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
352 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
353 HOOK_PUSH = 'changegroup.push_logger'
353 HOOK_PUSH = 'changegroup.push_logger'
354
354
355 # TODO: johbo: Unify way how hooks are configured for git and hg,
355 # TODO: johbo: Unify way how hooks are configured for git and hg,
356 # git part is currently hardcoded.
356 # git part is currently hardcoded.
357
357
358 # SVN PATTERNS
358 # SVN PATTERNS
359 SVN_BRANCH_ID = 'vcs_svn_branch'
359 SVN_BRANCH_ID = 'vcs_svn_branch'
360 SVN_TAG_ID = 'vcs_svn_tag'
360 SVN_TAG_ID = 'vcs_svn_tag'
361
361
362 ui_id = Column(
362 ui_id = Column(
363 "ui_id", Integer(), nullable=False, unique=True, default=None,
363 "ui_id", Integer(), nullable=False, unique=True, default=None,
364 primary_key=True)
364 primary_key=True)
365 ui_section = Column(
365 ui_section = Column(
366 "ui_section", String(255), nullable=True, unique=None, default=None)
366 "ui_section", String(255), nullable=True, unique=None, default=None)
367 ui_key = Column(
367 ui_key = Column(
368 "ui_key", String(255), nullable=True, unique=None, default=None)
368 "ui_key", String(255), nullable=True, unique=None, default=None)
369 ui_value = Column(
369 ui_value = Column(
370 "ui_value", String(255), nullable=True, unique=None, default=None)
370 "ui_value", String(255), nullable=True, unique=None, default=None)
371 ui_active = Column(
371 ui_active = Column(
372 "ui_active", Boolean(), nullable=True, unique=None, default=True)
372 "ui_active", Boolean(), nullable=True, unique=None, default=True)
373
373
374 def __repr__(self):
374 def __repr__(self):
375 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
375 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
376 self.ui_key, self.ui_value)
376 self.ui_key, self.ui_value)
377
377
378
378
379 class RepoRhodeCodeSetting(Base, BaseModel):
379 class RepoRhodeCodeSetting(Base, BaseModel):
380 __tablename__ = 'repo_rhodecode_settings'
380 __tablename__ = 'repo_rhodecode_settings'
381 __table_args__ = (
381 __table_args__ = (
382 UniqueConstraint(
382 UniqueConstraint(
383 'app_settings_name', 'repository_id',
383 'app_settings_name', 'repository_id',
384 name='uq_repo_rhodecode_setting_name_repo_id'),
384 name='uq_repo_rhodecode_setting_name_repo_id'),
385 {'extend_existing': True, 'mysql_engine': 'InnoDB',
385 {'extend_existing': True, 'mysql_engine': 'InnoDB',
386 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
386 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
387 )
387 )
388
388
389 repository_id = Column(
389 repository_id = Column(
390 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
390 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
391 nullable=False)
391 nullable=False)
392 app_settings_id = Column(
392 app_settings_id = Column(
393 "app_settings_id", Integer(), nullable=False, unique=True,
393 "app_settings_id", Integer(), nullable=False, unique=True,
394 default=None, primary_key=True)
394 default=None, primary_key=True)
395 app_settings_name = Column(
395 app_settings_name = Column(
396 "app_settings_name", String(255), nullable=True, unique=None,
396 "app_settings_name", String(255), nullable=True, unique=None,
397 default=None)
397 default=None)
398 _app_settings_value = Column(
398 _app_settings_value = Column(
399 "app_settings_value", String(4096), nullable=True, unique=None,
399 "app_settings_value", String(4096), nullable=True, unique=None,
400 default=None)
400 default=None)
401 _app_settings_type = Column(
401 _app_settings_type = Column(
402 "app_settings_type", String(255), nullable=True, unique=None,
402 "app_settings_type", String(255), nullable=True, unique=None,
403 default=None)
403 default=None)
404
404
405 repository = relationship('Repository')
405 repository = relationship('Repository')
406
406
407 def __init__(self, repository_id, key='', val='', type='unicode'):
407 def __init__(self, repository_id, key='', val='', type='unicode'):
408 self.repository_id = repository_id
408 self.repository_id = repository_id
409 self.app_settings_name = key
409 self.app_settings_name = key
410 self.app_settings_type = type
410 self.app_settings_type = type
411 self.app_settings_value = val
411 self.app_settings_value = val
412
412
413 @validates('_app_settings_value')
413 @validates('_app_settings_value')
414 def validate_settings_value(self, key, val):
414 def validate_settings_value(self, key, val):
415 assert type(val) == unicode
415 assert type(val) == unicode
416 return val
416 return val
417
417
418 @hybrid_property
418 @hybrid_property
419 def app_settings_value(self):
419 def app_settings_value(self):
420 v = self._app_settings_value
420 v = self._app_settings_value
421 type_ = self.app_settings_type
421 type_ = self.app_settings_type
422 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
422 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
423 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
423 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
424 return converter(v)
424 return converter(v)
425
425
426 @app_settings_value.setter
426 @app_settings_value.setter
427 def app_settings_value(self, val):
427 def app_settings_value(self, val):
428 """
428 """
429 Setter that will always make sure we use unicode in app_settings_value
429 Setter that will always make sure we use unicode in app_settings_value
430
430
431 :param val:
431 :param val:
432 """
432 """
433 self._app_settings_value = safe_unicode(val)
433 self._app_settings_value = safe_unicode(val)
434
434
435 @hybrid_property
435 @hybrid_property
436 def app_settings_type(self):
436 def app_settings_type(self):
437 return self._app_settings_type
437 return self._app_settings_type
438
438
439 @app_settings_type.setter
439 @app_settings_type.setter
440 def app_settings_type(self, val):
440 def app_settings_type(self, val):
441 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
441 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
442 if val not in SETTINGS_TYPES:
442 if val not in SETTINGS_TYPES:
443 raise Exception('type must be one of %s got %s'
443 raise Exception('type must be one of %s got %s'
444 % (SETTINGS_TYPES.keys(), val))
444 % (SETTINGS_TYPES.keys(), val))
445 self._app_settings_type = val
445 self._app_settings_type = val
446
446
447 def __unicode__(self):
447 def __unicode__(self):
448 return u"<%s('%s:%s:%s[%s]')>" % (
448 return u"<%s('%s:%s:%s[%s]')>" % (
449 self.__class__.__name__, self.repository.repo_name,
449 self.__class__.__name__, self.repository.repo_name,
450 self.app_settings_name, self.app_settings_value,
450 self.app_settings_name, self.app_settings_value,
451 self.app_settings_type
451 self.app_settings_type
452 )
452 )
453
453
454
454
455 class RepoRhodeCodeUi(Base, BaseModel):
455 class RepoRhodeCodeUi(Base, BaseModel):
456 __tablename__ = 'repo_rhodecode_ui'
456 __tablename__ = 'repo_rhodecode_ui'
457 __table_args__ = (
457 __table_args__ = (
458 UniqueConstraint(
458 UniqueConstraint(
459 'repository_id', 'ui_section', 'ui_key',
459 'repository_id', 'ui_section', 'ui_key',
460 name='uq_repo_rhodecode_ui_repository_id_section_key'),
460 name='uq_repo_rhodecode_ui_repository_id_section_key'),
461 {'extend_existing': True, 'mysql_engine': 'InnoDB',
461 {'extend_existing': True, 'mysql_engine': 'InnoDB',
462 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
462 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
463 )
463 )
464
464
465 repository_id = Column(
465 repository_id = Column(
466 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
466 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
467 nullable=False)
467 nullable=False)
468 ui_id = Column(
468 ui_id = Column(
469 "ui_id", Integer(), nullable=False, unique=True, default=None,
469 "ui_id", Integer(), nullable=False, unique=True, default=None,
470 primary_key=True)
470 primary_key=True)
471 ui_section = Column(
471 ui_section = Column(
472 "ui_section", String(255), nullable=True, unique=None, default=None)
472 "ui_section", String(255), nullable=True, unique=None, default=None)
473 ui_key = Column(
473 ui_key = Column(
474 "ui_key", String(255), nullable=True, unique=None, default=None)
474 "ui_key", String(255), nullable=True, unique=None, default=None)
475 ui_value = Column(
475 ui_value = Column(
476 "ui_value", String(255), nullable=True, unique=None, default=None)
476 "ui_value", String(255), nullable=True, unique=None, default=None)
477 ui_active = Column(
477 ui_active = Column(
478 "ui_active", Boolean(), nullable=True, unique=None, default=True)
478 "ui_active", Boolean(), nullable=True, unique=None, default=True)
479
479
480 repository = relationship('Repository')
480 repository = relationship('Repository')
481
481
482 def __repr__(self):
482 def __repr__(self):
483 return '<%s[%s:%s]%s=>%s]>' % (
483 return '<%s[%s:%s]%s=>%s]>' % (
484 self.__class__.__name__, self.repository.repo_name,
484 self.__class__.__name__, self.repository.repo_name,
485 self.ui_section, self.ui_key, self.ui_value)
485 self.ui_section, self.ui_key, self.ui_value)
486
486
487
487
488 class User(Base, BaseModel):
488 class User(Base, BaseModel):
489 __tablename__ = 'users'
489 __tablename__ = 'users'
490 __table_args__ = (
490 __table_args__ = (
491 UniqueConstraint('username'), UniqueConstraint('email'),
491 UniqueConstraint('username'), UniqueConstraint('email'),
492 Index('u_username_idx', 'username'),
492 Index('u_username_idx', 'username'),
493 Index('u_email_idx', 'email'),
493 Index('u_email_idx', 'email'),
494 {'extend_existing': True, 'mysql_engine': 'InnoDB',
494 {'extend_existing': True, 'mysql_engine': 'InnoDB',
495 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
495 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
496 )
496 )
497 DEFAULT_USER = 'default'
497 DEFAULT_USER = 'default'
498 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
498 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
499 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
499 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
500
500
501 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
501 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
502 username = Column("username", String(255), nullable=True, unique=None, default=None)
502 username = Column("username", String(255), nullable=True, unique=None, default=None)
503 password = Column("password", String(255), nullable=True, unique=None, default=None)
503 password = Column("password", String(255), nullable=True, unique=None, default=None)
504 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
504 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
505 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
505 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
506 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
506 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
507 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
507 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
508 _email = Column("email", String(255), nullable=True, unique=None, default=None)
508 _email = Column("email", String(255), nullable=True, unique=None, default=None)
509 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
509 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
510 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
510 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
511 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
511 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
512 api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
512 api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
513 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
513 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
514 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
514 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
515 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
515 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
516
516
517 user_log = relationship('UserLog')
517 user_log = relationship('UserLog')
518 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
518 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
519
519
520 repositories = relationship('Repository')
520 repositories = relationship('Repository')
521 repository_groups = relationship('RepoGroup')
521 repository_groups = relationship('RepoGroup')
522 user_groups = relationship('UserGroup')
522 user_groups = relationship('UserGroup')
523
523
524 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
524 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
525 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
525 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
526
526
527 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
527 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
528 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
528 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
529 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
529 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
530
530
531 group_member = relationship('UserGroupMember', cascade='all')
531 group_member = relationship('UserGroupMember', cascade='all')
532
532
533 notifications = relationship('UserNotification', cascade='all')
533 notifications = relationship('UserNotification', cascade='all')
534 # notifications assigned to this user
534 # notifications assigned to this user
535 user_created_notifications = relationship('Notification', cascade='all')
535 user_created_notifications = relationship('Notification', cascade='all')
536 # comments created by this user
536 # comments created by this user
537 user_comments = relationship('ChangesetComment', cascade='all')
537 user_comments = relationship('ChangesetComment', cascade='all')
538 # user profile extra info
538 # user profile extra info
539 user_emails = relationship('UserEmailMap', cascade='all')
539 user_emails = relationship('UserEmailMap', cascade='all')
540 user_ip_map = relationship('UserIpMap', cascade='all')
540 user_ip_map = relationship('UserIpMap', cascade='all')
541 user_auth_tokens = relationship('UserApiKeys', cascade='all')
541 user_auth_tokens = relationship('UserApiKeys', cascade='all')
542 # gists
542 # gists
543 user_gists = relationship('Gist', cascade='all')
543 user_gists = relationship('Gist', cascade='all')
544 # user pull requests
544 # user pull requests
545 user_pull_requests = relationship('PullRequest', cascade='all')
545 user_pull_requests = relationship('PullRequest', cascade='all')
546 # external identities
546 # external identities
547 extenal_identities = relationship(
547 extenal_identities = relationship(
548 'ExternalIdentity',
548 'ExternalIdentity',
549 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
549 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
550 cascade='all')
550 cascade='all')
551
551
552 def __unicode__(self):
552 def __unicode__(self):
553 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
553 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
554 self.user_id, self.username)
554 self.user_id, self.username)
555
555
556 @hybrid_property
556 @hybrid_property
557 def email(self):
557 def email(self):
558 return self._email
558 return self._email
559
559
560 @email.setter
560 @email.setter
561 def email(self, val):
561 def email(self, val):
562 self._email = val.lower() if val else None
562 self._email = val.lower() if val else None
563
563
564 @property
564 @property
565 def firstname(self):
565 def firstname(self):
566 # alias for future
566 # alias for future
567 return self.name
567 return self.name
568
568
569 @property
569 @property
570 def emails(self):
570 def emails(self):
571 other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
571 other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
572 return [self.email] + [x.email for x in other]
572 return [self.email] + [x.email for x in other]
573
573
574 @property
574 @property
575 def auth_tokens(self):
575 def auth_tokens(self):
576 return [self.api_key] + [x.api_key for x in self.extra_auth_tokens]
576 return [self.api_key] + [x.api_key for x in self.extra_auth_tokens]
577
577
578 @property
578 @property
579 def extra_auth_tokens(self):
579 def extra_auth_tokens(self):
580 return UserApiKeys.query().filter(UserApiKeys.user == self).all()
580 return UserApiKeys.query().filter(UserApiKeys.user == self).all()
581
581
582 @property
582 @property
583 def feed_token(self):
583 def feed_token(self):
584 feed_tokens = UserApiKeys.query()\
584 feed_tokens = UserApiKeys.query()\
585 .filter(UserApiKeys.user == self)\
585 .filter(UserApiKeys.user == self)\
586 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\
586 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\
587 .all()
587 .all()
588 if feed_tokens:
588 if feed_tokens:
589 return feed_tokens[0].api_key
589 return feed_tokens[0].api_key
590 else:
590 else:
591 # use the main token so we don't end up with nothing...
591 # use the main token so we don't end up with nothing...
592 return self.api_key
592 return self.api_key
593
593
594 @classmethod
594 @classmethod
595 def extra_valid_auth_tokens(cls, user, role=None):
595 def extra_valid_auth_tokens(cls, user, role=None):
596 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
596 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
597 .filter(or_(UserApiKeys.expires == -1,
597 .filter(or_(UserApiKeys.expires == -1,
598 UserApiKeys.expires >= time.time()))
598 UserApiKeys.expires >= time.time()))
599 if role:
599 if role:
600 tokens = tokens.filter(or_(UserApiKeys.role == role,
600 tokens = tokens.filter(or_(UserApiKeys.role == role,
601 UserApiKeys.role == UserApiKeys.ROLE_ALL))
601 UserApiKeys.role == UserApiKeys.ROLE_ALL))
602 return tokens.all()
602 return tokens.all()
603
603
604 @property
604 @property
605 def ip_addresses(self):
605 def ip_addresses(self):
606 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
606 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
607 return [x.ip_addr for x in ret]
607 return [x.ip_addr for x in ret]
608
608
609 @property
609 @property
610 def username_and_name(self):
610 def username_and_name(self):
611 return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
611 return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
612
612
613 @property
613 @property
614 def username_or_name_or_email(self):
614 def username_or_name_or_email(self):
615 full_name = self.full_name if self.full_name is not ' ' else None
615 full_name = self.full_name if self.full_name is not ' ' else None
616 return self.username or full_name or self.email
616 return self.username or full_name or self.email
617
617
618 @property
618 @property
619 def full_name(self):
619 def full_name(self):
620 return '%s %s' % (self.firstname, self.lastname)
620 return '%s %s' % (self.firstname, self.lastname)
621
621
622 @property
622 @property
623 def full_name_or_username(self):
623 def full_name_or_username(self):
624 return ('%s %s' % (self.firstname, self.lastname)
624 return ('%s %s' % (self.firstname, self.lastname)
625 if (self.firstname and self.lastname) else self.username)
625 if (self.firstname and self.lastname) else self.username)
626
626
627 @property
627 @property
628 def full_contact(self):
628 def full_contact(self):
629 return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
629 return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
630
630
631 @property
631 @property
632 def short_contact(self):
632 def short_contact(self):
633 return '%s %s' % (self.firstname, self.lastname)
633 return '%s %s' % (self.firstname, self.lastname)
634
634
635 @property
635 @property
636 def is_admin(self):
636 def is_admin(self):
637 return self.admin
637 return self.admin
638
638
639 @property
639 @property
640 def AuthUser(self):
640 def AuthUser(self):
641 """
641 """
642 Returns instance of AuthUser for this user
642 Returns instance of AuthUser for this user
643 """
643 """
644 from rhodecode.lib.auth import AuthUser
644 from rhodecode.lib.auth import AuthUser
645 return AuthUser(user_id=self.user_id, api_key=self.api_key,
645 return AuthUser(user_id=self.user_id, api_key=self.api_key,
646 username=self.username)
646 username=self.username)
647
647
648 @hybrid_property
648 @hybrid_property
649 def user_data(self):
649 def user_data(self):
650 if not self._user_data:
650 if not self._user_data:
651 return {}
651 return {}
652
652
653 try:
653 try:
654 return json.loads(self._user_data)
654 return json.loads(self._user_data)
655 except TypeError:
655 except TypeError:
656 return {}
656 return {}
657
657
658 @user_data.setter
658 @user_data.setter
659 def user_data(self, val):
659 def user_data(self, val):
660 if not isinstance(val, dict):
660 if not isinstance(val, dict):
661 raise Exception('user_data must be dict, got %s' % type(val))
661 raise Exception('user_data must be dict, got %s' % type(val))
662 try:
662 try:
663 self._user_data = json.dumps(val)
663 self._user_data = json.dumps(val)
664 except Exception:
664 except Exception:
665 log.error(traceback.format_exc())
665 log.error(traceback.format_exc())
666
666
667 @classmethod
667 @classmethod
668 def get_by_username(cls, username, case_insensitive=False,
668 def get_by_username(cls, username, case_insensitive=False,
669 cache=False, identity_cache=False):
669 cache=False, identity_cache=False):
670 session = Session()
670 session = Session()
671
671
672 if case_insensitive:
672 if case_insensitive:
673 q = cls.query().filter(
673 q = cls.query().filter(
674 func.lower(cls.username) == func.lower(username))
674 func.lower(cls.username) == func.lower(username))
675 else:
675 else:
676 q = cls.query().filter(cls.username == username)
676 q = cls.query().filter(cls.username == username)
677
677
678 if cache:
678 if cache:
679 if identity_cache:
679 if identity_cache:
680 val = cls.identity_cache(session, 'username', username)
680 val = cls.identity_cache(session, 'username', username)
681 if val:
681 if val:
682 return val
682 return val
683 else:
683 else:
684 q = q.options(
684 q = q.options(
685 FromCache("sql_cache_short",
685 FromCache("sql_cache_short",
686 "get_user_by_name_%s" % _hash_key(username)))
686 "get_user_by_name_%s" % _hash_key(username)))
687
687
688 return q.scalar()
688 return q.scalar()
689
689
690 @classmethod
690 @classmethod
691 def get_by_auth_token(cls, auth_token, cache=False, fallback=True):
691 def get_by_auth_token(cls, auth_token, cache=False, fallback=True):
692 q = cls.query().filter(cls.api_key == auth_token)
692 q = cls.query().filter(cls.api_key == auth_token)
693
693
694 if cache:
694 if cache:
695 q = q.options(FromCache("sql_cache_short",
695 q = q.options(FromCache("sql_cache_short",
696 "get_auth_token_%s" % auth_token))
696 "get_auth_token_%s" % auth_token))
697 res = q.scalar()
697 res = q.scalar()
698
698
699 if fallback and not res:
699 if fallback and not res:
700 #fallback to additional keys
700 #fallback to additional keys
701 _res = UserApiKeys.query()\
701 _res = UserApiKeys.query()\
702 .filter(UserApiKeys.api_key == auth_token)\
702 .filter(UserApiKeys.api_key == auth_token)\
703 .filter(or_(UserApiKeys.expires == -1,
703 .filter(or_(UserApiKeys.expires == -1,
704 UserApiKeys.expires >= time.time()))\
704 UserApiKeys.expires >= time.time()))\
705 .first()
705 .first()
706 if _res:
706 if _res:
707 res = _res.user
707 res = _res.user
708 return res
708 return res
709
709
710 @classmethod
710 @classmethod
711 def get_by_email(cls, email, case_insensitive=False, cache=False):
711 def get_by_email(cls, email, case_insensitive=False, cache=False):
712
712
713 if case_insensitive:
713 if case_insensitive:
714 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
714 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
715
715
716 else:
716 else:
717 q = cls.query().filter(cls.email == email)
717 q = cls.query().filter(cls.email == email)
718
718
719 if cache:
719 if cache:
720 q = q.options(FromCache("sql_cache_short",
720 q = q.options(FromCache("sql_cache_short",
721 "get_email_key_%s" % _hash_key(email)))
721 "get_email_key_%s" % _hash_key(email)))
722
722
723 ret = q.scalar()
723 ret = q.scalar()
724 if ret is None:
724 if ret is None:
725 q = UserEmailMap.query()
725 q = UserEmailMap.query()
726 # try fetching in alternate email map
726 # try fetching in alternate email map
727 if case_insensitive:
727 if case_insensitive:
728 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
728 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
729 else:
729 else:
730 q = q.filter(UserEmailMap.email == email)
730 q = q.filter(UserEmailMap.email == email)
731 q = q.options(joinedload(UserEmailMap.user))
731 q = q.options(joinedload(UserEmailMap.user))
732 if cache:
732 if cache:
733 q = q.options(FromCache("sql_cache_short",
733 q = q.options(FromCache("sql_cache_short",
734 "get_email_map_key_%s" % email))
734 "get_email_map_key_%s" % email))
735 ret = getattr(q.scalar(), 'user', None)
735 ret = getattr(q.scalar(), 'user', None)
736
736
737 return ret
737 return ret
738
738
739 @classmethod
739 @classmethod
740 def get_from_cs_author(cls, author):
740 def get_from_cs_author(cls, author):
741 """
741 """
742 Tries to get User objects out of commit author string
742 Tries to get User objects out of commit author string
743
743
744 :param author:
744 :param author:
745 """
745 """
746 from rhodecode.lib.helpers import email, author_name
746 from rhodecode.lib.helpers import email, author_name
747 # Valid email in the attribute passed, see if they're in the system
747 # Valid email in the attribute passed, see if they're in the system
748 _email = email(author)
748 _email = email(author)
749 if _email:
749 if _email:
750 user = cls.get_by_email(_email, case_insensitive=True)
750 user = cls.get_by_email(_email, case_insensitive=True)
751 if user:
751 if user:
752 return user
752 return user
753 # Maybe we can match by username?
753 # Maybe we can match by username?
754 _author = author_name(author)
754 _author = author_name(author)
755 user = cls.get_by_username(_author, case_insensitive=True)
755 user = cls.get_by_username(_author, case_insensitive=True)
756 if user:
756 if user:
757 return user
757 return user
758
758
759 def update_userdata(self, **kwargs):
759 def update_userdata(self, **kwargs):
760 usr = self
760 usr = self
761 old = usr.user_data
761 old = usr.user_data
762 old.update(**kwargs)
762 old.update(**kwargs)
763 usr.user_data = old
763 usr.user_data = old
764 Session().add(usr)
764 Session().add(usr)
765 log.debug('updated userdata with ', kwargs)
765 log.debug('updated userdata with ', kwargs)
766
766
767 def update_lastlogin(self):
767 def update_lastlogin(self):
768 """Update user lastlogin"""
768 """Update user lastlogin"""
769 self.last_login = datetime.datetime.now()
769 self.last_login = datetime.datetime.now()
770 Session().add(self)
770 Session().add(self)
771 log.debug('updated user %s lastlogin', self.username)
771 log.debug('updated user %s lastlogin', self.username)
772
772
773 def update_lastactivity(self):
773 def update_lastactivity(self):
774 """Update user lastactivity"""
774 """Update user lastactivity"""
775 usr = self
775 usr = self
776 old = usr.user_data
776 old = usr.user_data
777 old.update({'last_activity': time.time()})
777 old.update({'last_activity': time.time()})
778 usr.user_data = old
778 usr.user_data = old
779 Session().add(usr)
779 Session().add(usr)
780 log.debug('updated user %s lastactivity', usr.username)
780 log.debug('updated user %s lastactivity', usr.username)
781
781
782 def update_password(self, new_password, change_api_key=False):
782 def update_password(self, new_password, change_api_key=False):
783 from rhodecode.lib.auth import get_crypt_password,generate_auth_token
783 from rhodecode.lib.auth import get_crypt_password,generate_auth_token
784
784
785 self.password = get_crypt_password(new_password)
785 self.password = get_crypt_password(new_password)
786 if change_api_key:
786 if change_api_key:
787 self.api_key = generate_auth_token(self.username)
787 self.api_key = generate_auth_token(self.username)
788 Session().add(self)
788 Session().add(self)
789
789
790 @classmethod
790 @classmethod
791 def get_first_super_admin(cls):
791 def get_first_super_admin(cls):
792 user = User.query().filter(User.admin == true()).first()
792 user = User.query().filter(User.admin == true()).first()
793 if user is None:
793 if user is None:
794 raise Exception('FATAL: Missing administrative account!')
794 raise Exception('FATAL: Missing administrative account!')
795 return user
795 return user
796
796
797 @classmethod
797 @classmethod
798 def get_all_super_admins(cls):
798 def get_all_super_admins(cls):
799 """
799 """
800 Returns all admin accounts sorted by username
800 Returns all admin accounts sorted by username
801 """
801 """
802 return User.query().filter(User.admin == true())\
802 return User.query().filter(User.admin == true())\
803 .order_by(User.username.asc()).all()
803 .order_by(User.username.asc()).all()
804
804
805 @classmethod
805 @classmethod
806 def get_default_user(cls, cache=False):
806 def get_default_user(cls, cache=False):
807 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
807 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
808 if user is None:
808 if user is None:
809 raise Exception('FATAL: Missing default account!')
809 raise Exception('FATAL: Missing default account!')
810 return user
810 return user
811
811
812 def _get_default_perms(self, user, suffix=''):
812 def _get_default_perms(self, user, suffix=''):
813 from rhodecode.model.permission import PermissionModel
813 from rhodecode.model.permission import PermissionModel
814 return PermissionModel().get_default_perms(user.user_perms, suffix)
814 return PermissionModel().get_default_perms(user.user_perms, suffix)
815
815
816 def get_default_perms(self, suffix=''):
816 def get_default_perms(self, suffix=''):
817 return self._get_default_perms(self, suffix)
817 return self._get_default_perms(self, suffix)
818
818
819 def get_api_data(self, include_secrets=False, details='full'):
819 def get_api_data(self, include_secrets=False, details='full'):
820 """
820 """
821 Common function for generating user related data for API
821 Common function for generating user related data for API
822
822
823 :param include_secrets: By default secrets in the API data will be replaced
823 :param include_secrets: By default secrets in the API data will be replaced
824 by a placeholder value to prevent exposing this data by accident. In case
824 by a placeholder value to prevent exposing this data by accident. In case
825 this data shall be exposed, set this flag to ``True``.
825 this data shall be exposed, set this flag to ``True``.
826
826
827 :param details: details can be 'basic|full' basic gives only a subset of
827 :param details: details can be 'basic|full' basic gives only a subset of
828 the available user information that includes user_id, name and emails.
828 the available user information that includes user_id, name and emails.
829 """
829 """
830 user = self
830 user = self
831 user_data = self.user_data
831 user_data = self.user_data
832 data = {
832 data = {
833 'user_id': user.user_id,
833 'user_id': user.user_id,
834 'username': user.username,
834 'username': user.username,
835 'firstname': user.name,
835 'firstname': user.name,
836 'lastname': user.lastname,
836 'lastname': user.lastname,
837 'email': user.email,
837 'email': user.email,
838 'emails': user.emails,
838 'emails': user.emails,
839 }
839 }
840 if details == 'basic':
840 if details == 'basic':
841 return data
841 return data
842
842
843 api_key_length = 40
843 api_key_length = 40
844 api_key_replacement = '*' * api_key_length
844 api_key_replacement = '*' * api_key_length
845
845
846 extras = {
846 extras = {
847 'api_key': api_key_replacement,
847 'api_key': api_key_replacement,
848 'api_keys': [api_key_replacement],
848 'api_keys': [api_key_replacement],
849 'active': user.active,
849 'active': user.active,
850 'admin': user.admin,
850 'admin': user.admin,
851 'extern_type': user.extern_type,
851 'extern_type': user.extern_type,
852 'extern_name': user.extern_name,
852 'extern_name': user.extern_name,
853 'last_login': user.last_login,
853 'last_login': user.last_login,
854 'ip_addresses': user.ip_addresses,
854 'ip_addresses': user.ip_addresses,
855 'language': user_data.get('language')
855 'language': user_data.get('language')
856 }
856 }
857 data.update(extras)
857 data.update(extras)
858
858
859 if include_secrets:
859 if include_secrets:
860 data['api_key'] = user.api_key
860 data['api_key'] = user.api_key
861 data['api_keys'] = user.auth_tokens
861 data['api_keys'] = user.auth_tokens
862 return data
862 return data
863
863
864 def __json__(self):
864 def __json__(self):
865 data = {
865 data = {
866 'full_name': self.full_name,
866 'full_name': self.full_name,
867 'full_name_or_username': self.full_name_or_username,
867 'full_name_or_username': self.full_name_or_username,
868 'short_contact': self.short_contact,
868 'short_contact': self.short_contact,
869 'full_contact': self.full_contact,
869 'full_contact': self.full_contact,
870 }
870 }
871 data.update(self.get_api_data())
871 data.update(self.get_api_data())
872 return data
872 return data
873
873
874
874
875 class UserApiKeys(Base, BaseModel):
875 class UserApiKeys(Base, BaseModel):
876 __tablename__ = 'user_api_keys'
876 __tablename__ = 'user_api_keys'
877 __table_args__ = (
877 __table_args__ = (
878 Index('uak_api_key_idx', 'api_key'),
878 Index('uak_api_key_idx', 'api_key'),
879 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
879 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
880 UniqueConstraint('api_key'),
880 UniqueConstraint('api_key'),
881 {'extend_existing': True, 'mysql_engine': 'InnoDB',
881 {'extend_existing': True, 'mysql_engine': 'InnoDB',
882 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
882 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
883 )
883 )
884 __mapper_args__ = {}
884 __mapper_args__ = {}
885
885
886 # ApiKey role
886 # ApiKey role
887 ROLE_ALL = 'token_role_all'
887 ROLE_ALL = 'token_role_all'
888 ROLE_HTTP = 'token_role_http'
888 ROLE_HTTP = 'token_role_http'
889 ROLE_VCS = 'token_role_vcs'
889 ROLE_VCS = 'token_role_vcs'
890 ROLE_API = 'token_role_api'
890 ROLE_API = 'token_role_api'
891 ROLE_FEED = 'token_role_feed'
891 ROLE_FEED = 'token_role_feed'
892 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
892 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
893
893
894 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
894 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
895 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
895 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
896 api_key = Column("api_key", String(255), nullable=False, unique=True)
896 api_key = Column("api_key", String(255), nullable=False, unique=True)
897 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
897 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
898 expires = Column('expires', Float(53), nullable=False)
898 expires = Column('expires', Float(53), nullable=False)
899 role = Column('role', String(255), nullable=True)
899 role = Column('role', String(255), nullable=True)
900 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
900 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
901
901
902 user = relationship('User', lazy='joined')
902 user = relationship('User', lazy='joined')
903
903
904 @classmethod
904 @classmethod
905 def _get_role_name(cls, role):
905 def _get_role_name(cls, role):
906 return {
906 return {
907 cls.ROLE_ALL: _('all'),
907 cls.ROLE_ALL: _('all'),
908 cls.ROLE_HTTP: _('http/web interface'),
908 cls.ROLE_HTTP: _('http/web interface'),
909 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
909 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
910 cls.ROLE_API: _('api calls'),
910 cls.ROLE_API: _('api calls'),
911 cls.ROLE_FEED: _('feed access'),
911 cls.ROLE_FEED: _('feed access'),
912 }.get(role, role)
912 }.get(role, role)
913
913
914 @property
914 @property
915 def expired(self):
915 def expired(self):
916 if self.expires == -1:
916 if self.expires == -1:
917 return False
917 return False
918 return time.time() > self.expires
918 return time.time() > self.expires
919
919
920 @property
920 @property
921 def role_humanized(self):
921 def role_humanized(self):
922 return self._get_role_name(self.role)
922 return self._get_role_name(self.role)
923
923
924
924
925 class UserEmailMap(Base, BaseModel):
925 class UserEmailMap(Base, BaseModel):
926 __tablename__ = 'user_email_map'
926 __tablename__ = 'user_email_map'
927 __table_args__ = (
927 __table_args__ = (
928 Index('uem_email_idx', 'email'),
928 Index('uem_email_idx', 'email'),
929 UniqueConstraint('email'),
929 UniqueConstraint('email'),
930 {'extend_existing': True, 'mysql_engine': 'InnoDB',
930 {'extend_existing': True, 'mysql_engine': 'InnoDB',
931 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
931 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
932 )
932 )
933 __mapper_args__ = {}
933 __mapper_args__ = {}
934
934
935 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
935 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
936 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
936 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
937 _email = Column("email", String(255), nullable=True, unique=False, default=None)
937 _email = Column("email", String(255), nullable=True, unique=False, default=None)
938 user = relationship('User', lazy='joined')
938 user = relationship('User', lazy='joined')
939
939
940 @validates('_email')
940 @validates('_email')
941 def validate_email(self, key, email):
941 def validate_email(self, key, email):
942 # check if this email is not main one
942 # check if this email is not main one
943 main_email = Session().query(User).filter(User.email == email).scalar()
943 main_email = Session().query(User).filter(User.email == email).scalar()
944 if main_email is not None:
944 if main_email is not None:
945 raise AttributeError('email %s is present is user table' % email)
945 raise AttributeError('email %s is present is user table' % email)
946 return email
946 return email
947
947
948 @hybrid_property
948 @hybrid_property
949 def email(self):
949 def email(self):
950 return self._email
950 return self._email
951
951
952 @email.setter
952 @email.setter
953 def email(self, val):
953 def email(self, val):
954 self._email = val.lower() if val else None
954 self._email = val.lower() if val else None
955
955
956
956
957 class UserIpMap(Base, BaseModel):
957 class UserIpMap(Base, BaseModel):
958 __tablename__ = 'user_ip_map'
958 __tablename__ = 'user_ip_map'
959 __table_args__ = (
959 __table_args__ = (
960 UniqueConstraint('user_id', 'ip_addr'),
960 UniqueConstraint('user_id', 'ip_addr'),
961 {'extend_existing': True, 'mysql_engine': 'InnoDB',
961 {'extend_existing': True, 'mysql_engine': 'InnoDB',
962 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
962 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
963 )
963 )
964 __mapper_args__ = {}
964 __mapper_args__ = {}
965
965
966 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
966 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
967 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
967 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
968 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
968 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
969 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
969 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
970 description = Column("description", String(10000), nullable=True, unique=None, default=None)
970 description = Column("description", String(10000), nullable=True, unique=None, default=None)
971 user = relationship('User', lazy='joined')
971 user = relationship('User', lazy='joined')
972
972
973 @classmethod
973 @classmethod
974 def _get_ip_range(cls, ip_addr):
974 def _get_ip_range(cls, ip_addr):
975 net = ipaddress.ip_network(ip_addr, strict=False)
975 net = ipaddress.ip_network(ip_addr, strict=False)
976 return [str(net.network_address), str(net.broadcast_address)]
976 return [str(net.network_address), str(net.broadcast_address)]
977
977
978 def __json__(self):
978 def __json__(self):
979 return {
979 return {
980 'ip_addr': self.ip_addr,
980 'ip_addr': self.ip_addr,
981 'ip_range': self._get_ip_range(self.ip_addr),
981 'ip_range': self._get_ip_range(self.ip_addr),
982 }
982 }
983
983
984 def __unicode__(self):
984 def __unicode__(self):
985 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
985 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
986 self.user_id, self.ip_addr)
986 self.user_id, self.ip_addr)
987
987
988 class UserLog(Base, BaseModel):
988 class UserLog(Base, BaseModel):
989 __tablename__ = 'user_logs'
989 __tablename__ = 'user_logs'
990 __table_args__ = (
990 __table_args__ = (
991 {'extend_existing': True, 'mysql_engine': 'InnoDB',
991 {'extend_existing': True, 'mysql_engine': 'InnoDB',
992 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
992 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
993 )
993 )
994 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
994 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
995 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
995 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
996 username = Column("username", String(255), nullable=True, unique=None, default=None)
996 username = Column("username", String(255), nullable=True, unique=None, default=None)
997 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
997 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
998 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
998 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
999 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
999 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1000 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1000 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1001 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1001 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1002
1002
1003 def __unicode__(self):
1003 def __unicode__(self):
1004 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1004 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1005 self.repository_name,
1005 self.repository_name,
1006 self.action)
1006 self.action)
1007
1007
1008 @property
1008 @property
1009 def action_as_day(self):
1009 def action_as_day(self):
1010 return datetime.date(*self.action_date.timetuple()[:3])
1010 return datetime.date(*self.action_date.timetuple()[:3])
1011
1011
1012 user = relationship('User')
1012 user = relationship('User')
1013 repository = relationship('Repository', cascade='')
1013 repository = relationship('Repository', cascade='')
1014
1014
1015
1015
1016 class UserGroup(Base, BaseModel):
1016 class UserGroup(Base, BaseModel):
1017 __tablename__ = 'users_groups'
1017 __tablename__ = 'users_groups'
1018 __table_args__ = (
1018 __table_args__ = (
1019 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1019 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1020 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1020 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1021 )
1021 )
1022
1022
1023 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1023 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1024 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1024 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1025 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1025 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1026 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1026 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1027 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1027 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1028 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1028 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1029 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1029 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1030 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1030 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1031
1031
1032 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1032 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1033 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1033 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1034 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1034 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1035 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1035 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1036 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1036 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1037 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1037 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1038
1038
1039 user = relationship('User')
1039 user = relationship('User')
1040
1040
1041 @hybrid_property
1041 @hybrid_property
1042 def group_data(self):
1042 def group_data(self):
1043 if not self._group_data:
1043 if not self._group_data:
1044 return {}
1044 return {}
1045
1045
1046 try:
1046 try:
1047 return json.loads(self._group_data)
1047 return json.loads(self._group_data)
1048 except TypeError:
1048 except TypeError:
1049 return {}
1049 return {}
1050
1050
1051 @group_data.setter
1051 @group_data.setter
1052 def group_data(self, val):
1052 def group_data(self, val):
1053 try:
1053 try:
1054 self._group_data = json.dumps(val)
1054 self._group_data = json.dumps(val)
1055 except Exception:
1055 except Exception:
1056 log.error(traceback.format_exc())
1056 log.error(traceback.format_exc())
1057
1057
1058 def __unicode__(self):
1058 def __unicode__(self):
1059 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1059 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1060 self.users_group_id,
1060 self.users_group_id,
1061 self.users_group_name)
1061 self.users_group_name)
1062
1062
1063 @classmethod
1063 @classmethod
1064 def get_by_group_name(cls, group_name, cache=False,
1064 def get_by_group_name(cls, group_name, cache=False,
1065 case_insensitive=False):
1065 case_insensitive=False):
1066 if case_insensitive:
1066 if case_insensitive:
1067 q = cls.query().filter(func.lower(cls.users_group_name) ==
1067 q = cls.query().filter(func.lower(cls.users_group_name) ==
1068 func.lower(group_name))
1068 func.lower(group_name))
1069
1069
1070 else:
1070 else:
1071 q = cls.query().filter(cls.users_group_name == group_name)
1071 q = cls.query().filter(cls.users_group_name == group_name)
1072 if cache:
1072 if cache:
1073 q = q.options(FromCache(
1073 q = q.options(FromCache(
1074 "sql_cache_short",
1074 "sql_cache_short",
1075 "get_group_%s" % _hash_key(group_name)))
1075 "get_group_%s" % _hash_key(group_name)))
1076 return q.scalar()
1076 return q.scalar()
1077
1077
1078 @classmethod
1078 @classmethod
1079 def get(cls, user_group_id, cache=False):
1079 def get(cls, user_group_id, cache=False):
1080 user_group = cls.query()
1080 user_group = cls.query()
1081 if cache:
1081 if cache:
1082 user_group = user_group.options(FromCache("sql_cache_short",
1082 user_group = user_group.options(FromCache("sql_cache_short",
1083 "get_users_group_%s" % user_group_id))
1083 "get_users_group_%s" % user_group_id))
1084 return user_group.get(user_group_id)
1084 return user_group.get(user_group_id)
1085
1085
1086 def permissions(self, with_admins=True, with_owner=True):
1086 def permissions(self, with_admins=True, with_owner=True):
1087 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1087 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1088 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1088 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1089 joinedload(UserUserGroupToPerm.user),
1089 joinedload(UserUserGroupToPerm.user),
1090 joinedload(UserUserGroupToPerm.permission),)
1090 joinedload(UserUserGroupToPerm.permission),)
1091
1091
1092 # get owners and admins and permissions. We do a trick of re-writing
1092 # get owners and admins and permissions. We do a trick of re-writing
1093 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1093 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1094 # has a global reference and changing one object propagates to all
1094 # has a global reference and changing one object propagates to all
1095 # others. This means if admin is also an owner admin_row that change
1095 # others. This means if admin is also an owner admin_row that change
1096 # would propagate to both objects
1096 # would propagate to both objects
1097 perm_rows = []
1097 perm_rows = []
1098 for _usr in q.all():
1098 for _usr in q.all():
1099 usr = AttributeDict(_usr.user.get_dict())
1099 usr = AttributeDict(_usr.user.get_dict())
1100 usr.permission = _usr.permission.permission_name
1100 usr.permission = _usr.permission.permission_name
1101 perm_rows.append(usr)
1101 perm_rows.append(usr)
1102
1102
1103 # filter the perm rows by 'default' first and then sort them by
1103 # filter the perm rows by 'default' first and then sort them by
1104 # admin,write,read,none permissions sorted again alphabetically in
1104 # admin,write,read,none permissions sorted again alphabetically in
1105 # each group
1105 # each group
1106 perm_rows = sorted(perm_rows, key=display_sort)
1106 perm_rows = sorted(perm_rows, key=display_sort)
1107
1107
1108 _admin_perm = 'usergroup.admin'
1108 _admin_perm = 'usergroup.admin'
1109 owner_row = []
1109 owner_row = []
1110 if with_owner:
1110 if with_owner:
1111 usr = AttributeDict(self.user.get_dict())
1111 usr = AttributeDict(self.user.get_dict())
1112 usr.owner_row = True
1112 usr.owner_row = True
1113 usr.permission = _admin_perm
1113 usr.permission = _admin_perm
1114 owner_row.append(usr)
1114 owner_row.append(usr)
1115
1115
1116 super_admin_rows = []
1116 super_admin_rows = []
1117 if with_admins:
1117 if with_admins:
1118 for usr in User.get_all_super_admins():
1118 for usr in User.get_all_super_admins():
1119 # if this admin is also owner, don't double the record
1119 # if this admin is also owner, don't double the record
1120 if usr.user_id == owner_row[0].user_id:
1120 if usr.user_id == owner_row[0].user_id:
1121 owner_row[0].admin_row = True
1121 owner_row[0].admin_row = True
1122 else:
1122 else:
1123 usr = AttributeDict(usr.get_dict())
1123 usr = AttributeDict(usr.get_dict())
1124 usr.admin_row = True
1124 usr.admin_row = True
1125 usr.permission = _admin_perm
1125 usr.permission = _admin_perm
1126 super_admin_rows.append(usr)
1126 super_admin_rows.append(usr)
1127
1127
1128 return super_admin_rows + owner_row + perm_rows
1128 return super_admin_rows + owner_row + perm_rows
1129
1129
1130 def permission_user_groups(self):
1130 def permission_user_groups(self):
1131 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1131 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1132 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1132 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1133 joinedload(UserGroupUserGroupToPerm.target_user_group),
1133 joinedload(UserGroupUserGroupToPerm.target_user_group),
1134 joinedload(UserGroupUserGroupToPerm.permission),)
1134 joinedload(UserGroupUserGroupToPerm.permission),)
1135
1135
1136 perm_rows = []
1136 perm_rows = []
1137 for _user_group in q.all():
1137 for _user_group in q.all():
1138 usr = AttributeDict(_user_group.user_group.get_dict())
1138 usr = AttributeDict(_user_group.user_group.get_dict())
1139 usr.permission = _user_group.permission.permission_name
1139 usr.permission = _user_group.permission.permission_name
1140 perm_rows.append(usr)
1140 perm_rows.append(usr)
1141
1141
1142 return perm_rows
1142 return perm_rows
1143
1143
1144 def _get_default_perms(self, user_group, suffix=''):
1144 def _get_default_perms(self, user_group, suffix=''):
1145 from rhodecode.model.permission import PermissionModel
1145 from rhodecode.model.permission import PermissionModel
1146 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1146 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1147
1147
1148 def get_default_perms(self, suffix=''):
1148 def get_default_perms(self, suffix=''):
1149 return self._get_default_perms(self, suffix)
1149 return self._get_default_perms(self, suffix)
1150
1150
1151 def get_api_data(self, with_group_members=True, include_secrets=False):
1151 def get_api_data(self, with_group_members=True, include_secrets=False):
1152 """
1152 """
1153 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1153 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1154 basically forwarded.
1154 basically forwarded.
1155
1155
1156 """
1156 """
1157 user_group = self
1157 user_group = self
1158
1158
1159 data = {
1159 data = {
1160 'users_group_id': user_group.users_group_id,
1160 'users_group_id': user_group.users_group_id,
1161 'group_name': user_group.users_group_name,
1161 'group_name': user_group.users_group_name,
1162 'group_description': user_group.user_group_description,
1162 'group_description': user_group.user_group_description,
1163 'active': user_group.users_group_active,
1163 'active': user_group.users_group_active,
1164 'owner': user_group.user.username,
1164 'owner': user_group.user.username,
1165 }
1165 }
1166 if with_group_members:
1166 if with_group_members:
1167 users = []
1167 users = []
1168 for user in user_group.members:
1168 for user in user_group.members:
1169 user = user.user
1169 user = user.user
1170 users.append(user.get_api_data(include_secrets=include_secrets))
1170 users.append(user.get_api_data(include_secrets=include_secrets))
1171 data['users'] = users
1171 data['users'] = users
1172
1172
1173 return data
1173 return data
1174
1174
1175
1175
1176 class UserGroupMember(Base, BaseModel):
1176 class UserGroupMember(Base, BaseModel):
1177 __tablename__ = 'users_groups_members'
1177 __tablename__ = 'users_groups_members'
1178 __table_args__ = (
1178 __table_args__ = (
1179 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1179 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1180 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1180 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1181 )
1181 )
1182
1182
1183 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1183 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1184 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1184 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1185 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1185 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1186
1186
1187 user = relationship('User', lazy='joined')
1187 user = relationship('User', lazy='joined')
1188 users_group = relationship('UserGroup')
1188 users_group = relationship('UserGroup')
1189
1189
1190 def __init__(self, gr_id='', u_id=''):
1190 def __init__(self, gr_id='', u_id=''):
1191 self.users_group_id = gr_id
1191 self.users_group_id = gr_id
1192 self.user_id = u_id
1192 self.user_id = u_id
1193
1193
1194
1194
1195 class RepositoryField(Base, BaseModel):
1195 class RepositoryField(Base, BaseModel):
1196 __tablename__ = 'repositories_fields'
1196 __tablename__ = 'repositories_fields'
1197 __table_args__ = (
1197 __table_args__ = (
1198 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1198 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1199 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1199 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1200 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1200 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1201 )
1201 )
1202 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1202 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1203
1203
1204 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1204 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1205 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1205 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1206 field_key = Column("field_key", String(250))
1206 field_key = Column("field_key", String(250))
1207 field_label = Column("field_label", String(1024), nullable=False)
1207 field_label = Column("field_label", String(1024), nullable=False)
1208 field_value = Column("field_value", String(10000), nullable=False)
1208 field_value = Column("field_value", String(10000), nullable=False)
1209 field_desc = Column("field_desc", String(1024), nullable=False)
1209 field_desc = Column("field_desc", String(1024), nullable=False)
1210 field_type = Column("field_type", String(255), nullable=False, unique=None)
1210 field_type = Column("field_type", String(255), nullable=False, unique=None)
1211 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1211 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1212
1212
1213 repository = relationship('Repository')
1213 repository = relationship('Repository')
1214
1214
1215 @property
1215 @property
1216 def field_key_prefixed(self):
1216 def field_key_prefixed(self):
1217 return 'ex_%s' % self.field_key
1217 return 'ex_%s' % self.field_key
1218
1218
1219 @classmethod
1219 @classmethod
1220 def un_prefix_key(cls, key):
1220 def un_prefix_key(cls, key):
1221 if key.startswith(cls.PREFIX):
1221 if key.startswith(cls.PREFIX):
1222 return key[len(cls.PREFIX):]
1222 return key[len(cls.PREFIX):]
1223 return key
1223 return key
1224
1224
1225 @classmethod
1225 @classmethod
1226 def get_by_key_name(cls, key, repo):
1226 def get_by_key_name(cls, key, repo):
1227 row = cls.query()\
1227 row = cls.query()\
1228 .filter(cls.repository == repo)\
1228 .filter(cls.repository == repo)\
1229 .filter(cls.field_key == key).scalar()
1229 .filter(cls.field_key == key).scalar()
1230 return row
1230 return row
1231
1231
1232
1232
1233 class Repository(Base, BaseModel):
1233 class Repository(Base, BaseModel):
1234 __tablename__ = 'repositories'
1234 __tablename__ = 'repositories'
1235 __table_args__ = (
1235 __table_args__ = (
1236 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1236 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1237 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1237 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1238 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1238 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1239 )
1239 )
1240 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1240 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1241 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1241 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1242
1242
1243 STATE_CREATED = 'repo_state_created'
1243 STATE_CREATED = 'repo_state_created'
1244 STATE_PENDING = 'repo_state_pending'
1244 STATE_PENDING = 'repo_state_pending'
1245 STATE_ERROR = 'repo_state_error'
1245 STATE_ERROR = 'repo_state_error'
1246
1246
1247 LOCK_AUTOMATIC = 'lock_auto'
1247 LOCK_AUTOMATIC = 'lock_auto'
1248 LOCK_API = 'lock_api'
1248 LOCK_API = 'lock_api'
1249 LOCK_WEB = 'lock_web'
1249 LOCK_WEB = 'lock_web'
1250 LOCK_PULL = 'lock_pull'
1250 LOCK_PULL = 'lock_pull'
1251
1251
1252 NAME_SEP = URL_SEP
1252 NAME_SEP = URL_SEP
1253
1253
1254 repo_id = Column(
1254 repo_id = Column(
1255 "repo_id", Integer(), nullable=False, unique=True, default=None,
1255 "repo_id", Integer(), nullable=False, unique=True, default=None,
1256 primary_key=True)
1256 primary_key=True)
1257 _repo_name = Column(
1257 _repo_name = Column(
1258 "repo_name", Text(), nullable=False, default=None)
1258 "repo_name", Text(), nullable=False, default=None)
1259 _repo_name_hash = Column(
1259 _repo_name_hash = Column(
1260 "repo_name_hash", String(255), nullable=False, unique=True)
1260 "repo_name_hash", String(255), nullable=False, unique=True)
1261 repo_state = Column("repo_state", String(255), nullable=True)
1261 repo_state = Column("repo_state", String(255), nullable=True)
1262
1262
1263 clone_uri = Column(
1263 clone_uri = Column(
1264 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1264 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1265 default=None)
1265 default=None)
1266 repo_type = Column(
1266 repo_type = Column(
1267 "repo_type", String(255), nullable=False, unique=False, default=None)
1267 "repo_type", String(255), nullable=False, unique=False, default=None)
1268 user_id = Column(
1268 user_id = Column(
1269 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1269 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1270 unique=False, default=None)
1270 unique=False, default=None)
1271 private = Column(
1271 private = Column(
1272 "private", Boolean(), nullable=True, unique=None, default=None)
1272 "private", Boolean(), nullable=True, unique=None, default=None)
1273 enable_statistics = Column(
1273 enable_statistics = Column(
1274 "statistics", Boolean(), nullable=True, unique=None, default=True)
1274 "statistics", Boolean(), nullable=True, unique=None, default=True)
1275 enable_downloads = Column(
1275 enable_downloads = Column(
1276 "downloads", Boolean(), nullable=True, unique=None, default=True)
1276 "downloads", Boolean(), nullable=True, unique=None, default=True)
1277 description = Column(
1277 description = Column(
1278 "description", String(10000), nullable=True, unique=None, default=None)
1278 "description", String(10000), nullable=True, unique=None, default=None)
1279 created_on = Column(
1279 created_on = Column(
1280 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1280 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1281 default=datetime.datetime.now)
1281 default=datetime.datetime.now)
1282 updated_on = Column(
1282 updated_on = Column(
1283 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1283 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1284 default=datetime.datetime.now)
1284 default=datetime.datetime.now)
1285 _landing_revision = Column(
1285 _landing_revision = Column(
1286 "landing_revision", String(255), nullable=False, unique=False,
1286 "landing_revision", String(255), nullable=False, unique=False,
1287 default=None)
1287 default=None)
1288 enable_locking = Column(
1288 enable_locking = Column(
1289 "enable_locking", Boolean(), nullable=False, unique=None,
1289 "enable_locking", Boolean(), nullable=False, unique=None,
1290 default=False)
1290 default=False)
1291 _locked = Column(
1291 _locked = Column(
1292 "locked", String(255), nullable=True, unique=False, default=None)
1292 "locked", String(255), nullable=True, unique=False, default=None)
1293 _changeset_cache = Column(
1293 _changeset_cache = Column(
1294 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1294 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1295
1295
1296 fork_id = Column(
1296 fork_id = Column(
1297 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1297 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1298 nullable=True, unique=False, default=None)
1298 nullable=True, unique=False, default=None)
1299 group_id = Column(
1299 group_id = Column(
1300 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1300 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1301 unique=False, default=None)
1301 unique=False, default=None)
1302
1302
1303 user = relationship('User', lazy='joined')
1303 user = relationship('User', lazy='joined')
1304 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1304 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1305 group = relationship('RepoGroup', lazy='joined')
1305 group = relationship('RepoGroup', lazy='joined')
1306 repo_to_perm = relationship(
1306 repo_to_perm = relationship(
1307 'UserRepoToPerm', cascade='all',
1307 'UserRepoToPerm', cascade='all',
1308 order_by='UserRepoToPerm.repo_to_perm_id')
1308 order_by='UserRepoToPerm.repo_to_perm_id')
1309 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1309 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1310 stats = relationship('Statistics', cascade='all', uselist=False)
1310 stats = relationship('Statistics', cascade='all', uselist=False)
1311
1311
1312 followers = relationship(
1312 followers = relationship(
1313 'UserFollowing',
1313 'UserFollowing',
1314 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1314 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1315 cascade='all')
1315 cascade='all')
1316 extra_fields = relationship(
1316 extra_fields = relationship(
1317 'RepositoryField', cascade="all, delete, delete-orphan")
1317 'RepositoryField', cascade="all, delete, delete-orphan")
1318 logs = relationship('UserLog')
1318 logs = relationship('UserLog')
1319 comments = relationship(
1319 comments = relationship(
1320 'ChangesetComment', cascade="all, delete, delete-orphan")
1320 'ChangesetComment', cascade="all, delete, delete-orphan")
1321 pull_requests_source = relationship(
1321 pull_requests_source = relationship(
1322 'PullRequest',
1322 'PullRequest',
1323 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1323 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1324 cascade="all, delete, delete-orphan")
1324 cascade="all, delete, delete-orphan")
1325 pull_requests_target = relationship(
1325 pull_requests_target = relationship(
1326 'PullRequest',
1326 'PullRequest',
1327 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1327 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1328 cascade="all, delete, delete-orphan")
1328 cascade="all, delete, delete-orphan")
1329 ui = relationship('RepoRhodeCodeUi', cascade="all")
1329 ui = relationship('RepoRhodeCodeUi', cascade="all")
1330 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1330 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1331 integrations = relationship('Integration',
1331 integrations = relationship('Integration',
1332 cascade="all, delete, delete-orphan")
1332 cascade="all, delete, delete-orphan")
1333
1333
1334 def __unicode__(self):
1334 def __unicode__(self):
1335 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1335 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1336 safe_unicode(self.repo_name))
1336 safe_unicode(self.repo_name))
1337
1337
1338 @hybrid_property
1338 @hybrid_property
1339 def landing_rev(self):
1339 def landing_rev(self):
1340 # always should return [rev_type, rev]
1340 # always should return [rev_type, rev]
1341 if self._landing_revision:
1341 if self._landing_revision:
1342 _rev_info = self._landing_revision.split(':')
1342 _rev_info = self._landing_revision.split(':')
1343 if len(_rev_info) < 2:
1343 if len(_rev_info) < 2:
1344 _rev_info.insert(0, 'rev')
1344 _rev_info.insert(0, 'rev')
1345 return [_rev_info[0], _rev_info[1]]
1345 return [_rev_info[0], _rev_info[1]]
1346 return [None, None]
1346 return [None, None]
1347
1347
1348 @landing_rev.setter
1348 @landing_rev.setter
1349 def landing_rev(self, val):
1349 def landing_rev(self, val):
1350 if ':' not in val:
1350 if ':' not in val:
1351 raise ValueError('value must be delimited with `:` and consist '
1351 raise ValueError('value must be delimited with `:` and consist '
1352 'of <rev_type>:<rev>, got %s instead' % val)
1352 'of <rev_type>:<rev>, got %s instead' % val)
1353 self._landing_revision = val
1353 self._landing_revision = val
1354
1354
1355 @hybrid_property
1355 @hybrid_property
1356 def locked(self):
1356 def locked(self):
1357 if self._locked:
1357 if self._locked:
1358 user_id, timelocked, reason = self._locked.split(':')
1358 user_id, timelocked, reason = self._locked.split(':')
1359 lock_values = int(user_id), timelocked, reason
1359 lock_values = int(user_id), timelocked, reason
1360 else:
1360 else:
1361 lock_values = [None, None, None]
1361 lock_values = [None, None, None]
1362 return lock_values
1362 return lock_values
1363
1363
1364 @locked.setter
1364 @locked.setter
1365 def locked(self, val):
1365 def locked(self, val):
1366 if val and isinstance(val, (list, tuple)):
1366 if val and isinstance(val, (list, tuple)):
1367 self._locked = ':'.join(map(str, val))
1367 self._locked = ':'.join(map(str, val))
1368 else:
1368 else:
1369 self._locked = None
1369 self._locked = None
1370
1370
1371 @hybrid_property
1371 @hybrid_property
1372 def changeset_cache(self):
1372 def changeset_cache(self):
1373 from rhodecode.lib.vcs.backends.base import EmptyCommit
1373 from rhodecode.lib.vcs.backends.base import EmptyCommit
1374 dummy = EmptyCommit().__json__()
1374 dummy = EmptyCommit().__json__()
1375 if not self._changeset_cache:
1375 if not self._changeset_cache:
1376 return dummy
1376 return dummy
1377 try:
1377 try:
1378 return json.loads(self._changeset_cache)
1378 return json.loads(self._changeset_cache)
1379 except TypeError:
1379 except TypeError:
1380 return dummy
1380 return dummy
1381 except Exception:
1381 except Exception:
1382 log.error(traceback.format_exc())
1382 log.error(traceback.format_exc())
1383 return dummy
1383 return dummy
1384
1384
1385 @changeset_cache.setter
1385 @changeset_cache.setter
1386 def changeset_cache(self, val):
1386 def changeset_cache(self, val):
1387 try:
1387 try:
1388 self._changeset_cache = json.dumps(val)
1388 self._changeset_cache = json.dumps(val)
1389 except Exception:
1389 except Exception:
1390 log.error(traceback.format_exc())
1390 log.error(traceback.format_exc())
1391
1391
1392 @hybrid_property
1392 @hybrid_property
1393 def repo_name(self):
1393 def repo_name(self):
1394 return self._repo_name
1394 return self._repo_name
1395
1395
1396 @repo_name.setter
1396 @repo_name.setter
1397 def repo_name(self, value):
1397 def repo_name(self, value):
1398 self._repo_name = value
1398 self._repo_name = value
1399 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1399 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1400
1400
1401 @classmethod
1401 @classmethod
1402 def normalize_repo_name(cls, repo_name):
1402 def normalize_repo_name(cls, repo_name):
1403 """
1403 """
1404 Normalizes os specific repo_name to the format internally stored inside
1404 Normalizes os specific repo_name to the format internally stored inside
1405 database using URL_SEP
1405 database using URL_SEP
1406
1406
1407 :param cls:
1407 :param cls:
1408 :param repo_name:
1408 :param repo_name:
1409 """
1409 """
1410 return cls.NAME_SEP.join(repo_name.split(os.sep))
1410 return cls.NAME_SEP.join(repo_name.split(os.sep))
1411
1411
1412 @classmethod
1412 @classmethod
1413 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1413 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1414 session = Session()
1414 session = Session()
1415 q = session.query(cls).filter(cls.repo_name == repo_name)
1415 q = session.query(cls).filter(cls.repo_name == repo_name)
1416
1416
1417 if cache:
1417 if cache:
1418 if identity_cache:
1418 if identity_cache:
1419 val = cls.identity_cache(session, 'repo_name', repo_name)
1419 val = cls.identity_cache(session, 'repo_name', repo_name)
1420 if val:
1420 if val:
1421 return val
1421 return val
1422 else:
1422 else:
1423 q = q.options(
1423 q = q.options(
1424 FromCache("sql_cache_short",
1424 FromCache("sql_cache_short",
1425 "get_repo_by_name_%s" % _hash_key(repo_name)))
1425 "get_repo_by_name_%s" % _hash_key(repo_name)))
1426
1426
1427 return q.scalar()
1427 return q.scalar()
1428
1428
1429 @classmethod
1429 @classmethod
1430 def get_by_full_path(cls, repo_full_path):
1430 def get_by_full_path(cls, repo_full_path):
1431 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1431 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1432 repo_name = cls.normalize_repo_name(repo_name)
1432 repo_name = cls.normalize_repo_name(repo_name)
1433 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1433 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1434
1434
1435 @classmethod
1435 @classmethod
1436 def get_repo_forks(cls, repo_id):
1436 def get_repo_forks(cls, repo_id):
1437 return cls.query().filter(Repository.fork_id == repo_id)
1437 return cls.query().filter(Repository.fork_id == repo_id)
1438
1438
1439 @classmethod
1439 @classmethod
1440 def base_path(cls):
1440 def base_path(cls):
1441 """
1441 """
1442 Returns base path when all repos are stored
1442 Returns base path when all repos are stored
1443
1443
1444 :param cls:
1444 :param cls:
1445 """
1445 """
1446 q = Session().query(RhodeCodeUi)\
1446 q = Session().query(RhodeCodeUi)\
1447 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1447 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1448 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1448 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1449 return q.one().ui_value
1449 return q.one().ui_value
1450
1450
1451 @classmethod
1451 @classmethod
1452 def is_valid(cls, repo_name):
1452 def is_valid(cls, repo_name):
1453 """
1453 """
1454 returns True if given repo name is a valid filesystem repository
1454 returns True if given repo name is a valid filesystem repository
1455
1455
1456 :param cls:
1456 :param cls:
1457 :param repo_name:
1457 :param repo_name:
1458 """
1458 """
1459 from rhodecode.lib.utils import is_valid_repo
1459 from rhodecode.lib.utils import is_valid_repo
1460
1460
1461 return is_valid_repo(repo_name, cls.base_path())
1461 return is_valid_repo(repo_name, cls.base_path())
1462
1462
1463 @classmethod
1463 @classmethod
1464 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1464 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1465 case_insensitive=True):
1465 case_insensitive=True):
1466 q = Repository.query()
1466 q = Repository.query()
1467
1467
1468 if not isinstance(user_id, Optional):
1468 if not isinstance(user_id, Optional):
1469 q = q.filter(Repository.user_id == user_id)
1469 q = q.filter(Repository.user_id == user_id)
1470
1470
1471 if not isinstance(group_id, Optional):
1471 if not isinstance(group_id, Optional):
1472 q = q.filter(Repository.group_id == group_id)
1472 q = q.filter(Repository.group_id == group_id)
1473
1473
1474 if case_insensitive:
1474 if case_insensitive:
1475 q = q.order_by(func.lower(Repository.repo_name))
1475 q = q.order_by(func.lower(Repository.repo_name))
1476 else:
1476 else:
1477 q = q.order_by(Repository.repo_name)
1477 q = q.order_by(Repository.repo_name)
1478 return q.all()
1478 return q.all()
1479
1479
1480 @property
1480 @property
1481 def forks(self):
1481 def forks(self):
1482 """
1482 """
1483 Return forks of this repo
1483 Return forks of this repo
1484 """
1484 """
1485 return Repository.get_repo_forks(self.repo_id)
1485 return Repository.get_repo_forks(self.repo_id)
1486
1486
1487 @property
1487 @property
1488 def parent(self):
1488 def parent(self):
1489 """
1489 """
1490 Returns fork parent
1490 Returns fork parent
1491 """
1491 """
1492 return self.fork
1492 return self.fork
1493
1493
1494 @property
1494 @property
1495 def just_name(self):
1495 def just_name(self):
1496 return self.repo_name.split(self.NAME_SEP)[-1]
1496 return self.repo_name.split(self.NAME_SEP)[-1]
1497
1497
1498 @property
1498 @property
1499 def groups_with_parents(self):
1499 def groups_with_parents(self):
1500 groups = []
1500 groups = []
1501 if self.group is None:
1501 if self.group is None:
1502 return groups
1502 return groups
1503
1503
1504 cur_gr = self.group
1504 cur_gr = self.group
1505 groups.insert(0, cur_gr)
1505 groups.insert(0, cur_gr)
1506 while 1:
1506 while 1:
1507 gr = getattr(cur_gr, 'parent_group', None)
1507 gr = getattr(cur_gr, 'parent_group', None)
1508 cur_gr = cur_gr.parent_group
1508 cur_gr = cur_gr.parent_group
1509 if gr is None:
1509 if gr is None:
1510 break
1510 break
1511 groups.insert(0, gr)
1511 groups.insert(0, gr)
1512
1512
1513 return groups
1513 return groups
1514
1514
1515 @property
1515 @property
1516 def groups_and_repo(self):
1516 def groups_and_repo(self):
1517 return self.groups_with_parents, self
1517 return self.groups_with_parents, self
1518
1518
1519 @LazyProperty
1519 @LazyProperty
1520 def repo_path(self):
1520 def repo_path(self):
1521 """
1521 """
1522 Returns base full path for that repository means where it actually
1522 Returns base full path for that repository means where it actually
1523 exists on a filesystem
1523 exists on a filesystem
1524 """
1524 """
1525 q = Session().query(RhodeCodeUi).filter(
1525 q = Session().query(RhodeCodeUi).filter(
1526 RhodeCodeUi.ui_key == self.NAME_SEP)
1526 RhodeCodeUi.ui_key == self.NAME_SEP)
1527 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1527 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1528 return q.one().ui_value
1528 return q.one().ui_value
1529
1529
1530 @property
1530 @property
1531 def repo_full_path(self):
1531 def repo_full_path(self):
1532 p = [self.repo_path]
1532 p = [self.repo_path]
1533 # we need to split the name by / since this is how we store the
1533 # we need to split the name by / since this is how we store the
1534 # names in the database, but that eventually needs to be converted
1534 # names in the database, but that eventually needs to be converted
1535 # into a valid system path
1535 # into a valid system path
1536 p += self.repo_name.split(self.NAME_SEP)
1536 p += self.repo_name.split(self.NAME_SEP)
1537 return os.path.join(*map(safe_unicode, p))
1537 return os.path.join(*map(safe_unicode, p))
1538
1538
1539 @property
1539 @property
1540 def cache_keys(self):
1540 def cache_keys(self):
1541 """
1541 """
1542 Returns associated cache keys for that repo
1542 Returns associated cache keys for that repo
1543 """
1543 """
1544 return CacheKey.query()\
1544 return CacheKey.query()\
1545 .filter(CacheKey.cache_args == self.repo_name)\
1545 .filter(CacheKey.cache_args == self.repo_name)\
1546 .order_by(CacheKey.cache_key)\
1546 .order_by(CacheKey.cache_key)\
1547 .all()
1547 .all()
1548
1548
1549 def get_new_name(self, repo_name):
1549 def get_new_name(self, repo_name):
1550 """
1550 """
1551 returns new full repository name based on assigned group and new new
1551 returns new full repository name based on assigned group and new new
1552
1552
1553 :param group_name:
1553 :param group_name:
1554 """
1554 """
1555 path_prefix = self.group.full_path_splitted if self.group else []
1555 path_prefix = self.group.full_path_splitted if self.group else []
1556 return self.NAME_SEP.join(path_prefix + [repo_name])
1556 return self.NAME_SEP.join(path_prefix + [repo_name])
1557
1557
1558 @property
1558 @property
1559 def _config(self):
1559 def _config(self):
1560 """
1560 """
1561 Returns db based config object.
1561 Returns db based config object.
1562 """
1562 """
1563 from rhodecode.lib.utils import make_db_config
1563 from rhodecode.lib.utils import make_db_config
1564 return make_db_config(clear_session=False, repo=self)
1564 return make_db_config(clear_session=False, repo=self)
1565
1565
1566 def permissions(self, with_admins=True, with_owner=True):
1566 def permissions(self, with_admins=True, with_owner=True):
1567 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1567 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1568 q = q.options(joinedload(UserRepoToPerm.repository),
1568 q = q.options(joinedload(UserRepoToPerm.repository),
1569 joinedload(UserRepoToPerm.user),
1569 joinedload(UserRepoToPerm.user),
1570 joinedload(UserRepoToPerm.permission),)
1570 joinedload(UserRepoToPerm.permission),)
1571
1571
1572 # get owners and admins and permissions. We do a trick of re-writing
1572 # get owners and admins and permissions. We do a trick of re-writing
1573 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1573 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1574 # has a global reference and changing one object propagates to all
1574 # has a global reference and changing one object propagates to all
1575 # others. This means if admin is also an owner admin_row that change
1575 # others. This means if admin is also an owner admin_row that change
1576 # would propagate to both objects
1576 # would propagate to both objects
1577 perm_rows = []
1577 perm_rows = []
1578 for _usr in q.all():
1578 for _usr in q.all():
1579 usr = AttributeDict(_usr.user.get_dict())
1579 usr = AttributeDict(_usr.user.get_dict())
1580 usr.permission = _usr.permission.permission_name
1580 usr.permission = _usr.permission.permission_name
1581 perm_rows.append(usr)
1581 perm_rows.append(usr)
1582
1582
1583 # filter the perm rows by 'default' first and then sort them by
1583 # filter the perm rows by 'default' first and then sort them by
1584 # admin,write,read,none permissions sorted again alphabetically in
1584 # admin,write,read,none permissions sorted again alphabetically in
1585 # each group
1585 # each group
1586 perm_rows = sorted(perm_rows, key=display_sort)
1586 perm_rows = sorted(perm_rows, key=display_sort)
1587
1587
1588 _admin_perm = 'repository.admin'
1588 _admin_perm = 'repository.admin'
1589 owner_row = []
1589 owner_row = []
1590 if with_owner:
1590 if with_owner:
1591 usr = AttributeDict(self.user.get_dict())
1591 usr = AttributeDict(self.user.get_dict())
1592 usr.owner_row = True
1592 usr.owner_row = True
1593 usr.permission = _admin_perm
1593 usr.permission = _admin_perm
1594 owner_row.append(usr)
1594 owner_row.append(usr)
1595
1595
1596 super_admin_rows = []
1596 super_admin_rows = []
1597 if with_admins:
1597 if with_admins:
1598 for usr in User.get_all_super_admins():
1598 for usr in User.get_all_super_admins():
1599 # if this admin is also owner, don't double the record
1599 # if this admin is also owner, don't double the record
1600 if usr.user_id == owner_row[0].user_id:
1600 if usr.user_id == owner_row[0].user_id:
1601 owner_row[0].admin_row = True
1601 owner_row[0].admin_row = True
1602 else:
1602 else:
1603 usr = AttributeDict(usr.get_dict())
1603 usr = AttributeDict(usr.get_dict())
1604 usr.admin_row = True
1604 usr.admin_row = True
1605 usr.permission = _admin_perm
1605 usr.permission = _admin_perm
1606 super_admin_rows.append(usr)
1606 super_admin_rows.append(usr)
1607
1607
1608 return super_admin_rows + owner_row + perm_rows
1608 return super_admin_rows + owner_row + perm_rows
1609
1609
1610 def permission_user_groups(self):
1610 def permission_user_groups(self):
1611 q = UserGroupRepoToPerm.query().filter(
1611 q = UserGroupRepoToPerm.query().filter(
1612 UserGroupRepoToPerm.repository == self)
1612 UserGroupRepoToPerm.repository == self)
1613 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1613 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1614 joinedload(UserGroupRepoToPerm.users_group),
1614 joinedload(UserGroupRepoToPerm.users_group),
1615 joinedload(UserGroupRepoToPerm.permission),)
1615 joinedload(UserGroupRepoToPerm.permission),)
1616
1616
1617 perm_rows = []
1617 perm_rows = []
1618 for _user_group in q.all():
1618 for _user_group in q.all():
1619 usr = AttributeDict(_user_group.users_group.get_dict())
1619 usr = AttributeDict(_user_group.users_group.get_dict())
1620 usr.permission = _user_group.permission.permission_name
1620 usr.permission = _user_group.permission.permission_name
1621 perm_rows.append(usr)
1621 perm_rows.append(usr)
1622
1622
1623 return perm_rows
1623 return perm_rows
1624
1624
1625 def get_api_data(self, include_secrets=False):
1625 def get_api_data(self, include_secrets=False):
1626 """
1626 """
1627 Common function for generating repo api data
1627 Common function for generating repo api data
1628
1628
1629 :param include_secrets: See :meth:`User.get_api_data`.
1629 :param include_secrets: See :meth:`User.get_api_data`.
1630
1630
1631 """
1631 """
1632 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1632 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1633 # move this methods on models level.
1633 # move this methods on models level.
1634 from rhodecode.model.settings import SettingsModel
1634 from rhodecode.model.settings import SettingsModel
1635
1635
1636 repo = self
1636 repo = self
1637 _user_id, _time, _reason = self.locked
1637 _user_id, _time, _reason = self.locked
1638
1638
1639 data = {
1639 data = {
1640 'repo_id': repo.repo_id,
1640 'repo_id': repo.repo_id,
1641 'repo_name': repo.repo_name,
1641 'repo_name': repo.repo_name,
1642 'repo_type': repo.repo_type,
1642 'repo_type': repo.repo_type,
1643 'clone_uri': repo.clone_uri or '',
1643 'clone_uri': repo.clone_uri or '',
1644 'url': url('summary_home', repo_name=self.repo_name, qualified=True),
1644 'url': url('summary_home', repo_name=self.repo_name, qualified=True),
1645 'private': repo.private,
1645 'private': repo.private,
1646 'created_on': repo.created_on,
1646 'created_on': repo.created_on,
1647 'description': repo.description,
1647 'description': repo.description,
1648 'landing_rev': repo.landing_rev,
1648 'landing_rev': repo.landing_rev,
1649 'owner': repo.user.username,
1649 'owner': repo.user.username,
1650 'fork_of': repo.fork.repo_name if repo.fork else None,
1650 'fork_of': repo.fork.repo_name if repo.fork else None,
1651 'enable_statistics': repo.enable_statistics,
1651 'enable_statistics': repo.enable_statistics,
1652 'enable_locking': repo.enable_locking,
1652 'enable_locking': repo.enable_locking,
1653 'enable_downloads': repo.enable_downloads,
1653 'enable_downloads': repo.enable_downloads,
1654 'last_changeset': repo.changeset_cache,
1654 'last_changeset': repo.changeset_cache,
1655 'locked_by': User.get(_user_id).get_api_data(
1655 'locked_by': User.get(_user_id).get_api_data(
1656 include_secrets=include_secrets) if _user_id else None,
1656 include_secrets=include_secrets) if _user_id else None,
1657 'locked_date': time_to_datetime(_time) if _time else None,
1657 'locked_date': time_to_datetime(_time) if _time else None,
1658 'lock_reason': _reason if _reason else None,
1658 'lock_reason': _reason if _reason else None,
1659 }
1659 }
1660
1660
1661 # TODO: mikhail: should be per-repo settings here
1661 # TODO: mikhail: should be per-repo settings here
1662 rc_config = SettingsModel().get_all_settings()
1662 rc_config = SettingsModel().get_all_settings()
1663 repository_fields = str2bool(
1663 repository_fields = str2bool(
1664 rc_config.get('rhodecode_repository_fields'))
1664 rc_config.get('rhodecode_repository_fields'))
1665 if repository_fields:
1665 if repository_fields:
1666 for f in self.extra_fields:
1666 for f in self.extra_fields:
1667 data[f.field_key_prefixed] = f.field_value
1667 data[f.field_key_prefixed] = f.field_value
1668
1668
1669 return data
1669 return data
1670
1670
1671 @classmethod
1671 @classmethod
1672 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1672 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1673 if not lock_time:
1673 if not lock_time:
1674 lock_time = time.time()
1674 lock_time = time.time()
1675 if not lock_reason:
1675 if not lock_reason:
1676 lock_reason = cls.LOCK_AUTOMATIC
1676 lock_reason = cls.LOCK_AUTOMATIC
1677 repo.locked = [user_id, lock_time, lock_reason]
1677 repo.locked = [user_id, lock_time, lock_reason]
1678 Session().add(repo)
1678 Session().add(repo)
1679 Session().commit()
1679 Session().commit()
1680
1680
1681 @classmethod
1681 @classmethod
1682 def unlock(cls, repo):
1682 def unlock(cls, repo):
1683 repo.locked = None
1683 repo.locked = None
1684 Session().add(repo)
1684 Session().add(repo)
1685 Session().commit()
1685 Session().commit()
1686
1686
1687 @classmethod
1687 @classmethod
1688 def getlock(cls, repo):
1688 def getlock(cls, repo):
1689 return repo.locked
1689 return repo.locked
1690
1690
1691 def is_user_lock(self, user_id):
1691 def is_user_lock(self, user_id):
1692 if self.lock[0]:
1692 if self.lock[0]:
1693 lock_user_id = safe_int(self.lock[0])
1693 lock_user_id = safe_int(self.lock[0])
1694 user_id = safe_int(user_id)
1694 user_id = safe_int(user_id)
1695 # both are ints, and they are equal
1695 # both are ints, and they are equal
1696 return all([lock_user_id, user_id]) and lock_user_id == user_id
1696 return all([lock_user_id, user_id]) and lock_user_id == user_id
1697
1697
1698 return False
1698 return False
1699
1699
1700 def get_locking_state(self, action, user_id, only_when_enabled=True):
1700 def get_locking_state(self, action, user_id, only_when_enabled=True):
1701 """
1701 """
1702 Checks locking on this repository, if locking is enabled and lock is
1702 Checks locking on this repository, if locking is enabled and lock is
1703 present returns a tuple of make_lock, locked, locked_by.
1703 present returns a tuple of make_lock, locked, locked_by.
1704 make_lock can have 3 states None (do nothing) True, make lock
1704 make_lock can have 3 states None (do nothing) True, make lock
1705 False release lock, This value is later propagated to hooks, which
1705 False release lock, This value is later propagated to hooks, which
1706 do the locking. Think about this as signals passed to hooks what to do.
1706 do the locking. Think about this as signals passed to hooks what to do.
1707
1707
1708 """
1708 """
1709 # TODO: johbo: This is part of the business logic and should be moved
1709 # TODO: johbo: This is part of the business logic and should be moved
1710 # into the RepositoryModel.
1710 # into the RepositoryModel.
1711
1711
1712 if action not in ('push', 'pull'):
1712 if action not in ('push', 'pull'):
1713 raise ValueError("Invalid action value: %s" % repr(action))
1713 raise ValueError("Invalid action value: %s" % repr(action))
1714
1714
1715 # defines if locked error should be thrown to user
1715 # defines if locked error should be thrown to user
1716 currently_locked = False
1716 currently_locked = False
1717 # defines if new lock should be made, tri-state
1717 # defines if new lock should be made, tri-state
1718 make_lock = None
1718 make_lock = None
1719 repo = self
1719 repo = self
1720 user = User.get(user_id)
1720 user = User.get(user_id)
1721
1721
1722 lock_info = repo.locked
1722 lock_info = repo.locked
1723
1723
1724 if repo and (repo.enable_locking or not only_when_enabled):
1724 if repo and (repo.enable_locking or not only_when_enabled):
1725 if action == 'push':
1725 if action == 'push':
1726 # check if it's already locked !, if it is compare users
1726 # check if it's already locked !, if it is compare users
1727 locked_by_user_id = lock_info[0]
1727 locked_by_user_id = lock_info[0]
1728 if user.user_id == locked_by_user_id:
1728 if user.user_id == locked_by_user_id:
1729 log.debug(
1729 log.debug(
1730 'Got `push` action from user %s, now unlocking', user)
1730 'Got `push` action from user %s, now unlocking', user)
1731 # unlock if we have push from user who locked
1731 # unlock if we have push from user who locked
1732 make_lock = False
1732 make_lock = False
1733 else:
1733 else:
1734 # we're not the same user who locked, ban with
1734 # we're not the same user who locked, ban with
1735 # code defined in settings (default is 423 HTTP Locked) !
1735 # code defined in settings (default is 423 HTTP Locked) !
1736 log.debug('Repo %s is currently locked by %s', repo, user)
1736 log.debug('Repo %s is currently locked by %s', repo, user)
1737 currently_locked = True
1737 currently_locked = True
1738 elif action == 'pull':
1738 elif action == 'pull':
1739 # [0] user [1] date
1739 # [0] user [1] date
1740 if lock_info[0] and lock_info[1]:
1740 if lock_info[0] and lock_info[1]:
1741 log.debug('Repo %s is currently locked by %s', repo, user)
1741 log.debug('Repo %s is currently locked by %s', repo, user)
1742 currently_locked = True
1742 currently_locked = True
1743 else:
1743 else:
1744 log.debug('Setting lock on repo %s by %s', repo, user)
1744 log.debug('Setting lock on repo %s by %s', repo, user)
1745 make_lock = True
1745 make_lock = True
1746
1746
1747 else:
1747 else:
1748 log.debug('Repository %s do not have locking enabled', repo)
1748 log.debug('Repository %s do not have locking enabled', repo)
1749
1749
1750 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
1750 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
1751 make_lock, currently_locked, lock_info)
1751 make_lock, currently_locked, lock_info)
1752
1752
1753 from rhodecode.lib.auth import HasRepoPermissionAny
1753 from rhodecode.lib.auth import HasRepoPermissionAny
1754 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
1754 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
1755 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
1755 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
1756 # if we don't have at least write permission we cannot make a lock
1756 # if we don't have at least write permission we cannot make a lock
1757 log.debug('lock state reset back to FALSE due to lack '
1757 log.debug('lock state reset back to FALSE due to lack '
1758 'of at least read permission')
1758 'of at least read permission')
1759 make_lock = False
1759 make_lock = False
1760
1760
1761 return make_lock, currently_locked, lock_info
1761 return make_lock, currently_locked, lock_info
1762
1762
1763 @property
1763 @property
1764 def last_db_change(self):
1764 def last_db_change(self):
1765 return self.updated_on
1765 return self.updated_on
1766
1766
1767 @property
1767 @property
1768 def clone_uri_hidden(self):
1768 def clone_uri_hidden(self):
1769 clone_uri = self.clone_uri
1769 clone_uri = self.clone_uri
1770 if clone_uri:
1770 if clone_uri:
1771 import urlobject
1771 import urlobject
1772 url_obj = urlobject.URLObject(clone_uri)
1772 url_obj = urlobject.URLObject(clone_uri)
1773 if url_obj.password:
1773 if url_obj.password:
1774 clone_uri = url_obj.with_password('*****')
1774 clone_uri = url_obj.with_password('*****')
1775 return clone_uri
1775 return clone_uri
1776
1776
1777 def clone_url(self, **override):
1777 def clone_url(self, **override):
1778 qualified_home_url = url('home', qualified=True)
1778 qualified_home_url = url('home', qualified=True)
1779
1779
1780 uri_tmpl = None
1780 uri_tmpl = None
1781 if 'with_id' in override:
1781 if 'with_id' in override:
1782 uri_tmpl = self.DEFAULT_CLONE_URI_ID
1782 uri_tmpl = self.DEFAULT_CLONE_URI_ID
1783 del override['with_id']
1783 del override['with_id']
1784
1784
1785 if 'uri_tmpl' in override:
1785 if 'uri_tmpl' in override:
1786 uri_tmpl = override['uri_tmpl']
1786 uri_tmpl = override['uri_tmpl']
1787 del override['uri_tmpl']
1787 del override['uri_tmpl']
1788
1788
1789 # we didn't override our tmpl from **overrides
1789 # we didn't override our tmpl from **overrides
1790 if not uri_tmpl:
1790 if not uri_tmpl:
1791 uri_tmpl = self.DEFAULT_CLONE_URI
1791 uri_tmpl = self.DEFAULT_CLONE_URI
1792 try:
1792 try:
1793 from pylons import tmpl_context as c
1793 from pylons import tmpl_context as c
1794 uri_tmpl = c.clone_uri_tmpl
1794 uri_tmpl = c.clone_uri_tmpl
1795 except Exception:
1795 except Exception:
1796 # in any case if we call this outside of request context,
1796 # in any case if we call this outside of request context,
1797 # ie, not having tmpl_context set up
1797 # ie, not having tmpl_context set up
1798 pass
1798 pass
1799
1799
1800 return get_clone_url(uri_tmpl=uri_tmpl,
1800 return get_clone_url(uri_tmpl=uri_tmpl,
1801 qualifed_home_url=qualified_home_url,
1801 qualifed_home_url=qualified_home_url,
1802 repo_name=self.repo_name,
1802 repo_name=self.repo_name,
1803 repo_id=self.repo_id, **override)
1803 repo_id=self.repo_id, **override)
1804
1804
1805 def set_state(self, state):
1805 def set_state(self, state):
1806 self.repo_state = state
1806 self.repo_state = state
1807 Session().add(self)
1807 Session().add(self)
1808 #==========================================================================
1808 #==========================================================================
1809 # SCM PROPERTIES
1809 # SCM PROPERTIES
1810 #==========================================================================
1810 #==========================================================================
1811
1811
1812 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
1812 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
1813 return get_commit_safe(
1813 return get_commit_safe(
1814 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
1814 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
1815
1815
1816 def get_changeset(self, rev=None, pre_load=None):
1816 def get_changeset(self, rev=None, pre_load=None):
1817 warnings.warn("Use get_commit", DeprecationWarning)
1817 warnings.warn("Use get_commit", DeprecationWarning)
1818 commit_id = None
1818 commit_id = None
1819 commit_idx = None
1819 commit_idx = None
1820 if isinstance(rev, basestring):
1820 if isinstance(rev, basestring):
1821 commit_id = rev
1821 commit_id = rev
1822 else:
1822 else:
1823 commit_idx = rev
1823 commit_idx = rev
1824 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
1824 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
1825 pre_load=pre_load)
1825 pre_load=pre_load)
1826
1826
1827 def get_landing_commit(self):
1827 def get_landing_commit(self):
1828 """
1828 """
1829 Returns landing commit, or if that doesn't exist returns the tip
1829 Returns landing commit, or if that doesn't exist returns the tip
1830 """
1830 """
1831 _rev_type, _rev = self.landing_rev
1831 _rev_type, _rev = self.landing_rev
1832 commit = self.get_commit(_rev)
1832 commit = self.get_commit(_rev)
1833 if isinstance(commit, EmptyCommit):
1833 if isinstance(commit, EmptyCommit):
1834 return self.get_commit()
1834 return self.get_commit()
1835 return commit
1835 return commit
1836
1836
1837 def update_commit_cache(self, cs_cache=None, config=None):
1837 def update_commit_cache(self, cs_cache=None, config=None):
1838 """
1838 """
1839 Update cache of last changeset for repository, keys should be::
1839 Update cache of last changeset for repository, keys should be::
1840
1840
1841 short_id
1841 short_id
1842 raw_id
1842 raw_id
1843 revision
1843 revision
1844 parents
1844 parents
1845 message
1845 message
1846 date
1846 date
1847 author
1847 author
1848
1848
1849 :param cs_cache:
1849 :param cs_cache:
1850 """
1850 """
1851 from rhodecode.lib.vcs.backends.base import BaseChangeset
1851 from rhodecode.lib.vcs.backends.base import BaseChangeset
1852 if cs_cache is None:
1852 if cs_cache is None:
1853 # use no-cache version here
1853 # use no-cache version here
1854 scm_repo = self.scm_instance(cache=False, config=config)
1854 scm_repo = self.scm_instance(cache=False, config=config)
1855 if scm_repo:
1855 if scm_repo:
1856 cs_cache = scm_repo.get_commit(
1856 cs_cache = scm_repo.get_commit(
1857 pre_load=["author", "date", "message", "parents"])
1857 pre_load=["author", "date", "message", "parents"])
1858 else:
1858 else:
1859 cs_cache = EmptyCommit()
1859 cs_cache = EmptyCommit()
1860
1860
1861 if isinstance(cs_cache, BaseChangeset):
1861 if isinstance(cs_cache, BaseChangeset):
1862 cs_cache = cs_cache.__json__()
1862 cs_cache = cs_cache.__json__()
1863
1863
1864 def is_outdated(new_cs_cache):
1864 def is_outdated(new_cs_cache):
1865 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
1865 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
1866 new_cs_cache['revision'] != self.changeset_cache['revision']):
1866 new_cs_cache['revision'] != self.changeset_cache['revision']):
1867 return True
1867 return True
1868 return False
1868 return False
1869
1869
1870 # check if we have maybe already latest cached revision
1870 # check if we have maybe already latest cached revision
1871 if is_outdated(cs_cache) or not self.changeset_cache:
1871 if is_outdated(cs_cache) or not self.changeset_cache:
1872 _default = datetime.datetime.fromtimestamp(0)
1872 _default = datetime.datetime.fromtimestamp(0)
1873 last_change = cs_cache.get('date') or _default
1873 last_change = cs_cache.get('date') or _default
1874 log.debug('updated repo %s with new cs cache %s',
1874 log.debug('updated repo %s with new cs cache %s',
1875 self.repo_name, cs_cache)
1875 self.repo_name, cs_cache)
1876 self.updated_on = last_change
1876 self.updated_on = last_change
1877 self.changeset_cache = cs_cache
1877 self.changeset_cache = cs_cache
1878 Session().add(self)
1878 Session().add(self)
1879 Session().commit()
1879 Session().commit()
1880 else:
1880 else:
1881 log.debug('Skipping update_commit_cache for repo:`%s` '
1881 log.debug('Skipping update_commit_cache for repo:`%s` '
1882 'commit already with latest changes', self.repo_name)
1882 'commit already with latest changes', self.repo_name)
1883
1883
1884 @property
1884 @property
1885 def tip(self):
1885 def tip(self):
1886 return self.get_commit('tip')
1886 return self.get_commit('tip')
1887
1887
1888 @property
1888 @property
1889 def author(self):
1889 def author(self):
1890 return self.tip.author
1890 return self.tip.author
1891
1891
1892 @property
1892 @property
1893 def last_change(self):
1893 def last_change(self):
1894 return self.scm_instance().last_change
1894 return self.scm_instance().last_change
1895
1895
1896 def get_comments(self, revisions=None):
1896 def get_comments(self, revisions=None):
1897 """
1897 """
1898 Returns comments for this repository grouped by revisions
1898 Returns comments for this repository grouped by revisions
1899
1899
1900 :param revisions: filter query by revisions only
1900 :param revisions: filter query by revisions only
1901 """
1901 """
1902 cmts = ChangesetComment.query()\
1902 cmts = ChangesetComment.query()\
1903 .filter(ChangesetComment.repo == self)
1903 .filter(ChangesetComment.repo == self)
1904 if revisions:
1904 if revisions:
1905 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
1905 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
1906 grouped = collections.defaultdict(list)
1906 grouped = collections.defaultdict(list)
1907 for cmt in cmts.all():
1907 for cmt in cmts.all():
1908 grouped[cmt.revision].append(cmt)
1908 grouped[cmt.revision].append(cmt)
1909 return grouped
1909 return grouped
1910
1910
1911 def statuses(self, revisions=None):
1911 def statuses(self, revisions=None):
1912 """
1912 """
1913 Returns statuses for this repository
1913 Returns statuses for this repository
1914
1914
1915 :param revisions: list of revisions to get statuses for
1915 :param revisions: list of revisions to get statuses for
1916 """
1916 """
1917 statuses = ChangesetStatus.query()\
1917 statuses = ChangesetStatus.query()\
1918 .filter(ChangesetStatus.repo == self)\
1918 .filter(ChangesetStatus.repo == self)\
1919 .filter(ChangesetStatus.version == 0)
1919 .filter(ChangesetStatus.version == 0)
1920
1920
1921 if revisions:
1921 if revisions:
1922 # Try doing the filtering in chunks to avoid hitting limits
1922 # Try doing the filtering in chunks to avoid hitting limits
1923 size = 500
1923 size = 500
1924 status_results = []
1924 status_results = []
1925 for chunk in xrange(0, len(revisions), size):
1925 for chunk in xrange(0, len(revisions), size):
1926 status_results += statuses.filter(
1926 status_results += statuses.filter(
1927 ChangesetStatus.revision.in_(
1927 ChangesetStatus.revision.in_(
1928 revisions[chunk: chunk+size])
1928 revisions[chunk: chunk+size])
1929 ).all()
1929 ).all()
1930 else:
1930 else:
1931 status_results = statuses.all()
1931 status_results = statuses.all()
1932
1932
1933 grouped = {}
1933 grouped = {}
1934
1934
1935 # maybe we have open new pullrequest without a status?
1935 # maybe we have open new pullrequest without a status?
1936 stat = ChangesetStatus.STATUS_UNDER_REVIEW
1936 stat = ChangesetStatus.STATUS_UNDER_REVIEW
1937 status_lbl = ChangesetStatus.get_status_lbl(stat)
1937 status_lbl = ChangesetStatus.get_status_lbl(stat)
1938 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
1938 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
1939 for rev in pr.revisions:
1939 for rev in pr.revisions:
1940 pr_id = pr.pull_request_id
1940 pr_id = pr.pull_request_id
1941 pr_repo = pr.target_repo.repo_name
1941 pr_repo = pr.target_repo.repo_name
1942 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
1942 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
1943
1943
1944 for stat in status_results:
1944 for stat in status_results:
1945 pr_id = pr_repo = None
1945 pr_id = pr_repo = None
1946 if stat.pull_request:
1946 if stat.pull_request:
1947 pr_id = stat.pull_request.pull_request_id
1947 pr_id = stat.pull_request.pull_request_id
1948 pr_repo = stat.pull_request.target_repo.repo_name
1948 pr_repo = stat.pull_request.target_repo.repo_name
1949 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
1949 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
1950 pr_id, pr_repo]
1950 pr_id, pr_repo]
1951 return grouped
1951 return grouped
1952
1952
1953 # ==========================================================================
1953 # ==========================================================================
1954 # SCM CACHE INSTANCE
1954 # SCM CACHE INSTANCE
1955 # ==========================================================================
1955 # ==========================================================================
1956
1956
1957 def scm_instance(self, **kwargs):
1957 def scm_instance(self, **kwargs):
1958 import rhodecode
1958 import rhodecode
1959
1959
1960 # Passing a config will not hit the cache currently only used
1960 # Passing a config will not hit the cache currently only used
1961 # for repo2dbmapper
1961 # for repo2dbmapper
1962 config = kwargs.pop('config', None)
1962 config = kwargs.pop('config', None)
1963 cache = kwargs.pop('cache', None)
1963 cache = kwargs.pop('cache', None)
1964 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
1964 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
1965 # if cache is NOT defined use default global, else we have a full
1965 # if cache is NOT defined use default global, else we have a full
1966 # control over cache behaviour
1966 # control over cache behaviour
1967 if cache is None and full_cache and not config:
1967 if cache is None and full_cache and not config:
1968 return self._get_instance_cached()
1968 return self._get_instance_cached()
1969 return self._get_instance(cache=bool(cache), config=config)
1969 return self._get_instance(cache=bool(cache), config=config)
1970
1970
1971 def _get_instance_cached(self):
1971 def _get_instance_cached(self):
1972 @cache_region('long_term')
1972 @cache_region('long_term')
1973 def _get_repo(cache_key):
1973 def _get_repo(cache_key):
1974 return self._get_instance()
1974 return self._get_instance()
1975
1975
1976 invalidator_context = CacheKey.repo_context_cache(
1976 invalidator_context = CacheKey.repo_context_cache(
1977 _get_repo, self.repo_name, None, thread_scoped=True)
1977 _get_repo, self.repo_name, None, thread_scoped=True)
1978
1978
1979 with invalidator_context as context:
1979 with invalidator_context as context:
1980 context.invalidate()
1980 context.invalidate()
1981 repo = context.compute()
1981 repo = context.compute()
1982
1982
1983 return repo
1983 return repo
1984
1984
1985 def _get_instance(self, cache=True, config=None):
1985 def _get_instance(self, cache=True, config=None):
1986 config = config or self._config
1986 config = config or self._config
1987 custom_wire = {
1987 custom_wire = {
1988 'cache': cache # controls the vcs.remote cache
1988 'cache': cache # controls the vcs.remote cache
1989 }
1989 }
1990 repo = get_vcs_instance(
1990 repo = get_vcs_instance(
1991 repo_path=safe_str(self.repo_full_path),
1991 repo_path=safe_str(self.repo_full_path),
1992 config=config,
1992 config=config,
1993 with_wire=custom_wire,
1993 with_wire=custom_wire,
1994 create=False,
1994 create=False,
1995 _vcs_alias=self.repo_type)
1995 _vcs_alias=self.repo_type)
1996
1996
1997 return repo
1997 return repo
1998
1998
1999 def __json__(self):
1999 def __json__(self):
2000 return {'landing_rev': self.landing_rev}
2000 return {'landing_rev': self.landing_rev}
2001
2001
2002 def get_dict(self):
2002 def get_dict(self):
2003
2003
2004 # Since we transformed `repo_name` to a hybrid property, we need to
2004 # Since we transformed `repo_name` to a hybrid property, we need to
2005 # keep compatibility with the code which uses `repo_name` field.
2005 # keep compatibility with the code which uses `repo_name` field.
2006
2006
2007 result = super(Repository, self).get_dict()
2007 result = super(Repository, self).get_dict()
2008 result['repo_name'] = result.pop('_repo_name', None)
2008 result['repo_name'] = result.pop('_repo_name', None)
2009 return result
2009 return result
2010
2010
2011
2011
2012 class RepoGroup(Base, BaseModel):
2012 class RepoGroup(Base, BaseModel):
2013 __tablename__ = 'groups'
2013 __tablename__ = 'groups'
2014 __table_args__ = (
2014 __table_args__ = (
2015 UniqueConstraint('group_name', 'group_parent_id'),
2015 UniqueConstraint('group_name', 'group_parent_id'),
2016 CheckConstraint('group_id != group_parent_id'),
2016 CheckConstraint('group_id != group_parent_id'),
2017 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2017 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2018 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2018 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2019 )
2019 )
2020 __mapper_args__ = {'order_by': 'group_name'}
2020 __mapper_args__ = {'order_by': 'group_name'}
2021
2021
2022 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2022 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2023
2023
2024 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2024 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2025 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2025 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2026 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2026 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2027 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2027 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2028 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2028 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2029 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2029 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2030 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2030 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2031 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2031 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2032
2032
2033 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2033 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2034 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2034 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2035 parent_group = relationship('RepoGroup', remote_side=group_id)
2035 parent_group = relationship('RepoGroup', remote_side=group_id)
2036 user = relationship('User')
2036 user = relationship('User')
2037 integrations = relationship('Integration',
2037 integrations = relationship('Integration',
2038 cascade="all, delete, delete-orphan")
2038 cascade="all, delete, delete-orphan")
2039
2039
2040 def __init__(self, group_name='', parent_group=None):
2040 def __init__(self, group_name='', parent_group=None):
2041 self.group_name = group_name
2041 self.group_name = group_name
2042 self.parent_group = parent_group
2042 self.parent_group = parent_group
2043
2043
2044 def __unicode__(self):
2044 def __unicode__(self):
2045 return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
2045 return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
2046 self.group_name)
2046 self.group_name)
2047
2047
2048 @classmethod
2048 @classmethod
2049 def _generate_choice(cls, repo_group):
2049 def _generate_choice(cls, repo_group):
2050 from webhelpers.html import literal as _literal
2050 from webhelpers.html import literal as _literal
2051 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2051 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2052 return repo_group.group_id, _name(repo_group.full_path_splitted)
2052 return repo_group.group_id, _name(repo_group.full_path_splitted)
2053
2053
2054 @classmethod
2054 @classmethod
2055 def groups_choices(cls, groups=None, show_empty_group=True):
2055 def groups_choices(cls, groups=None, show_empty_group=True):
2056 if not groups:
2056 if not groups:
2057 groups = cls.query().all()
2057 groups = cls.query().all()
2058
2058
2059 repo_groups = []
2059 repo_groups = []
2060 if show_empty_group:
2060 if show_empty_group:
2061 repo_groups = [('-1', u'-- %s --' % _('No parent'))]
2061 repo_groups = [('-1', u'-- %s --' % _('No parent'))]
2062
2062
2063 repo_groups.extend([cls._generate_choice(x) for x in groups])
2063 repo_groups.extend([cls._generate_choice(x) for x in groups])
2064
2064
2065 repo_groups = sorted(
2065 repo_groups = sorted(
2066 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2066 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2067 return repo_groups
2067 return repo_groups
2068
2068
2069 @classmethod
2069 @classmethod
2070 def url_sep(cls):
2070 def url_sep(cls):
2071 return URL_SEP
2071 return URL_SEP
2072
2072
2073 @classmethod
2073 @classmethod
2074 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2074 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2075 if case_insensitive:
2075 if case_insensitive:
2076 gr = cls.query().filter(func.lower(cls.group_name)
2076 gr = cls.query().filter(func.lower(cls.group_name)
2077 == func.lower(group_name))
2077 == func.lower(group_name))
2078 else:
2078 else:
2079 gr = cls.query().filter(cls.group_name == group_name)
2079 gr = cls.query().filter(cls.group_name == group_name)
2080 if cache:
2080 if cache:
2081 gr = gr.options(FromCache(
2081 gr = gr.options(FromCache(
2082 "sql_cache_short",
2082 "sql_cache_short",
2083 "get_group_%s" % _hash_key(group_name)))
2083 "get_group_%s" % _hash_key(group_name)))
2084 return gr.scalar()
2084 return gr.scalar()
2085
2085
2086 @classmethod
2086 @classmethod
2087 def get_user_personal_repo_group(cls, user_id):
2087 def get_user_personal_repo_group(cls, user_id):
2088 user = User.get(user_id)
2088 user = User.get(user_id)
2089 return cls.query()\
2089 return cls.query()\
2090 .filter(cls.personal == true())\
2090 .filter(cls.personal == true())\
2091 .filter(cls.user == user).scalar()
2091 .filter(cls.user == user).scalar()
2092
2092
2093 @classmethod
2093 @classmethod
2094 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2094 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2095 case_insensitive=True):
2095 case_insensitive=True):
2096 q = RepoGroup.query()
2096 q = RepoGroup.query()
2097
2097
2098 if not isinstance(user_id, Optional):
2098 if not isinstance(user_id, Optional):
2099 q = q.filter(RepoGroup.user_id == user_id)
2099 q = q.filter(RepoGroup.user_id == user_id)
2100
2100
2101 if not isinstance(group_id, Optional):
2101 if not isinstance(group_id, Optional):
2102 q = q.filter(RepoGroup.group_parent_id == group_id)
2102 q = q.filter(RepoGroup.group_parent_id == group_id)
2103
2103
2104 if case_insensitive:
2104 if case_insensitive:
2105 q = q.order_by(func.lower(RepoGroup.group_name))
2105 q = q.order_by(func.lower(RepoGroup.group_name))
2106 else:
2106 else:
2107 q = q.order_by(RepoGroup.group_name)
2107 q = q.order_by(RepoGroup.group_name)
2108 return q.all()
2108 return q.all()
2109
2109
2110 @property
2110 @property
2111 def parents(self):
2111 def parents(self):
2112 parents_recursion_limit = 10
2112 parents_recursion_limit = 10
2113 groups = []
2113 groups = []
2114 if self.parent_group is None:
2114 if self.parent_group is None:
2115 return groups
2115 return groups
2116 cur_gr = self.parent_group
2116 cur_gr = self.parent_group
2117 groups.insert(0, cur_gr)
2117 groups.insert(0, cur_gr)
2118 cnt = 0
2118 cnt = 0
2119 while 1:
2119 while 1:
2120 cnt += 1
2120 cnt += 1
2121 gr = getattr(cur_gr, 'parent_group', None)
2121 gr = getattr(cur_gr, 'parent_group', None)
2122 cur_gr = cur_gr.parent_group
2122 cur_gr = cur_gr.parent_group
2123 if gr is None:
2123 if gr is None:
2124 break
2124 break
2125 if cnt == parents_recursion_limit:
2125 if cnt == parents_recursion_limit:
2126 # this will prevent accidental infinit loops
2126 # this will prevent accidental infinit loops
2127 log.error(('more than %s parents found for group %s, stopping '
2127 log.error(('more than %s parents found for group %s, stopping '
2128 'recursive parent fetching' % (parents_recursion_limit, self)))
2128 'recursive parent fetching' % (parents_recursion_limit, self)))
2129 break
2129 break
2130
2130
2131 groups.insert(0, gr)
2131 groups.insert(0, gr)
2132 return groups
2132 return groups
2133
2133
2134 @property
2134 @property
2135 def children(self):
2135 def children(self):
2136 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2136 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2137
2137
2138 @property
2138 @property
2139 def name(self):
2139 def name(self):
2140 return self.group_name.split(RepoGroup.url_sep())[-1]
2140 return self.group_name.split(RepoGroup.url_sep())[-1]
2141
2141
2142 @property
2142 @property
2143 def full_path(self):
2143 def full_path(self):
2144 return self.group_name
2144 return self.group_name
2145
2145
2146 @property
2146 @property
2147 def full_path_splitted(self):
2147 def full_path_splitted(self):
2148 return self.group_name.split(RepoGroup.url_sep())
2148 return self.group_name.split(RepoGroup.url_sep())
2149
2149
2150 @property
2150 @property
2151 def repositories(self):
2151 def repositories(self):
2152 return Repository.query()\
2152 return Repository.query()\
2153 .filter(Repository.group == self)\
2153 .filter(Repository.group == self)\
2154 .order_by(Repository.repo_name)
2154 .order_by(Repository.repo_name)
2155
2155
2156 @property
2156 @property
2157 def repositories_recursive_count(self):
2157 def repositories_recursive_count(self):
2158 cnt = self.repositories.count()
2158 cnt = self.repositories.count()
2159
2159
2160 def children_count(group):
2160 def children_count(group):
2161 cnt = 0
2161 cnt = 0
2162 for child in group.children:
2162 for child in group.children:
2163 cnt += child.repositories.count()
2163 cnt += child.repositories.count()
2164 cnt += children_count(child)
2164 cnt += children_count(child)
2165 return cnt
2165 return cnt
2166
2166
2167 return cnt + children_count(self)
2167 return cnt + children_count(self)
2168
2168
2169 def _recursive_objects(self, include_repos=True):
2169 def _recursive_objects(self, include_repos=True):
2170 all_ = []
2170 all_ = []
2171
2171
2172 def _get_members(root_gr):
2172 def _get_members(root_gr):
2173 if include_repos:
2173 if include_repos:
2174 for r in root_gr.repositories:
2174 for r in root_gr.repositories:
2175 all_.append(r)
2175 all_.append(r)
2176 childs = root_gr.children.all()
2176 childs = root_gr.children.all()
2177 if childs:
2177 if childs:
2178 for gr in childs:
2178 for gr in childs:
2179 all_.append(gr)
2179 all_.append(gr)
2180 _get_members(gr)
2180 _get_members(gr)
2181
2181
2182 _get_members(self)
2182 _get_members(self)
2183 return [self] + all_
2183 return [self] + all_
2184
2184
2185 def recursive_groups_and_repos(self):
2185 def recursive_groups_and_repos(self):
2186 """
2186 """
2187 Recursive return all groups, with repositories in those groups
2187 Recursive return all groups, with repositories in those groups
2188 """
2188 """
2189 return self._recursive_objects()
2189 return self._recursive_objects()
2190
2190
2191 def recursive_groups(self):
2191 def recursive_groups(self):
2192 """
2192 """
2193 Returns all children groups for this group including children of children
2193 Returns all children groups for this group including children of children
2194 """
2194 """
2195 return self._recursive_objects(include_repos=False)
2195 return self._recursive_objects(include_repos=False)
2196
2196
2197 def get_new_name(self, group_name):
2197 def get_new_name(self, group_name):
2198 """
2198 """
2199 returns new full group name based on parent and new name
2199 returns new full group name based on parent and new name
2200
2200
2201 :param group_name:
2201 :param group_name:
2202 """
2202 """
2203 path_prefix = (self.parent_group.full_path_splitted if
2203 path_prefix = (self.parent_group.full_path_splitted if
2204 self.parent_group else [])
2204 self.parent_group else [])
2205 return RepoGroup.url_sep().join(path_prefix + [group_name])
2205 return RepoGroup.url_sep().join(path_prefix + [group_name])
2206
2206
2207 def permissions(self, with_admins=True, with_owner=True):
2207 def permissions(self, with_admins=True, with_owner=True):
2208 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2208 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2209 q = q.options(joinedload(UserRepoGroupToPerm.group),
2209 q = q.options(joinedload(UserRepoGroupToPerm.group),
2210 joinedload(UserRepoGroupToPerm.user),
2210 joinedload(UserRepoGroupToPerm.user),
2211 joinedload(UserRepoGroupToPerm.permission),)
2211 joinedload(UserRepoGroupToPerm.permission),)
2212
2212
2213 # get owners and admins and permissions. We do a trick of re-writing
2213 # get owners and admins and permissions. We do a trick of re-writing
2214 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2214 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2215 # has a global reference and changing one object propagates to all
2215 # has a global reference and changing one object propagates to all
2216 # others. This means if admin is also an owner admin_row that change
2216 # others. This means if admin is also an owner admin_row that change
2217 # would propagate to both objects
2217 # would propagate to both objects
2218 perm_rows = []
2218 perm_rows = []
2219 for _usr in q.all():
2219 for _usr in q.all():
2220 usr = AttributeDict(_usr.user.get_dict())
2220 usr = AttributeDict(_usr.user.get_dict())
2221 usr.permission = _usr.permission.permission_name
2221 usr.permission = _usr.permission.permission_name
2222 perm_rows.append(usr)
2222 perm_rows.append(usr)
2223
2223
2224 # filter the perm rows by 'default' first and then sort them by
2224 # filter the perm rows by 'default' first and then sort them by
2225 # admin,write,read,none permissions sorted again alphabetically in
2225 # admin,write,read,none permissions sorted again alphabetically in
2226 # each group
2226 # each group
2227 perm_rows = sorted(perm_rows, key=display_sort)
2227 perm_rows = sorted(perm_rows, key=display_sort)
2228
2228
2229 _admin_perm = 'group.admin'
2229 _admin_perm = 'group.admin'
2230 owner_row = []
2230 owner_row = []
2231 if with_owner:
2231 if with_owner:
2232 usr = AttributeDict(self.user.get_dict())
2232 usr = AttributeDict(self.user.get_dict())
2233 usr.owner_row = True
2233 usr.owner_row = True
2234 usr.permission = _admin_perm
2234 usr.permission = _admin_perm
2235 owner_row.append(usr)
2235 owner_row.append(usr)
2236
2236
2237 super_admin_rows = []
2237 super_admin_rows = []
2238 if with_admins:
2238 if with_admins:
2239 for usr in User.get_all_super_admins():
2239 for usr in User.get_all_super_admins():
2240 # if this admin is also owner, don't double the record
2240 # if this admin is also owner, don't double the record
2241 if usr.user_id == owner_row[0].user_id:
2241 if usr.user_id == owner_row[0].user_id:
2242 owner_row[0].admin_row = True
2242 owner_row[0].admin_row = True
2243 else:
2243 else:
2244 usr = AttributeDict(usr.get_dict())
2244 usr = AttributeDict(usr.get_dict())
2245 usr.admin_row = True
2245 usr.admin_row = True
2246 usr.permission = _admin_perm
2246 usr.permission = _admin_perm
2247 super_admin_rows.append(usr)
2247 super_admin_rows.append(usr)
2248
2248
2249 return super_admin_rows + owner_row + perm_rows
2249 return super_admin_rows + owner_row + perm_rows
2250
2250
2251 def permission_user_groups(self):
2251 def permission_user_groups(self):
2252 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2252 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2253 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2253 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2254 joinedload(UserGroupRepoGroupToPerm.users_group),
2254 joinedload(UserGroupRepoGroupToPerm.users_group),
2255 joinedload(UserGroupRepoGroupToPerm.permission),)
2255 joinedload(UserGroupRepoGroupToPerm.permission),)
2256
2256
2257 perm_rows = []
2257 perm_rows = []
2258 for _user_group in q.all():
2258 for _user_group in q.all():
2259 usr = AttributeDict(_user_group.users_group.get_dict())
2259 usr = AttributeDict(_user_group.users_group.get_dict())
2260 usr.permission = _user_group.permission.permission_name
2260 usr.permission = _user_group.permission.permission_name
2261 perm_rows.append(usr)
2261 perm_rows.append(usr)
2262
2262
2263 return perm_rows
2263 return perm_rows
2264
2264
2265 def get_api_data(self):
2265 def get_api_data(self):
2266 """
2266 """
2267 Common function for generating api data
2267 Common function for generating api data
2268
2268
2269 """
2269 """
2270 group = self
2270 group = self
2271 data = {
2271 data = {
2272 'group_id': group.group_id,
2272 'group_id': group.group_id,
2273 'group_name': group.group_name,
2273 'group_name': group.group_name,
2274 'group_description': group.group_description,
2274 'group_description': group.group_description,
2275 'parent_group': group.parent_group.group_name if group.parent_group else None,
2275 'parent_group': group.parent_group.group_name if group.parent_group else None,
2276 'repositories': [x.repo_name for x in group.repositories],
2276 'repositories': [x.repo_name for x in group.repositories],
2277 'owner': group.user.username,
2277 'owner': group.user.username,
2278 }
2278 }
2279 return data
2279 return data
2280
2280
2281
2281
2282 class Permission(Base, BaseModel):
2282 class Permission(Base, BaseModel):
2283 __tablename__ = 'permissions'
2283 __tablename__ = 'permissions'
2284 __table_args__ = (
2284 __table_args__ = (
2285 Index('p_perm_name_idx', 'permission_name'),
2285 Index('p_perm_name_idx', 'permission_name'),
2286 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2286 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2287 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2287 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2288 )
2288 )
2289 PERMS = [
2289 PERMS = [
2290 ('hg.admin', _('RhodeCode Super Administrator')),
2290 ('hg.admin', _('RhodeCode Super Administrator')),
2291
2291
2292 ('repository.none', _('Repository no access')),
2292 ('repository.none', _('Repository no access')),
2293 ('repository.read', _('Repository read access')),
2293 ('repository.read', _('Repository read access')),
2294 ('repository.write', _('Repository write access')),
2294 ('repository.write', _('Repository write access')),
2295 ('repository.admin', _('Repository admin access')),
2295 ('repository.admin', _('Repository admin access')),
2296
2296
2297 ('group.none', _('Repository group no access')),
2297 ('group.none', _('Repository group no access')),
2298 ('group.read', _('Repository group read access')),
2298 ('group.read', _('Repository group read access')),
2299 ('group.write', _('Repository group write access')),
2299 ('group.write', _('Repository group write access')),
2300 ('group.admin', _('Repository group admin access')),
2300 ('group.admin', _('Repository group admin access')),
2301
2301
2302 ('usergroup.none', _('User group no access')),
2302 ('usergroup.none', _('User group no access')),
2303 ('usergroup.read', _('User group read access')),
2303 ('usergroup.read', _('User group read access')),
2304 ('usergroup.write', _('User group write access')),
2304 ('usergroup.write', _('User group write access')),
2305 ('usergroup.admin', _('User group admin access')),
2305 ('usergroup.admin', _('User group admin access')),
2306
2306
2307 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2307 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2308 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2308 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2309
2309
2310 ('hg.usergroup.create.false', _('User Group creation disabled')),
2310 ('hg.usergroup.create.false', _('User Group creation disabled')),
2311 ('hg.usergroup.create.true', _('User Group creation enabled')),
2311 ('hg.usergroup.create.true', _('User Group creation enabled')),
2312
2312
2313 ('hg.create.none', _('Repository creation disabled')),
2313 ('hg.create.none', _('Repository creation disabled')),
2314 ('hg.create.repository', _('Repository creation enabled')),
2314 ('hg.create.repository', _('Repository creation enabled')),
2315 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2315 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2316 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2316 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2317
2317
2318 ('hg.fork.none', _('Repository forking disabled')),
2318 ('hg.fork.none', _('Repository forking disabled')),
2319 ('hg.fork.repository', _('Repository forking enabled')),
2319 ('hg.fork.repository', _('Repository forking enabled')),
2320
2320
2321 ('hg.register.none', _('Registration disabled')),
2321 ('hg.register.none', _('Registration disabled')),
2322 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2322 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2323 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2323 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2324
2324
2325 ('hg.password_reset.enabled', _('Password reset enabled')),
2325 ('hg.password_reset.enabled', _('Password reset enabled')),
2326 ('hg.password_reset.hidden', _('Password reset hidden')),
2326 ('hg.password_reset.hidden', _('Password reset hidden')),
2327 ('hg.password_reset.disabled', _('Password reset disabled')),
2327 ('hg.password_reset.disabled', _('Password reset disabled')),
2328
2328
2329 ('hg.extern_activate.manual', _('Manual activation of external account')),
2329 ('hg.extern_activate.manual', _('Manual activation of external account')),
2330 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2330 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2331
2331
2332 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2332 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2333 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2333 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2334 ]
2334 ]
2335
2335
2336 # definition of system default permissions for DEFAULT user
2336 # definition of system default permissions for DEFAULT user
2337 DEFAULT_USER_PERMISSIONS = [
2337 DEFAULT_USER_PERMISSIONS = [
2338 'repository.read',
2338 'repository.read',
2339 'group.read',
2339 'group.read',
2340 'usergroup.read',
2340 'usergroup.read',
2341 'hg.create.repository',
2341 'hg.create.repository',
2342 'hg.repogroup.create.false',
2342 'hg.repogroup.create.false',
2343 'hg.usergroup.create.false',
2343 'hg.usergroup.create.false',
2344 'hg.create.write_on_repogroup.true',
2344 'hg.create.write_on_repogroup.true',
2345 'hg.fork.repository',
2345 'hg.fork.repository',
2346 'hg.register.manual_activate',
2346 'hg.register.manual_activate',
2347 'hg.password_reset.enabled',
2347 'hg.password_reset.enabled',
2348 'hg.extern_activate.auto',
2348 'hg.extern_activate.auto',
2349 'hg.inherit_default_perms.true',
2349 'hg.inherit_default_perms.true',
2350 ]
2350 ]
2351
2351
2352 # defines which permissions are more important higher the more important
2352 # defines which permissions are more important higher the more important
2353 # Weight defines which permissions are more important.
2353 # Weight defines which permissions are more important.
2354 # The higher number the more important.
2354 # The higher number the more important.
2355 PERM_WEIGHTS = {
2355 PERM_WEIGHTS = {
2356 'repository.none': 0,
2356 'repository.none': 0,
2357 'repository.read': 1,
2357 'repository.read': 1,
2358 'repository.write': 3,
2358 'repository.write': 3,
2359 'repository.admin': 4,
2359 'repository.admin': 4,
2360
2360
2361 'group.none': 0,
2361 'group.none': 0,
2362 'group.read': 1,
2362 'group.read': 1,
2363 'group.write': 3,
2363 'group.write': 3,
2364 'group.admin': 4,
2364 'group.admin': 4,
2365
2365
2366 'usergroup.none': 0,
2366 'usergroup.none': 0,
2367 'usergroup.read': 1,
2367 'usergroup.read': 1,
2368 'usergroup.write': 3,
2368 'usergroup.write': 3,
2369 'usergroup.admin': 4,
2369 'usergroup.admin': 4,
2370
2370
2371 'hg.repogroup.create.false': 0,
2371 'hg.repogroup.create.false': 0,
2372 'hg.repogroup.create.true': 1,
2372 'hg.repogroup.create.true': 1,
2373
2373
2374 'hg.usergroup.create.false': 0,
2374 'hg.usergroup.create.false': 0,
2375 'hg.usergroup.create.true': 1,
2375 'hg.usergroup.create.true': 1,
2376
2376
2377 'hg.fork.none': 0,
2377 'hg.fork.none': 0,
2378 'hg.fork.repository': 1,
2378 'hg.fork.repository': 1,
2379 'hg.create.none': 0,
2379 'hg.create.none': 0,
2380 'hg.create.repository': 1
2380 'hg.create.repository': 1
2381 }
2381 }
2382
2382
2383 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2383 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2384 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2384 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2385 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2385 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2386
2386
2387 def __unicode__(self):
2387 def __unicode__(self):
2388 return u"<%s('%s:%s')>" % (
2388 return u"<%s('%s:%s')>" % (
2389 self.__class__.__name__, self.permission_id, self.permission_name
2389 self.__class__.__name__, self.permission_id, self.permission_name
2390 )
2390 )
2391
2391
2392 @classmethod
2392 @classmethod
2393 def get_by_key(cls, key):
2393 def get_by_key(cls, key):
2394 return cls.query().filter(cls.permission_name == key).scalar()
2394 return cls.query().filter(cls.permission_name == key).scalar()
2395
2395
2396 @classmethod
2396 @classmethod
2397 def get_default_repo_perms(cls, user_id, repo_id=None):
2397 def get_default_repo_perms(cls, user_id, repo_id=None):
2398 q = Session().query(UserRepoToPerm, Repository, Permission)\
2398 q = Session().query(UserRepoToPerm, Repository, Permission)\
2399 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2399 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2400 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2400 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2401 .filter(UserRepoToPerm.user_id == user_id)
2401 .filter(UserRepoToPerm.user_id == user_id)
2402 if repo_id:
2402 if repo_id:
2403 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2403 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2404 return q.all()
2404 return q.all()
2405
2405
2406 @classmethod
2406 @classmethod
2407 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2407 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2408 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2408 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2409 .join(
2409 .join(
2410 Permission,
2410 Permission,
2411 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2411 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2412 .join(
2412 .join(
2413 Repository,
2413 Repository,
2414 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2414 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2415 .join(
2415 .join(
2416 UserGroup,
2416 UserGroup,
2417 UserGroupRepoToPerm.users_group_id ==
2417 UserGroupRepoToPerm.users_group_id ==
2418 UserGroup.users_group_id)\
2418 UserGroup.users_group_id)\
2419 .join(
2419 .join(
2420 UserGroupMember,
2420 UserGroupMember,
2421 UserGroupRepoToPerm.users_group_id ==
2421 UserGroupRepoToPerm.users_group_id ==
2422 UserGroupMember.users_group_id)\
2422 UserGroupMember.users_group_id)\
2423 .filter(
2423 .filter(
2424 UserGroupMember.user_id == user_id,
2424 UserGroupMember.user_id == user_id,
2425 UserGroup.users_group_active == true())
2425 UserGroup.users_group_active == true())
2426 if repo_id:
2426 if repo_id:
2427 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2427 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2428 return q.all()
2428 return q.all()
2429
2429
2430 @classmethod
2430 @classmethod
2431 def get_default_group_perms(cls, user_id, repo_group_id=None):
2431 def get_default_group_perms(cls, user_id, repo_group_id=None):
2432 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2432 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2433 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2433 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2434 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2434 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2435 .filter(UserRepoGroupToPerm.user_id == user_id)
2435 .filter(UserRepoGroupToPerm.user_id == user_id)
2436 if repo_group_id:
2436 if repo_group_id:
2437 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2437 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2438 return q.all()
2438 return q.all()
2439
2439
2440 @classmethod
2440 @classmethod
2441 def get_default_group_perms_from_user_group(
2441 def get_default_group_perms_from_user_group(
2442 cls, user_id, repo_group_id=None):
2442 cls, user_id, repo_group_id=None):
2443 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2443 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2444 .join(
2444 .join(
2445 Permission,
2445 Permission,
2446 UserGroupRepoGroupToPerm.permission_id ==
2446 UserGroupRepoGroupToPerm.permission_id ==
2447 Permission.permission_id)\
2447 Permission.permission_id)\
2448 .join(
2448 .join(
2449 RepoGroup,
2449 RepoGroup,
2450 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2450 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2451 .join(
2451 .join(
2452 UserGroup,
2452 UserGroup,
2453 UserGroupRepoGroupToPerm.users_group_id ==
2453 UserGroupRepoGroupToPerm.users_group_id ==
2454 UserGroup.users_group_id)\
2454 UserGroup.users_group_id)\
2455 .join(
2455 .join(
2456 UserGroupMember,
2456 UserGroupMember,
2457 UserGroupRepoGroupToPerm.users_group_id ==
2457 UserGroupRepoGroupToPerm.users_group_id ==
2458 UserGroupMember.users_group_id)\
2458 UserGroupMember.users_group_id)\
2459 .filter(
2459 .filter(
2460 UserGroupMember.user_id == user_id,
2460 UserGroupMember.user_id == user_id,
2461 UserGroup.users_group_active == true())
2461 UserGroup.users_group_active == true())
2462 if repo_group_id:
2462 if repo_group_id:
2463 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2463 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2464 return q.all()
2464 return q.all()
2465
2465
2466 @classmethod
2466 @classmethod
2467 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2467 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2468 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2468 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2469 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2469 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2470 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2470 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2471 .filter(UserUserGroupToPerm.user_id == user_id)
2471 .filter(UserUserGroupToPerm.user_id == user_id)
2472 if user_group_id:
2472 if user_group_id:
2473 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2473 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2474 return q.all()
2474 return q.all()
2475
2475
2476 @classmethod
2476 @classmethod
2477 def get_default_user_group_perms_from_user_group(
2477 def get_default_user_group_perms_from_user_group(
2478 cls, user_id, user_group_id=None):
2478 cls, user_id, user_group_id=None):
2479 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2479 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2480 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2480 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2481 .join(
2481 .join(
2482 Permission,
2482 Permission,
2483 UserGroupUserGroupToPerm.permission_id ==
2483 UserGroupUserGroupToPerm.permission_id ==
2484 Permission.permission_id)\
2484 Permission.permission_id)\
2485 .join(
2485 .join(
2486 TargetUserGroup,
2486 TargetUserGroup,
2487 UserGroupUserGroupToPerm.target_user_group_id ==
2487 UserGroupUserGroupToPerm.target_user_group_id ==
2488 TargetUserGroup.users_group_id)\
2488 TargetUserGroup.users_group_id)\
2489 .join(
2489 .join(
2490 UserGroup,
2490 UserGroup,
2491 UserGroupUserGroupToPerm.user_group_id ==
2491 UserGroupUserGroupToPerm.user_group_id ==
2492 UserGroup.users_group_id)\
2492 UserGroup.users_group_id)\
2493 .join(
2493 .join(
2494 UserGroupMember,
2494 UserGroupMember,
2495 UserGroupUserGroupToPerm.user_group_id ==
2495 UserGroupUserGroupToPerm.user_group_id ==
2496 UserGroupMember.users_group_id)\
2496 UserGroupMember.users_group_id)\
2497 .filter(
2497 .filter(
2498 UserGroupMember.user_id == user_id,
2498 UserGroupMember.user_id == user_id,
2499 UserGroup.users_group_active == true())
2499 UserGroup.users_group_active == true())
2500 if user_group_id:
2500 if user_group_id:
2501 q = q.filter(
2501 q = q.filter(
2502 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2502 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2503
2503
2504 return q.all()
2504 return q.all()
2505
2505
2506
2506
2507 class UserRepoToPerm(Base, BaseModel):
2507 class UserRepoToPerm(Base, BaseModel):
2508 __tablename__ = 'repo_to_perm'
2508 __tablename__ = 'repo_to_perm'
2509 __table_args__ = (
2509 __table_args__ = (
2510 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2510 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2511 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2511 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2512 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2512 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2513 )
2513 )
2514 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2514 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2515 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2515 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2516 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2516 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2517 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2517 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2518
2518
2519 user = relationship('User')
2519 user = relationship('User')
2520 repository = relationship('Repository')
2520 repository = relationship('Repository')
2521 permission = relationship('Permission')
2521 permission = relationship('Permission')
2522
2522
2523 @classmethod
2523 @classmethod
2524 def create(cls, user, repository, permission):
2524 def create(cls, user, repository, permission):
2525 n = cls()
2525 n = cls()
2526 n.user = user
2526 n.user = user
2527 n.repository = repository
2527 n.repository = repository
2528 n.permission = permission
2528 n.permission = permission
2529 Session().add(n)
2529 Session().add(n)
2530 return n
2530 return n
2531
2531
2532 def __unicode__(self):
2532 def __unicode__(self):
2533 return u'<%s => %s >' % (self.user, self.repository)
2533 return u'<%s => %s >' % (self.user, self.repository)
2534
2534
2535
2535
2536 class UserUserGroupToPerm(Base, BaseModel):
2536 class UserUserGroupToPerm(Base, BaseModel):
2537 __tablename__ = 'user_user_group_to_perm'
2537 __tablename__ = 'user_user_group_to_perm'
2538 __table_args__ = (
2538 __table_args__ = (
2539 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2539 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2540 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2540 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2541 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2541 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2542 )
2542 )
2543 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2543 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2544 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2544 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2545 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2545 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2546 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2546 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2547
2547
2548 user = relationship('User')
2548 user = relationship('User')
2549 user_group = relationship('UserGroup')
2549 user_group = relationship('UserGroup')
2550 permission = relationship('Permission')
2550 permission = relationship('Permission')
2551
2551
2552 @classmethod
2552 @classmethod
2553 def create(cls, user, user_group, permission):
2553 def create(cls, user, user_group, permission):
2554 n = cls()
2554 n = cls()
2555 n.user = user
2555 n.user = user
2556 n.user_group = user_group
2556 n.user_group = user_group
2557 n.permission = permission
2557 n.permission = permission
2558 Session().add(n)
2558 Session().add(n)
2559 return n
2559 return n
2560
2560
2561 def __unicode__(self):
2561 def __unicode__(self):
2562 return u'<%s => %s >' % (self.user, self.user_group)
2562 return u'<%s => %s >' % (self.user, self.user_group)
2563
2563
2564
2564
2565 class UserToPerm(Base, BaseModel):
2565 class UserToPerm(Base, BaseModel):
2566 __tablename__ = 'user_to_perm'
2566 __tablename__ = 'user_to_perm'
2567 __table_args__ = (
2567 __table_args__ = (
2568 UniqueConstraint('user_id', 'permission_id'),
2568 UniqueConstraint('user_id', 'permission_id'),
2569 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2569 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2570 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2570 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2571 )
2571 )
2572 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2572 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2573 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2573 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2574 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2574 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2575
2575
2576 user = relationship('User')
2576 user = relationship('User')
2577 permission = relationship('Permission', lazy='joined')
2577 permission = relationship('Permission', lazy='joined')
2578
2578
2579 def __unicode__(self):
2579 def __unicode__(self):
2580 return u'<%s => %s >' % (self.user, self.permission)
2580 return u'<%s => %s >' % (self.user, self.permission)
2581
2581
2582
2582
2583 class UserGroupRepoToPerm(Base, BaseModel):
2583 class UserGroupRepoToPerm(Base, BaseModel):
2584 __tablename__ = 'users_group_repo_to_perm'
2584 __tablename__ = 'users_group_repo_to_perm'
2585 __table_args__ = (
2585 __table_args__ = (
2586 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2586 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2587 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2587 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2588 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2588 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2589 )
2589 )
2590 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2590 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2591 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2591 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2592 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2592 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2593 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2593 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2594
2594
2595 users_group = relationship('UserGroup')
2595 users_group = relationship('UserGroup')
2596 permission = relationship('Permission')
2596 permission = relationship('Permission')
2597 repository = relationship('Repository')
2597 repository = relationship('Repository')
2598
2598
2599 @classmethod
2599 @classmethod
2600 def create(cls, users_group, repository, permission):
2600 def create(cls, users_group, repository, permission):
2601 n = cls()
2601 n = cls()
2602 n.users_group = users_group
2602 n.users_group = users_group
2603 n.repository = repository
2603 n.repository = repository
2604 n.permission = permission
2604 n.permission = permission
2605 Session().add(n)
2605 Session().add(n)
2606 return n
2606 return n
2607
2607
2608 def __unicode__(self):
2608 def __unicode__(self):
2609 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2609 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2610
2610
2611
2611
2612 class UserGroupUserGroupToPerm(Base, BaseModel):
2612 class UserGroupUserGroupToPerm(Base, BaseModel):
2613 __tablename__ = 'user_group_user_group_to_perm'
2613 __tablename__ = 'user_group_user_group_to_perm'
2614 __table_args__ = (
2614 __table_args__ = (
2615 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2615 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2616 CheckConstraint('target_user_group_id != user_group_id'),
2616 CheckConstraint('target_user_group_id != user_group_id'),
2617 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2617 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2618 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2618 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2619 )
2619 )
2620 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)
2620 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)
2621 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2621 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2622 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2622 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2623 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2623 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2624
2624
2625 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2625 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2626 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2626 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2627 permission = relationship('Permission')
2627 permission = relationship('Permission')
2628
2628
2629 @classmethod
2629 @classmethod
2630 def create(cls, target_user_group, user_group, permission):
2630 def create(cls, target_user_group, user_group, permission):
2631 n = cls()
2631 n = cls()
2632 n.target_user_group = target_user_group
2632 n.target_user_group = target_user_group
2633 n.user_group = user_group
2633 n.user_group = user_group
2634 n.permission = permission
2634 n.permission = permission
2635 Session().add(n)
2635 Session().add(n)
2636 return n
2636 return n
2637
2637
2638 def __unicode__(self):
2638 def __unicode__(self):
2639 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2639 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2640
2640
2641
2641
2642 class UserGroupToPerm(Base, BaseModel):
2642 class UserGroupToPerm(Base, BaseModel):
2643 __tablename__ = 'users_group_to_perm'
2643 __tablename__ = 'users_group_to_perm'
2644 __table_args__ = (
2644 __table_args__ = (
2645 UniqueConstraint('users_group_id', 'permission_id',),
2645 UniqueConstraint('users_group_id', 'permission_id',),
2646 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2646 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2647 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2647 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2648 )
2648 )
2649 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2649 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2650 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2650 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2651 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2651 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2652
2652
2653 users_group = relationship('UserGroup')
2653 users_group = relationship('UserGroup')
2654 permission = relationship('Permission')
2654 permission = relationship('Permission')
2655
2655
2656
2656
2657 class UserRepoGroupToPerm(Base, BaseModel):
2657 class UserRepoGroupToPerm(Base, BaseModel):
2658 __tablename__ = 'user_repo_group_to_perm'
2658 __tablename__ = 'user_repo_group_to_perm'
2659 __table_args__ = (
2659 __table_args__ = (
2660 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2660 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2661 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2661 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2662 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2662 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2663 )
2663 )
2664
2664
2665 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2665 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2666 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2666 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2667 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2667 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2668 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2668 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2669
2669
2670 user = relationship('User')
2670 user = relationship('User')
2671 group = relationship('RepoGroup')
2671 group = relationship('RepoGroup')
2672 permission = relationship('Permission')
2672 permission = relationship('Permission')
2673
2673
2674 @classmethod
2674 @classmethod
2675 def create(cls, user, repository_group, permission):
2675 def create(cls, user, repository_group, permission):
2676 n = cls()
2676 n = cls()
2677 n.user = user
2677 n.user = user
2678 n.group = repository_group
2678 n.group = repository_group
2679 n.permission = permission
2679 n.permission = permission
2680 Session().add(n)
2680 Session().add(n)
2681 return n
2681 return n
2682
2682
2683
2683
2684 class UserGroupRepoGroupToPerm(Base, BaseModel):
2684 class UserGroupRepoGroupToPerm(Base, BaseModel):
2685 __tablename__ = 'users_group_repo_group_to_perm'
2685 __tablename__ = 'users_group_repo_group_to_perm'
2686 __table_args__ = (
2686 __table_args__ = (
2687 UniqueConstraint('users_group_id', 'group_id'),
2687 UniqueConstraint('users_group_id', 'group_id'),
2688 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2688 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2689 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2689 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2690 )
2690 )
2691
2691
2692 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)
2692 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)
2693 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2693 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2694 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2694 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2695 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2695 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2696
2696
2697 users_group = relationship('UserGroup')
2697 users_group = relationship('UserGroup')
2698 permission = relationship('Permission')
2698 permission = relationship('Permission')
2699 group = relationship('RepoGroup')
2699 group = relationship('RepoGroup')
2700
2700
2701 @classmethod
2701 @classmethod
2702 def create(cls, user_group, repository_group, permission):
2702 def create(cls, user_group, repository_group, permission):
2703 n = cls()
2703 n = cls()
2704 n.users_group = user_group
2704 n.users_group = user_group
2705 n.group = repository_group
2705 n.group = repository_group
2706 n.permission = permission
2706 n.permission = permission
2707 Session().add(n)
2707 Session().add(n)
2708 return n
2708 return n
2709
2709
2710 def __unicode__(self):
2710 def __unicode__(self):
2711 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
2711 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
2712
2712
2713
2713
2714 class Statistics(Base, BaseModel):
2714 class Statistics(Base, BaseModel):
2715 __tablename__ = 'statistics'
2715 __tablename__ = 'statistics'
2716 __table_args__ = (
2716 __table_args__ = (
2717 UniqueConstraint('repository_id'),
2717 UniqueConstraint('repository_id'),
2718 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2718 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2719 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2719 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2720 )
2720 )
2721 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2721 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2722 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
2722 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
2723 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
2723 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
2724 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
2724 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
2725 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
2725 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
2726 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
2726 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
2727
2727
2728 repository = relationship('Repository', single_parent=True)
2728 repository = relationship('Repository', single_parent=True)
2729
2729
2730
2730
2731 class UserFollowing(Base, BaseModel):
2731 class UserFollowing(Base, BaseModel):
2732 __tablename__ = 'user_followings'
2732 __tablename__ = 'user_followings'
2733 __table_args__ = (
2733 __table_args__ = (
2734 UniqueConstraint('user_id', 'follows_repository_id'),
2734 UniqueConstraint('user_id', 'follows_repository_id'),
2735 UniqueConstraint('user_id', 'follows_user_id'),
2735 UniqueConstraint('user_id', 'follows_user_id'),
2736 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2736 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2737 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2737 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2738 )
2738 )
2739
2739
2740 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2740 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2741 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2741 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2742 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
2742 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
2743 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
2743 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
2744 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2744 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2745
2745
2746 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
2746 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
2747
2747
2748 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
2748 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
2749 follows_repository = relationship('Repository', order_by='Repository.repo_name')
2749 follows_repository = relationship('Repository', order_by='Repository.repo_name')
2750
2750
2751 @classmethod
2751 @classmethod
2752 def get_repo_followers(cls, repo_id):
2752 def get_repo_followers(cls, repo_id):
2753 return cls.query().filter(cls.follows_repo_id == repo_id)
2753 return cls.query().filter(cls.follows_repo_id == repo_id)
2754
2754
2755
2755
2756 class CacheKey(Base, BaseModel):
2756 class CacheKey(Base, BaseModel):
2757 __tablename__ = 'cache_invalidation'
2757 __tablename__ = 'cache_invalidation'
2758 __table_args__ = (
2758 __table_args__ = (
2759 UniqueConstraint('cache_key'),
2759 UniqueConstraint('cache_key'),
2760 Index('key_idx', 'cache_key'),
2760 Index('key_idx', 'cache_key'),
2761 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2761 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2762 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2762 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2763 )
2763 )
2764 CACHE_TYPE_ATOM = 'ATOM'
2764 CACHE_TYPE_ATOM = 'ATOM'
2765 CACHE_TYPE_RSS = 'RSS'
2765 CACHE_TYPE_RSS = 'RSS'
2766 CACHE_TYPE_README = 'README'
2766 CACHE_TYPE_README = 'README'
2767
2767
2768 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2768 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2769 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
2769 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
2770 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
2770 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
2771 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
2771 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
2772
2772
2773 def __init__(self, cache_key, cache_args=''):
2773 def __init__(self, cache_key, cache_args=''):
2774 self.cache_key = cache_key
2774 self.cache_key = cache_key
2775 self.cache_args = cache_args
2775 self.cache_args = cache_args
2776 self.cache_active = False
2776 self.cache_active = False
2777
2777
2778 def __unicode__(self):
2778 def __unicode__(self):
2779 return u"<%s('%s:%s[%s]')>" % (
2779 return u"<%s('%s:%s[%s]')>" % (
2780 self.__class__.__name__,
2780 self.__class__.__name__,
2781 self.cache_id, self.cache_key, self.cache_active)
2781 self.cache_id, self.cache_key, self.cache_active)
2782
2782
2783 def _cache_key_partition(self):
2783 def _cache_key_partition(self):
2784 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
2784 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
2785 return prefix, repo_name, suffix
2785 return prefix, repo_name, suffix
2786
2786
2787 def get_prefix(self):
2787 def get_prefix(self):
2788 """
2788 """
2789 Try to extract prefix from existing cache key. The key could consist
2789 Try to extract prefix from existing cache key. The key could consist
2790 of prefix, repo_name, suffix
2790 of prefix, repo_name, suffix
2791 """
2791 """
2792 # this returns prefix, repo_name, suffix
2792 # this returns prefix, repo_name, suffix
2793 return self._cache_key_partition()[0]
2793 return self._cache_key_partition()[0]
2794
2794
2795 def get_suffix(self):
2795 def get_suffix(self):
2796 """
2796 """
2797 get suffix that might have been used in _get_cache_key to
2797 get suffix that might have been used in _get_cache_key to
2798 generate self.cache_key. Only used for informational purposes
2798 generate self.cache_key. Only used for informational purposes
2799 in repo_edit.html.
2799 in repo_edit.html.
2800 """
2800 """
2801 # prefix, repo_name, suffix
2801 # prefix, repo_name, suffix
2802 return self._cache_key_partition()[2]
2802 return self._cache_key_partition()[2]
2803
2803
2804 @classmethod
2804 @classmethod
2805 def delete_all_cache(cls):
2805 def delete_all_cache(cls):
2806 """
2806 """
2807 Delete all cache keys from database.
2807 Delete all cache keys from database.
2808 Should only be run when all instances are down and all entries
2808 Should only be run when all instances are down and all entries
2809 thus stale.
2809 thus stale.
2810 """
2810 """
2811 cls.query().delete()
2811 cls.query().delete()
2812 Session().commit()
2812 Session().commit()
2813
2813
2814 @classmethod
2814 @classmethod
2815 def get_cache_key(cls, repo_name, cache_type):
2815 def get_cache_key(cls, repo_name, cache_type):
2816 """
2816 """
2817
2817
2818 Generate a cache key for this process of RhodeCode instance.
2818 Generate a cache key for this process of RhodeCode instance.
2819 Prefix most likely will be process id or maybe explicitly set
2819 Prefix most likely will be process id or maybe explicitly set
2820 instance_id from .ini file.
2820 instance_id from .ini file.
2821 """
2821 """
2822 import rhodecode
2822 import rhodecode
2823 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
2823 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
2824
2824
2825 repo_as_unicode = safe_unicode(repo_name)
2825 repo_as_unicode = safe_unicode(repo_name)
2826 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
2826 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
2827 if cache_type else repo_as_unicode
2827 if cache_type else repo_as_unicode
2828
2828
2829 return u'{}{}'.format(prefix, key)
2829 return u'{}{}'.format(prefix, key)
2830
2830
2831 @classmethod
2831 @classmethod
2832 def set_invalidate(cls, repo_name, delete=False):
2832 def set_invalidate(cls, repo_name, delete=False):
2833 """
2833 """
2834 Mark all caches of a repo as invalid in the database.
2834 Mark all caches of a repo as invalid in the database.
2835 """
2835 """
2836
2836
2837 try:
2837 try:
2838 qry = Session().query(cls).filter(cls.cache_args == repo_name)
2838 qry = Session().query(cls).filter(cls.cache_args == repo_name)
2839 if delete:
2839 if delete:
2840 log.debug('cache objects deleted for repo %s',
2840 log.debug('cache objects deleted for repo %s',
2841 safe_str(repo_name))
2841 safe_str(repo_name))
2842 qry.delete()
2842 qry.delete()
2843 else:
2843 else:
2844 log.debug('cache objects marked as invalid for repo %s',
2844 log.debug('cache objects marked as invalid for repo %s',
2845 safe_str(repo_name))
2845 safe_str(repo_name))
2846 qry.update({"cache_active": False})
2846 qry.update({"cache_active": False})
2847
2847
2848 Session().commit()
2848 Session().commit()
2849 except Exception:
2849 except Exception:
2850 log.exception(
2850 log.exception(
2851 'Cache key invalidation failed for repository %s',
2851 'Cache key invalidation failed for repository %s',
2852 safe_str(repo_name))
2852 safe_str(repo_name))
2853 Session().rollback()
2853 Session().rollback()
2854
2854
2855 @classmethod
2855 @classmethod
2856 def get_active_cache(cls, cache_key):
2856 def get_active_cache(cls, cache_key):
2857 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
2857 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
2858 if inv_obj:
2858 if inv_obj:
2859 return inv_obj
2859 return inv_obj
2860 return None
2860 return None
2861
2861
2862 @classmethod
2862 @classmethod
2863 def repo_context_cache(cls, compute_func, repo_name, cache_type,
2863 def repo_context_cache(cls, compute_func, repo_name, cache_type,
2864 thread_scoped=False):
2864 thread_scoped=False):
2865 """
2865 """
2866 @cache_region('long_term')
2866 @cache_region('long_term')
2867 def _heavy_calculation(cache_key):
2867 def _heavy_calculation(cache_key):
2868 return 'result'
2868 return 'result'
2869
2869
2870 cache_context = CacheKey.repo_context_cache(
2870 cache_context = CacheKey.repo_context_cache(
2871 _heavy_calculation, repo_name, cache_type)
2871 _heavy_calculation, repo_name, cache_type)
2872
2872
2873 with cache_context as context:
2873 with cache_context as context:
2874 context.invalidate()
2874 context.invalidate()
2875 computed = context.compute()
2875 computed = context.compute()
2876
2876
2877 assert computed == 'result'
2877 assert computed == 'result'
2878 """
2878 """
2879 from rhodecode.lib import caches
2879 from rhodecode.lib import caches
2880 return caches.InvalidationContext(
2880 return caches.InvalidationContext(
2881 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
2881 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
2882
2882
2883
2883
2884 class ChangesetComment(Base, BaseModel):
2884 class ChangesetComment(Base, BaseModel):
2885 __tablename__ = 'changeset_comments'
2885 __tablename__ = 'changeset_comments'
2886 __table_args__ = (
2886 __table_args__ = (
2887 Index('cc_revision_idx', 'revision'),
2887 Index('cc_revision_idx', 'revision'),
2888 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2888 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2889 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2889 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2890 )
2890 )
2891
2891
2892 COMMENT_OUTDATED = u'comment_outdated'
2892 COMMENT_OUTDATED = u'comment_outdated'
2893
2893
2894 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
2894 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
2895 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
2895 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
2896 revision = Column('revision', String(40), nullable=True)
2896 revision = Column('revision', String(40), nullable=True)
2897 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
2897 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
2898 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
2898 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
2899 line_no = Column('line_no', Unicode(10), nullable=True)
2899 line_no = Column('line_no', Unicode(10), nullable=True)
2900 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
2900 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
2901 f_path = Column('f_path', Unicode(1000), nullable=True)
2901 f_path = Column('f_path', Unicode(1000), nullable=True)
2902 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
2902 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
2903 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
2903 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
2904 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2904 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2905 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2905 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2906 renderer = Column('renderer', Unicode(64), nullable=True)
2906 renderer = Column('renderer', Unicode(64), nullable=True)
2907 display_state = Column('display_state', Unicode(128), nullable=True)
2907 display_state = Column('display_state', Unicode(128), nullable=True)
2908
2908
2909 author = relationship('User', lazy='joined')
2909 author = relationship('User', lazy='joined')
2910 repo = relationship('Repository')
2910 repo = relationship('Repository')
2911 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
2911 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
2912 pull_request = relationship('PullRequest', lazy='joined')
2912 pull_request = relationship('PullRequest', lazy='joined')
2913 pull_request_version = relationship('PullRequestVersion')
2913 pull_request_version = relationship('PullRequestVersion')
2914
2914
2915 @classmethod
2915 @classmethod
2916 def get_users(cls, revision=None, pull_request_id=None):
2916 def get_users(cls, revision=None, pull_request_id=None):
2917 """
2917 """
2918 Returns user associated with this ChangesetComment. ie those
2918 Returns user associated with this ChangesetComment. ie those
2919 who actually commented
2919 who actually commented
2920
2920
2921 :param cls:
2921 :param cls:
2922 :param revision:
2922 :param revision:
2923 """
2923 """
2924 q = Session().query(User)\
2924 q = Session().query(User)\
2925 .join(ChangesetComment.author)
2925 .join(ChangesetComment.author)
2926 if revision:
2926 if revision:
2927 q = q.filter(cls.revision == revision)
2927 q = q.filter(cls.revision == revision)
2928 elif pull_request_id:
2928 elif pull_request_id:
2929 q = q.filter(cls.pull_request_id == pull_request_id)
2929 q = q.filter(cls.pull_request_id == pull_request_id)
2930 return q.all()
2930 return q.all()
2931
2931
2932 @property
2932 @property
2933 def outdated(self):
2933 def outdated(self):
2934 return self.display_state == self.COMMENT_OUTDATED
2934 return self.display_state == self.COMMENT_OUTDATED
2935
2935
2936 def outdated_at_version(self, version):
2936 def outdated_at_version(self, version):
2937 """
2937 """
2938 Checks if comment is outdated for given pull request version
2938 Checks if comment is outdated for given pull request version
2939 """
2939 """
2940 return self.outdated and self.pull_request_version_id != version
2940 return self.outdated and self.pull_request_version_id != version
2941
2941
2942 def render(self, mentions=False):
2942 def render(self, mentions=False):
2943 from rhodecode.lib import helpers as h
2943 from rhodecode.lib import helpers as h
2944 return h.render(self.text, renderer=self.renderer, mentions=mentions)
2944 return h.render(self.text, renderer=self.renderer, mentions=mentions)
2945
2945
2946 def __repr__(self):
2946 def __repr__(self):
2947 if self.comment_id:
2947 if self.comment_id:
2948 return '<DB:ChangesetComment #%s>' % self.comment_id
2948 return '<DB:ChangesetComment #%s>' % self.comment_id
2949 else:
2949 else:
2950 return '<DB:ChangesetComment at %#x>' % id(self)
2950 return '<DB:ChangesetComment at %#x>' % id(self)
2951
2951
2952
2952
2953 class ChangesetStatus(Base, BaseModel):
2953 class ChangesetStatus(Base, BaseModel):
2954 __tablename__ = 'changeset_statuses'
2954 __tablename__ = 'changeset_statuses'
2955 __table_args__ = (
2955 __table_args__ = (
2956 Index('cs_revision_idx', 'revision'),
2956 Index('cs_revision_idx', 'revision'),
2957 Index('cs_version_idx', 'version'),
2957 Index('cs_version_idx', 'version'),
2958 UniqueConstraint('repo_id', 'revision', 'version'),
2958 UniqueConstraint('repo_id', 'revision', 'version'),
2959 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2959 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2960 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2960 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2961 )
2961 )
2962 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
2962 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
2963 STATUS_APPROVED = 'approved'
2963 STATUS_APPROVED = 'approved'
2964 STATUS_REJECTED = 'rejected'
2964 STATUS_REJECTED = 'rejected'
2965 STATUS_UNDER_REVIEW = 'under_review'
2965 STATUS_UNDER_REVIEW = 'under_review'
2966
2966
2967 STATUSES = [
2967 STATUSES = [
2968 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
2968 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
2969 (STATUS_APPROVED, _("Approved")),
2969 (STATUS_APPROVED, _("Approved")),
2970 (STATUS_REJECTED, _("Rejected")),
2970 (STATUS_REJECTED, _("Rejected")),
2971 (STATUS_UNDER_REVIEW, _("Under Review")),
2971 (STATUS_UNDER_REVIEW, _("Under Review")),
2972 ]
2972 ]
2973
2973
2974 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
2974 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
2975 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
2975 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
2976 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
2976 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
2977 revision = Column('revision', String(40), nullable=False)
2977 revision = Column('revision', String(40), nullable=False)
2978 status = Column('status', String(128), nullable=False, default=DEFAULT)
2978 status = Column('status', String(128), nullable=False, default=DEFAULT)
2979 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
2979 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
2980 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
2980 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
2981 version = Column('version', Integer(), nullable=False, default=0)
2981 version = Column('version', Integer(), nullable=False, default=0)
2982 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
2982 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
2983
2983
2984 author = relationship('User', lazy='joined')
2984 author = relationship('User', lazy='joined')
2985 repo = relationship('Repository')
2985 repo = relationship('Repository')
2986 comment = relationship('ChangesetComment', lazy='joined')
2986 comment = relationship('ChangesetComment', lazy='joined')
2987 pull_request = relationship('PullRequest', lazy='joined')
2987 pull_request = relationship('PullRequest', lazy='joined')
2988
2988
2989 def __unicode__(self):
2989 def __unicode__(self):
2990 return u"<%s('%s[%s]:%s')>" % (
2990 return u"<%s('%s[%s]:%s')>" % (
2991 self.__class__.__name__,
2991 self.__class__.__name__,
2992 self.status, self.version, self.author
2992 self.status, self.version, self.author
2993 )
2993 )
2994
2994
2995 @classmethod
2995 @classmethod
2996 def get_status_lbl(cls, value):
2996 def get_status_lbl(cls, value):
2997 return dict(cls.STATUSES).get(value)
2997 return dict(cls.STATUSES).get(value)
2998
2998
2999 @property
2999 @property
3000 def status_lbl(self):
3000 def status_lbl(self):
3001 return ChangesetStatus.get_status_lbl(self.status)
3001 return ChangesetStatus.get_status_lbl(self.status)
3002
3002
3003
3003
3004 class _PullRequestBase(BaseModel):
3004 class _PullRequestBase(BaseModel):
3005 """
3005 """
3006 Common attributes of pull request and version entries.
3006 Common attributes of pull request and version entries.
3007 """
3007 """
3008
3008
3009 # .status values
3009 # .status values
3010 STATUS_NEW = u'new'
3010 STATUS_NEW = u'new'
3011 STATUS_OPEN = u'open'
3011 STATUS_OPEN = u'open'
3012 STATUS_CLOSED = u'closed'
3012 STATUS_CLOSED = u'closed'
3013
3013
3014 title = Column('title', Unicode(255), nullable=True)
3014 title = Column('title', Unicode(255), nullable=True)
3015 description = Column(
3015 description = Column(
3016 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3016 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3017 nullable=True)
3017 nullable=True)
3018 # new/open/closed status of pull request (not approve/reject/etc)
3018 # new/open/closed status of pull request (not approve/reject/etc)
3019 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3019 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3020 created_on = Column(
3020 created_on = Column(
3021 'created_on', DateTime(timezone=False), nullable=False,
3021 'created_on', DateTime(timezone=False), nullable=False,
3022 default=datetime.datetime.now)
3022 default=datetime.datetime.now)
3023 updated_on = Column(
3023 updated_on = Column(
3024 'updated_on', DateTime(timezone=False), nullable=False,
3024 'updated_on', DateTime(timezone=False), nullable=False,
3025 default=datetime.datetime.now)
3025 default=datetime.datetime.now)
3026
3026
3027 @declared_attr
3027 @declared_attr
3028 def user_id(cls):
3028 def user_id(cls):
3029 return Column(
3029 return Column(
3030 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3030 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3031 unique=None)
3031 unique=None)
3032
3032
3033 # 500 revisions max
3033 # 500 revisions max
3034 _revisions = Column(
3034 _revisions = Column(
3035 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3035 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3036
3036
3037 @declared_attr
3037 @declared_attr
3038 def source_repo_id(cls):
3038 def source_repo_id(cls):
3039 # TODO: dan: rename column to source_repo_id
3039 # TODO: dan: rename column to source_repo_id
3040 return Column(
3040 return Column(
3041 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3041 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3042 nullable=False)
3042 nullable=False)
3043
3043
3044 source_ref = Column('org_ref', Unicode(255), nullable=False)
3044 source_ref = Column('org_ref', Unicode(255), nullable=False)
3045
3045
3046 @declared_attr
3046 @declared_attr
3047 def target_repo_id(cls):
3047 def target_repo_id(cls):
3048 # TODO: dan: rename column to target_repo_id
3048 # TODO: dan: rename column to target_repo_id
3049 return Column(
3049 return Column(
3050 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3050 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3051 nullable=False)
3051 nullable=False)
3052
3052
3053 target_ref = Column('other_ref', Unicode(255), nullable=False)
3053 target_ref = Column('other_ref', Unicode(255), nullable=False)
3054 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3054 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3055
3055
3056 # TODO: dan: rename column to last_merge_source_rev
3056 # TODO: dan: rename column to last_merge_source_rev
3057 _last_merge_source_rev = Column(
3057 _last_merge_source_rev = Column(
3058 'last_merge_org_rev', String(40), nullable=True)
3058 'last_merge_org_rev', String(40), nullable=True)
3059 # TODO: dan: rename column to last_merge_target_rev
3059 # TODO: dan: rename column to last_merge_target_rev
3060 _last_merge_target_rev = Column(
3060 _last_merge_target_rev = Column(
3061 'last_merge_other_rev', String(40), nullable=True)
3061 'last_merge_other_rev', String(40), nullable=True)
3062 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3062 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3063 merge_rev = Column('merge_rev', String(40), nullable=True)
3063 merge_rev = Column('merge_rev', String(40), nullable=True)
3064
3064
3065 @hybrid_property
3065 @hybrid_property
3066 def revisions(self):
3066 def revisions(self):
3067 return self._revisions.split(':') if self._revisions else []
3067 return self._revisions.split(':') if self._revisions else []
3068
3068
3069 @revisions.setter
3069 @revisions.setter
3070 def revisions(self, val):
3070 def revisions(self, val):
3071 self._revisions = ':'.join(val)
3071 self._revisions = ':'.join(val)
3072
3072
3073 @declared_attr
3073 @declared_attr
3074 def author(cls):
3074 def author(cls):
3075 return relationship('User', lazy='joined')
3075 return relationship('User', lazy='joined')
3076
3076
3077 @declared_attr
3077 @declared_attr
3078 def source_repo(cls):
3078 def source_repo(cls):
3079 return relationship(
3079 return relationship(
3080 'Repository',
3080 'Repository',
3081 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3081 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3082
3082
3083 @property
3083 @property
3084 def source_ref_parts(self):
3084 def source_ref_parts(self):
3085 return self.unicode_to_reference(self.source_ref)
3085 return self.unicode_to_reference(self.source_ref)
3086
3086
3087 @declared_attr
3087 @declared_attr
3088 def target_repo(cls):
3088 def target_repo(cls):
3089 return relationship(
3089 return relationship(
3090 'Repository',
3090 'Repository',
3091 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3091 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3092
3092
3093 @property
3093 @property
3094 def target_ref_parts(self):
3094 def target_ref_parts(self):
3095 return self.unicode_to_reference(self.target_ref)
3095 return self.unicode_to_reference(self.target_ref)
3096
3096
3097 @property
3097 @property
3098 def shadow_merge_ref(self):
3098 def shadow_merge_ref(self):
3099 return self.unicode_to_reference(self._shadow_merge_ref)
3099 return self.unicode_to_reference(self._shadow_merge_ref)
3100
3100
3101 @shadow_merge_ref.setter
3101 @shadow_merge_ref.setter
3102 def shadow_merge_ref(self, ref):
3102 def shadow_merge_ref(self, ref):
3103 self._shadow_merge_ref = self.reference_to_unicode(ref)
3103 self._shadow_merge_ref = self.reference_to_unicode(ref)
3104
3104
3105 def unicode_to_reference(self, raw):
3105 def unicode_to_reference(self, raw):
3106 """
3106 """
3107 Convert a unicode (or string) to a reference object.
3107 Convert a unicode (or string) to a reference object.
3108 If unicode evaluates to False it returns None.
3108 If unicode evaluates to False it returns None.
3109 """
3109 """
3110 if raw:
3110 if raw:
3111 refs = raw.split(':')
3111 refs = raw.split(':')
3112 return Reference(*refs)
3112 return Reference(*refs)
3113 else:
3113 else:
3114 return None
3114 return None
3115
3115
3116 def reference_to_unicode(self, ref):
3116 def reference_to_unicode(self, ref):
3117 """
3117 """
3118 Convert a reference object to unicode.
3118 Convert a reference object to unicode.
3119 If reference is None it returns None.
3119 If reference is None it returns None.
3120 """
3120 """
3121 if ref:
3121 if ref:
3122 return u':'.join(ref)
3122 return u':'.join(ref)
3123 else:
3123 else:
3124 return None
3124 return None
3125
3125
3126 def get_api_data(self):
3126 def get_api_data(self):
3127 from rhodecode.model.pull_request import PullRequestModel
3127 from rhodecode.model.pull_request import PullRequestModel
3128 pull_request = self
3128 pull_request = self
3129 merge_status = PullRequestModel().merge_status(pull_request)
3129 merge_status = PullRequestModel().merge_status(pull_request)
3130
3130
3131 pull_request_url = url(
3131 pull_request_url = url(
3132 'pullrequest_show', repo_name=self.target_repo.repo_name,
3132 'pullrequest_show', repo_name=self.target_repo.repo_name,
3133 pull_request_id=self.pull_request_id, qualified=True)
3133 pull_request_id=self.pull_request_id, qualified=True)
3134
3134
3135 merge_data = {
3135 merge_data = {
3136 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3136 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3137 'reference': (
3137 'reference': (
3138 pull_request.shadow_merge_ref._asdict()
3138 pull_request.shadow_merge_ref._asdict()
3139 if pull_request.shadow_merge_ref else None),
3139 if pull_request.shadow_merge_ref else None),
3140 }
3140 }
3141
3141
3142 data = {
3142 data = {
3143 'pull_request_id': pull_request.pull_request_id,
3143 'pull_request_id': pull_request.pull_request_id,
3144 'url': pull_request_url,
3144 'url': pull_request_url,
3145 'title': pull_request.title,
3145 'title': pull_request.title,
3146 'description': pull_request.description,
3146 'description': pull_request.description,
3147 'status': pull_request.status,
3147 'status': pull_request.status,
3148 'created_on': pull_request.created_on,
3148 'created_on': pull_request.created_on,
3149 'updated_on': pull_request.updated_on,
3149 'updated_on': pull_request.updated_on,
3150 'commit_ids': pull_request.revisions,
3150 'commit_ids': pull_request.revisions,
3151 'review_status': pull_request.calculated_review_status(),
3151 'review_status': pull_request.calculated_review_status(),
3152 'mergeable': {
3152 'mergeable': {
3153 'status': merge_status[0],
3153 'status': merge_status[0],
3154 'message': unicode(merge_status[1]),
3154 'message': unicode(merge_status[1]),
3155 },
3155 },
3156 'source': {
3156 'source': {
3157 'clone_url': pull_request.source_repo.clone_url(),
3157 'clone_url': pull_request.source_repo.clone_url(),
3158 'repository': pull_request.source_repo.repo_name,
3158 'repository': pull_request.source_repo.repo_name,
3159 'reference': {
3159 'reference': {
3160 'name': pull_request.source_ref_parts.name,
3160 'name': pull_request.source_ref_parts.name,
3161 'type': pull_request.source_ref_parts.type,
3161 'type': pull_request.source_ref_parts.type,
3162 'commit_id': pull_request.source_ref_parts.commit_id,
3162 'commit_id': pull_request.source_ref_parts.commit_id,
3163 },
3163 },
3164 },
3164 },
3165 'target': {
3165 'target': {
3166 'clone_url': pull_request.target_repo.clone_url(),
3166 'clone_url': pull_request.target_repo.clone_url(),
3167 'repository': pull_request.target_repo.repo_name,
3167 'repository': pull_request.target_repo.repo_name,
3168 'reference': {
3168 'reference': {
3169 'name': pull_request.target_ref_parts.name,
3169 'name': pull_request.target_ref_parts.name,
3170 'type': pull_request.target_ref_parts.type,
3170 'type': pull_request.target_ref_parts.type,
3171 'commit_id': pull_request.target_ref_parts.commit_id,
3171 'commit_id': pull_request.target_ref_parts.commit_id,
3172 },
3172 },
3173 },
3173 },
3174 'merge': merge_data,
3174 'merge': merge_data,
3175 'author': pull_request.author.get_api_data(include_secrets=False,
3175 'author': pull_request.author.get_api_data(include_secrets=False,
3176 details='basic'),
3176 details='basic'),
3177 'reviewers': [
3177 'reviewers': [
3178 {
3178 {
3179 'user': reviewer.get_api_data(include_secrets=False,
3179 'user': reviewer.get_api_data(include_secrets=False,
3180 details='basic'),
3180 details='basic'),
3181 'reasons': reasons,
3181 'reasons': reasons,
3182 'review_status': st[0][1].status if st else 'not_reviewed',
3182 'review_status': st[0][1].status if st else 'not_reviewed',
3183 }
3183 }
3184 for reviewer, reasons, st in pull_request.reviewers_statuses()
3184 for reviewer, reasons, st in pull_request.reviewers_statuses()
3185 ]
3185 ]
3186 }
3186 }
3187
3187
3188 return data
3188 return data
3189
3189
3190
3190
3191 class PullRequest(Base, _PullRequestBase):
3191 class PullRequest(Base, _PullRequestBase):
3192 __tablename__ = 'pull_requests'
3192 __tablename__ = 'pull_requests'
3193 __table_args__ = (
3193 __table_args__ = (
3194 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3194 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3195 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3195 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3196 )
3196 )
3197
3197
3198 pull_request_id = Column(
3198 pull_request_id = Column(
3199 'pull_request_id', Integer(), nullable=False, primary_key=True)
3199 'pull_request_id', Integer(), nullable=False, primary_key=True)
3200
3200
3201 def __repr__(self):
3201 def __repr__(self):
3202 if self.pull_request_id:
3202 if self.pull_request_id:
3203 return '<DB:PullRequest #%s>' % self.pull_request_id
3203 return '<DB:PullRequest #%s>' % self.pull_request_id
3204 else:
3204 else:
3205 return '<DB:PullRequest at %#x>' % id(self)
3205 return '<DB:PullRequest at %#x>' % id(self)
3206
3206
3207 reviewers = relationship('PullRequestReviewers',
3207 reviewers = relationship('PullRequestReviewers',
3208 cascade="all, delete, delete-orphan")
3208 cascade="all, delete, delete-orphan")
3209 statuses = relationship('ChangesetStatus')
3209 statuses = relationship('ChangesetStatus')
3210 comments = relationship('ChangesetComment',
3210 comments = relationship('ChangesetComment',
3211 cascade="all, delete, delete-orphan")
3211 cascade="all, delete, delete-orphan")
3212 versions = relationship('PullRequestVersion',
3212 versions = relationship('PullRequestVersion',
3213 cascade="all, delete, delete-orphan",
3213 cascade="all, delete, delete-orphan",
3214 lazy='dynamic')
3214 lazy='dynamic')
3215
3215
3216
3217 @classmethod
3218 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3219 internal_methods=None):
3220
3221 class PullRequestDisplay(object):
3222 """
3223 Special object wrapper for showing PullRequest data via Versions
3224 It mimics PR object as close as possible. This is read only object
3225 just for display
3226 """
3227
3228 def __init__(self, attrs, internal=None):
3229 self.attrs = attrs
3230 # internal have priority over the given ones via attrs
3231 self.internal = internal or ['versions']
3232
3233 def __getattr__(self, item):
3234 if item in self.internal:
3235 return getattr(self, item)
3236 try:
3237 return self.attrs[item]
3238 except KeyError:
3239 raise AttributeError(
3240 '%s object has no attribute %s' % (self, item))
3241
3242 def __repr__(self):
3243 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3244
3245 def versions(self):
3246 return pull_request_obj.versions.order_by(
3247 PullRequestVersion.pull_request_version_id).all()
3248
3249 def is_closed(self):
3250 return pull_request_obj.is_closed()
3251
3252 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3253
3254 attrs.author = StrictAttributeDict(
3255 pull_request_obj.author.get_api_data())
3256 if pull_request_obj.target_repo:
3257 attrs.target_repo = StrictAttributeDict(
3258 pull_request_obj.target_repo.get_api_data())
3259 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3260
3261 if pull_request_obj.source_repo:
3262 attrs.source_repo = StrictAttributeDict(
3263 pull_request_obj.source_repo.get_api_data())
3264 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3265
3266 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3267 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3268 attrs.revisions = pull_request_obj.revisions
3269
3270 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3271
3272 return PullRequestDisplay(attrs, internal=internal_methods)
3273
3216 def is_closed(self):
3274 def is_closed(self):
3217 return self.status == self.STATUS_CLOSED
3275 return self.status == self.STATUS_CLOSED
3218
3276
3219 def __json__(self):
3277 def __json__(self):
3220 return {
3278 return {
3221 'revisions': self.revisions,
3279 'revisions': self.revisions,
3222 }
3280 }
3223
3281
3224 def calculated_review_status(self):
3282 def calculated_review_status(self):
3225 from rhodecode.model.changeset_status import ChangesetStatusModel
3283 from rhodecode.model.changeset_status import ChangesetStatusModel
3226 return ChangesetStatusModel().calculated_review_status(self)
3284 return ChangesetStatusModel().calculated_review_status(self)
3227
3285
3228 def reviewers_statuses(self):
3286 def reviewers_statuses(self):
3229 from rhodecode.model.changeset_status import ChangesetStatusModel
3287 from rhodecode.model.changeset_status import ChangesetStatusModel
3230 return ChangesetStatusModel().reviewers_statuses(self)
3288 return ChangesetStatusModel().reviewers_statuses(self)
3231
3289
3232
3290
3233 class PullRequestVersion(Base, _PullRequestBase):
3291 class PullRequestVersion(Base, _PullRequestBase):
3234 __tablename__ = 'pull_request_versions'
3292 __tablename__ = 'pull_request_versions'
3235 __table_args__ = (
3293 __table_args__ = (
3236 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3294 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3237 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3295 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3238 )
3296 )
3239
3297
3240 pull_request_version_id = Column(
3298 pull_request_version_id = Column(
3241 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3299 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3242 pull_request_id = Column(
3300 pull_request_id = Column(
3243 'pull_request_id', Integer(),
3301 'pull_request_id', Integer(),
3244 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3302 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3245 pull_request = relationship('PullRequest')
3303 pull_request = relationship('PullRequest')
3246
3304
3247 def __repr__(self):
3305 def __repr__(self):
3248 if self.pull_request_version_id:
3306 if self.pull_request_version_id:
3249 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3307 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3250 else:
3308 else:
3251 return '<DB:PullRequestVersion at %#x>' % id(self)
3309 return '<DB:PullRequestVersion at %#x>' % id(self)
3252
3310
3253 @property
3311 @property
3254 def reviewers(self):
3312 def reviewers(self):
3255 return self.pull_request.reviewers
3313 return self.pull_request.reviewers
3256
3314
3257 @property
3315 @property
3258 def versions(self):
3316 def versions(self):
3259 return self.pull_request.versions
3317 return self.pull_request.versions
3260
3318
3261 def is_closed(self):
3319 def is_closed(self):
3262 # calculate from original
3320 # calculate from original
3263 return self.pull_request.status == self.STATUS_CLOSED
3321 return self.pull_request.status == self.STATUS_CLOSED
3264
3322
3265 def calculated_review_status(self):
3323 def calculated_review_status(self):
3266 return self.pull_request.calculated_review_status()
3324 return self.pull_request.calculated_review_status()
3267
3325
3268 def reviewers_statuses(self):
3326 def reviewers_statuses(self):
3269 return self.pull_request.reviewers_statuses()
3327 return self.pull_request.reviewers_statuses()
3270
3328
3271
3329
3272 class PullRequestReviewers(Base, BaseModel):
3330 class PullRequestReviewers(Base, BaseModel):
3273 __tablename__ = 'pull_request_reviewers'
3331 __tablename__ = 'pull_request_reviewers'
3274 __table_args__ = (
3332 __table_args__ = (
3275 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3333 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3276 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3334 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3277 )
3335 )
3278
3336
3279 def __init__(self, user=None, pull_request=None, reasons=None):
3337 def __init__(self, user=None, pull_request=None, reasons=None):
3280 self.user = user
3338 self.user = user
3281 self.pull_request = pull_request
3339 self.pull_request = pull_request
3282 self.reasons = reasons or []
3340 self.reasons = reasons or []
3283
3341
3284 @hybrid_property
3342 @hybrid_property
3285 def reasons(self):
3343 def reasons(self):
3286 if not self._reasons:
3344 if not self._reasons:
3287 return []
3345 return []
3288 return self._reasons
3346 return self._reasons
3289
3347
3290 @reasons.setter
3348 @reasons.setter
3291 def reasons(self, val):
3349 def reasons(self, val):
3292 val = val or []
3350 val = val or []
3293 if any(not isinstance(x, basestring) for x in val):
3351 if any(not isinstance(x, basestring) for x in val):
3294 raise Exception('invalid reasons type, must be list of strings')
3352 raise Exception('invalid reasons type, must be list of strings')
3295 self._reasons = val
3353 self._reasons = val
3296
3354
3297 pull_requests_reviewers_id = Column(
3355 pull_requests_reviewers_id = Column(
3298 'pull_requests_reviewers_id', Integer(), nullable=False,
3356 'pull_requests_reviewers_id', Integer(), nullable=False,
3299 primary_key=True)
3357 primary_key=True)
3300 pull_request_id = Column(
3358 pull_request_id = Column(
3301 "pull_request_id", Integer(),
3359 "pull_request_id", Integer(),
3302 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3360 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3303 user_id = Column(
3361 user_id = Column(
3304 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3362 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3305 _reasons = Column(
3363 _reasons = Column(
3306 'reason', MutationList.as_mutable(
3364 'reason', MutationList.as_mutable(
3307 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3365 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3308
3366
3309 user = relationship('User')
3367 user = relationship('User')
3310 pull_request = relationship('PullRequest')
3368 pull_request = relationship('PullRequest')
3311
3369
3312
3370
3313 class Notification(Base, BaseModel):
3371 class Notification(Base, BaseModel):
3314 __tablename__ = 'notifications'
3372 __tablename__ = 'notifications'
3315 __table_args__ = (
3373 __table_args__ = (
3316 Index('notification_type_idx', 'type'),
3374 Index('notification_type_idx', 'type'),
3317 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3375 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3318 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3376 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3319 )
3377 )
3320
3378
3321 TYPE_CHANGESET_COMMENT = u'cs_comment'
3379 TYPE_CHANGESET_COMMENT = u'cs_comment'
3322 TYPE_MESSAGE = u'message'
3380 TYPE_MESSAGE = u'message'
3323 TYPE_MENTION = u'mention'
3381 TYPE_MENTION = u'mention'
3324 TYPE_REGISTRATION = u'registration'
3382 TYPE_REGISTRATION = u'registration'
3325 TYPE_PULL_REQUEST = u'pull_request'
3383 TYPE_PULL_REQUEST = u'pull_request'
3326 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3384 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3327
3385
3328 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3386 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3329 subject = Column('subject', Unicode(512), nullable=True)
3387 subject = Column('subject', Unicode(512), nullable=True)
3330 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3388 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3331 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3389 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3332 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3390 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3333 type_ = Column('type', Unicode(255))
3391 type_ = Column('type', Unicode(255))
3334
3392
3335 created_by_user = relationship('User')
3393 created_by_user = relationship('User')
3336 notifications_to_users = relationship('UserNotification', lazy='joined',
3394 notifications_to_users = relationship('UserNotification', lazy='joined',
3337 cascade="all, delete, delete-orphan")
3395 cascade="all, delete, delete-orphan")
3338
3396
3339 @property
3397 @property
3340 def recipients(self):
3398 def recipients(self):
3341 return [x.user for x in UserNotification.query()\
3399 return [x.user for x in UserNotification.query()\
3342 .filter(UserNotification.notification == self)\
3400 .filter(UserNotification.notification == self)\
3343 .order_by(UserNotification.user_id.asc()).all()]
3401 .order_by(UserNotification.user_id.asc()).all()]
3344
3402
3345 @classmethod
3403 @classmethod
3346 def create(cls, created_by, subject, body, recipients, type_=None):
3404 def create(cls, created_by, subject, body, recipients, type_=None):
3347 if type_ is None:
3405 if type_ is None:
3348 type_ = Notification.TYPE_MESSAGE
3406 type_ = Notification.TYPE_MESSAGE
3349
3407
3350 notification = cls()
3408 notification = cls()
3351 notification.created_by_user = created_by
3409 notification.created_by_user = created_by
3352 notification.subject = subject
3410 notification.subject = subject
3353 notification.body = body
3411 notification.body = body
3354 notification.type_ = type_
3412 notification.type_ = type_
3355 notification.created_on = datetime.datetime.now()
3413 notification.created_on = datetime.datetime.now()
3356
3414
3357 for u in recipients:
3415 for u in recipients:
3358 assoc = UserNotification()
3416 assoc = UserNotification()
3359 assoc.notification = notification
3417 assoc.notification = notification
3360
3418
3361 # if created_by is inside recipients mark his notification
3419 # if created_by is inside recipients mark his notification
3362 # as read
3420 # as read
3363 if u.user_id == created_by.user_id:
3421 if u.user_id == created_by.user_id:
3364 assoc.read = True
3422 assoc.read = True
3365
3423
3366 u.notifications.append(assoc)
3424 u.notifications.append(assoc)
3367 Session().add(notification)
3425 Session().add(notification)
3368
3426
3369 return notification
3427 return notification
3370
3428
3371 @property
3429 @property
3372 def description(self):
3430 def description(self):
3373 from rhodecode.model.notification import NotificationModel
3431 from rhodecode.model.notification import NotificationModel
3374 return NotificationModel().make_description(self)
3432 return NotificationModel().make_description(self)
3375
3433
3376
3434
3377 class UserNotification(Base, BaseModel):
3435 class UserNotification(Base, BaseModel):
3378 __tablename__ = 'user_to_notification'
3436 __tablename__ = 'user_to_notification'
3379 __table_args__ = (
3437 __table_args__ = (
3380 UniqueConstraint('user_id', 'notification_id'),
3438 UniqueConstraint('user_id', 'notification_id'),
3381 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3439 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3382 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3440 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3383 )
3441 )
3384 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3442 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3385 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3443 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3386 read = Column('read', Boolean, default=False)
3444 read = Column('read', Boolean, default=False)
3387 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3445 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3388
3446
3389 user = relationship('User', lazy="joined")
3447 user = relationship('User', lazy="joined")
3390 notification = relationship('Notification', lazy="joined",
3448 notification = relationship('Notification', lazy="joined",
3391 order_by=lambda: Notification.created_on.desc(),)
3449 order_by=lambda: Notification.created_on.desc(),)
3392
3450
3393 def mark_as_read(self):
3451 def mark_as_read(self):
3394 self.read = True
3452 self.read = True
3395 Session().add(self)
3453 Session().add(self)
3396
3454
3397
3455
3398 class Gist(Base, BaseModel):
3456 class Gist(Base, BaseModel):
3399 __tablename__ = 'gists'
3457 __tablename__ = 'gists'
3400 __table_args__ = (
3458 __table_args__ = (
3401 Index('g_gist_access_id_idx', 'gist_access_id'),
3459 Index('g_gist_access_id_idx', 'gist_access_id'),
3402 Index('g_created_on_idx', 'created_on'),
3460 Index('g_created_on_idx', 'created_on'),
3403 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3461 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3404 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3462 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3405 )
3463 )
3406 GIST_PUBLIC = u'public'
3464 GIST_PUBLIC = u'public'
3407 GIST_PRIVATE = u'private'
3465 GIST_PRIVATE = u'private'
3408 DEFAULT_FILENAME = u'gistfile1.txt'
3466 DEFAULT_FILENAME = u'gistfile1.txt'
3409
3467
3410 ACL_LEVEL_PUBLIC = u'acl_public'
3468 ACL_LEVEL_PUBLIC = u'acl_public'
3411 ACL_LEVEL_PRIVATE = u'acl_private'
3469 ACL_LEVEL_PRIVATE = u'acl_private'
3412
3470
3413 gist_id = Column('gist_id', Integer(), primary_key=True)
3471 gist_id = Column('gist_id', Integer(), primary_key=True)
3414 gist_access_id = Column('gist_access_id', Unicode(250))
3472 gist_access_id = Column('gist_access_id', Unicode(250))
3415 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3473 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3416 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3474 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3417 gist_expires = Column('gist_expires', Float(53), nullable=False)
3475 gist_expires = Column('gist_expires', Float(53), nullable=False)
3418 gist_type = Column('gist_type', Unicode(128), nullable=False)
3476 gist_type = Column('gist_type', Unicode(128), nullable=False)
3419 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3477 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3420 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3478 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3421 acl_level = Column('acl_level', Unicode(128), nullable=True)
3479 acl_level = Column('acl_level', Unicode(128), nullable=True)
3422
3480
3423 owner = relationship('User')
3481 owner = relationship('User')
3424
3482
3425 def __repr__(self):
3483 def __repr__(self):
3426 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3484 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3427
3485
3428 @classmethod
3486 @classmethod
3429 def get_or_404(cls, id_):
3487 def get_or_404(cls, id_):
3430 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3488 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3431 if not res:
3489 if not res:
3432 raise HTTPNotFound
3490 raise HTTPNotFound
3433 return res
3491 return res
3434
3492
3435 @classmethod
3493 @classmethod
3436 def get_by_access_id(cls, gist_access_id):
3494 def get_by_access_id(cls, gist_access_id):
3437 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3495 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3438
3496
3439 def gist_url(self):
3497 def gist_url(self):
3440 import rhodecode
3498 import rhodecode
3441 alias_url = rhodecode.CONFIG.get('gist_alias_url')
3499 alias_url = rhodecode.CONFIG.get('gist_alias_url')
3442 if alias_url:
3500 if alias_url:
3443 return alias_url.replace('{gistid}', self.gist_access_id)
3501 return alias_url.replace('{gistid}', self.gist_access_id)
3444
3502
3445 return url('gist', gist_id=self.gist_access_id, qualified=True)
3503 return url('gist', gist_id=self.gist_access_id, qualified=True)
3446
3504
3447 @classmethod
3505 @classmethod
3448 def base_path(cls):
3506 def base_path(cls):
3449 """
3507 """
3450 Returns base path when all gists are stored
3508 Returns base path when all gists are stored
3451
3509
3452 :param cls:
3510 :param cls:
3453 """
3511 """
3454 from rhodecode.model.gist import GIST_STORE_LOC
3512 from rhodecode.model.gist import GIST_STORE_LOC
3455 q = Session().query(RhodeCodeUi)\
3513 q = Session().query(RhodeCodeUi)\
3456 .filter(RhodeCodeUi.ui_key == URL_SEP)
3514 .filter(RhodeCodeUi.ui_key == URL_SEP)
3457 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3515 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3458 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3516 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3459
3517
3460 def get_api_data(self):
3518 def get_api_data(self):
3461 """
3519 """
3462 Common function for generating gist related data for API
3520 Common function for generating gist related data for API
3463 """
3521 """
3464 gist = self
3522 gist = self
3465 data = {
3523 data = {
3466 'gist_id': gist.gist_id,
3524 'gist_id': gist.gist_id,
3467 'type': gist.gist_type,
3525 'type': gist.gist_type,
3468 'access_id': gist.gist_access_id,
3526 'access_id': gist.gist_access_id,
3469 'description': gist.gist_description,
3527 'description': gist.gist_description,
3470 'url': gist.gist_url(),
3528 'url': gist.gist_url(),
3471 'expires': gist.gist_expires,
3529 'expires': gist.gist_expires,
3472 'created_on': gist.created_on,
3530 'created_on': gist.created_on,
3473 'modified_at': gist.modified_at,
3531 'modified_at': gist.modified_at,
3474 'content': None,
3532 'content': None,
3475 'acl_level': gist.acl_level,
3533 'acl_level': gist.acl_level,
3476 }
3534 }
3477 return data
3535 return data
3478
3536
3479 def __json__(self):
3537 def __json__(self):
3480 data = dict(
3538 data = dict(
3481 )
3539 )
3482 data.update(self.get_api_data())
3540 data.update(self.get_api_data())
3483 return data
3541 return data
3484 # SCM functions
3542 # SCM functions
3485
3543
3486 def scm_instance(self, **kwargs):
3544 def scm_instance(self, **kwargs):
3487 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3545 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3488 return get_vcs_instance(
3546 return get_vcs_instance(
3489 repo_path=safe_str(full_repo_path), create=False)
3547 repo_path=safe_str(full_repo_path), create=False)
3490
3548
3491
3549
3492 class DbMigrateVersion(Base, BaseModel):
3550 class DbMigrateVersion(Base, BaseModel):
3493 __tablename__ = 'db_migrate_version'
3551 __tablename__ = 'db_migrate_version'
3494 __table_args__ = (
3552 __table_args__ = (
3495 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3553 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3496 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3554 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3497 )
3555 )
3498 repository_id = Column('repository_id', String(250), primary_key=True)
3556 repository_id = Column('repository_id', String(250), primary_key=True)
3499 repository_path = Column('repository_path', Text)
3557 repository_path = Column('repository_path', Text)
3500 version = Column('version', Integer)
3558 version = Column('version', Integer)
3501
3559
3502
3560
3503 class ExternalIdentity(Base, BaseModel):
3561 class ExternalIdentity(Base, BaseModel):
3504 __tablename__ = 'external_identities'
3562 __tablename__ = 'external_identities'
3505 __table_args__ = (
3563 __table_args__ = (
3506 Index('local_user_id_idx', 'local_user_id'),
3564 Index('local_user_id_idx', 'local_user_id'),
3507 Index('external_id_idx', 'external_id'),
3565 Index('external_id_idx', 'external_id'),
3508 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3566 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3509 'mysql_charset': 'utf8'})
3567 'mysql_charset': 'utf8'})
3510
3568
3511 external_id = Column('external_id', Unicode(255), default=u'',
3569 external_id = Column('external_id', Unicode(255), default=u'',
3512 primary_key=True)
3570 primary_key=True)
3513 external_username = Column('external_username', Unicode(1024), default=u'')
3571 external_username = Column('external_username', Unicode(1024), default=u'')
3514 local_user_id = Column('local_user_id', Integer(),
3572 local_user_id = Column('local_user_id', Integer(),
3515 ForeignKey('users.user_id'), primary_key=True)
3573 ForeignKey('users.user_id'), primary_key=True)
3516 provider_name = Column('provider_name', Unicode(255), default=u'',
3574 provider_name = Column('provider_name', Unicode(255), default=u'',
3517 primary_key=True)
3575 primary_key=True)
3518 access_token = Column('access_token', String(1024), default=u'')
3576 access_token = Column('access_token', String(1024), default=u'')
3519 alt_token = Column('alt_token', String(1024), default=u'')
3577 alt_token = Column('alt_token', String(1024), default=u'')
3520 token_secret = Column('token_secret', String(1024), default=u'')
3578 token_secret = Column('token_secret', String(1024), default=u'')
3521
3579
3522 @classmethod
3580 @classmethod
3523 def by_external_id_and_provider(cls, external_id, provider_name,
3581 def by_external_id_and_provider(cls, external_id, provider_name,
3524 local_user_id=None):
3582 local_user_id=None):
3525 """
3583 """
3526 Returns ExternalIdentity instance based on search params
3584 Returns ExternalIdentity instance based on search params
3527
3585
3528 :param external_id:
3586 :param external_id:
3529 :param provider_name:
3587 :param provider_name:
3530 :return: ExternalIdentity
3588 :return: ExternalIdentity
3531 """
3589 """
3532 query = cls.query()
3590 query = cls.query()
3533 query = query.filter(cls.external_id == external_id)
3591 query = query.filter(cls.external_id == external_id)
3534 query = query.filter(cls.provider_name == provider_name)
3592 query = query.filter(cls.provider_name == provider_name)
3535 if local_user_id:
3593 if local_user_id:
3536 query = query.filter(cls.local_user_id == local_user_id)
3594 query = query.filter(cls.local_user_id == local_user_id)
3537 return query.first()
3595 return query.first()
3538
3596
3539 @classmethod
3597 @classmethod
3540 def user_by_external_id_and_provider(cls, external_id, provider_name):
3598 def user_by_external_id_and_provider(cls, external_id, provider_name):
3541 """
3599 """
3542 Returns User instance based on search params
3600 Returns User instance based on search params
3543
3601
3544 :param external_id:
3602 :param external_id:
3545 :param provider_name:
3603 :param provider_name:
3546 :return: User
3604 :return: User
3547 """
3605 """
3548 query = User.query()
3606 query = User.query()
3549 query = query.filter(cls.external_id == external_id)
3607 query = query.filter(cls.external_id == external_id)
3550 query = query.filter(cls.provider_name == provider_name)
3608 query = query.filter(cls.provider_name == provider_name)
3551 query = query.filter(User.user_id == cls.local_user_id)
3609 query = query.filter(User.user_id == cls.local_user_id)
3552 return query.first()
3610 return query.first()
3553
3611
3554 @classmethod
3612 @classmethod
3555 def by_local_user_id(cls, local_user_id):
3613 def by_local_user_id(cls, local_user_id):
3556 """
3614 """
3557 Returns all tokens for user
3615 Returns all tokens for user
3558
3616
3559 :param local_user_id:
3617 :param local_user_id:
3560 :return: ExternalIdentity
3618 :return: ExternalIdentity
3561 """
3619 """
3562 query = cls.query()
3620 query = cls.query()
3563 query = query.filter(cls.local_user_id == local_user_id)
3621 query = query.filter(cls.local_user_id == local_user_id)
3564 return query
3622 return query
3565
3623
3566
3624
3567 class Integration(Base, BaseModel):
3625 class Integration(Base, BaseModel):
3568 __tablename__ = 'integrations'
3626 __tablename__ = 'integrations'
3569 __table_args__ = (
3627 __table_args__ = (
3570 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3628 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3571 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3629 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3572 )
3630 )
3573
3631
3574 integration_id = Column('integration_id', Integer(), primary_key=True)
3632 integration_id = Column('integration_id', Integer(), primary_key=True)
3575 integration_type = Column('integration_type', String(255))
3633 integration_type = Column('integration_type', String(255))
3576 enabled = Column('enabled', Boolean(), nullable=False)
3634 enabled = Column('enabled', Boolean(), nullable=False)
3577 name = Column('name', String(255), nullable=False)
3635 name = Column('name', String(255), nullable=False)
3578 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
3636 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
3579 default=False)
3637 default=False)
3580
3638
3581 settings = Column(
3639 settings = Column(
3582 'settings_json', MutationObj.as_mutable(
3640 'settings_json', MutationObj.as_mutable(
3583 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3641 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3584 repo_id = Column(
3642 repo_id = Column(
3585 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
3643 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
3586 nullable=True, unique=None, default=None)
3644 nullable=True, unique=None, default=None)
3587 repo = relationship('Repository', lazy='joined')
3645 repo = relationship('Repository', lazy='joined')
3588
3646
3589 repo_group_id = Column(
3647 repo_group_id = Column(
3590 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
3648 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
3591 nullable=True, unique=None, default=None)
3649 nullable=True, unique=None, default=None)
3592 repo_group = relationship('RepoGroup', lazy='joined')
3650 repo_group = relationship('RepoGroup', lazy='joined')
3593
3651
3594 @property
3652 @property
3595 def scope(self):
3653 def scope(self):
3596 if self.repo:
3654 if self.repo:
3597 return repr(self.repo)
3655 return repr(self.repo)
3598 if self.repo_group:
3656 if self.repo_group:
3599 if self.child_repos_only:
3657 if self.child_repos_only:
3600 return repr(self.repo_group) + ' (child repos only)'
3658 return repr(self.repo_group) + ' (child repos only)'
3601 else:
3659 else:
3602 return repr(self.repo_group) + ' (recursive)'
3660 return repr(self.repo_group) + ' (recursive)'
3603 if self.child_repos_only:
3661 if self.child_repos_only:
3604 return 'root_repos'
3662 return 'root_repos'
3605 return 'global'
3663 return 'global'
3606
3664
3607 def __repr__(self):
3665 def __repr__(self):
3608 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
3666 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
3609
3667
3610
3668
3611 class RepoReviewRuleUser(Base, BaseModel):
3669 class RepoReviewRuleUser(Base, BaseModel):
3612 __tablename__ = 'repo_review_rules_users'
3670 __tablename__ = 'repo_review_rules_users'
3613 __table_args__ = (
3671 __table_args__ = (
3614 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3672 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3615 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3673 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3616 )
3674 )
3617 repo_review_rule_user_id = Column(
3675 repo_review_rule_user_id = Column(
3618 'repo_review_rule_user_id', Integer(), primary_key=True)
3676 'repo_review_rule_user_id', Integer(), primary_key=True)
3619 repo_review_rule_id = Column("repo_review_rule_id",
3677 repo_review_rule_id = Column("repo_review_rule_id",
3620 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3678 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3621 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'),
3679 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'),
3622 nullable=False)
3680 nullable=False)
3623 user = relationship('User')
3681 user = relationship('User')
3624
3682
3625
3683
3626 class RepoReviewRuleUserGroup(Base, BaseModel):
3684 class RepoReviewRuleUserGroup(Base, BaseModel):
3627 __tablename__ = 'repo_review_rules_users_groups'
3685 __tablename__ = 'repo_review_rules_users_groups'
3628 __table_args__ = (
3686 __table_args__ = (
3629 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3687 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3630 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3688 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3631 )
3689 )
3632 repo_review_rule_users_group_id = Column(
3690 repo_review_rule_users_group_id = Column(
3633 'repo_review_rule_users_group_id', Integer(), primary_key=True)
3691 'repo_review_rule_users_group_id', Integer(), primary_key=True)
3634 repo_review_rule_id = Column("repo_review_rule_id",
3692 repo_review_rule_id = Column("repo_review_rule_id",
3635 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3693 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3636 users_group_id = Column("users_group_id", Integer(),
3694 users_group_id = Column("users_group_id", Integer(),
3637 ForeignKey('users_groups.users_group_id'), nullable=False)
3695 ForeignKey('users_groups.users_group_id'), nullable=False)
3638 users_group = relationship('UserGroup')
3696 users_group = relationship('UserGroup')
3639
3697
3640
3698
3641 class RepoReviewRule(Base, BaseModel):
3699 class RepoReviewRule(Base, BaseModel):
3642 __tablename__ = 'repo_review_rules'
3700 __tablename__ = 'repo_review_rules'
3643 __table_args__ = (
3701 __table_args__ = (
3644 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3702 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3645 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3703 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3646 )
3704 )
3647
3705
3648 repo_review_rule_id = Column(
3706 repo_review_rule_id = Column(
3649 'repo_review_rule_id', Integer(), primary_key=True)
3707 'repo_review_rule_id', Integer(), primary_key=True)
3650 repo_id = Column(
3708 repo_id = Column(
3651 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
3709 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
3652 repo = relationship('Repository', backref='review_rules')
3710 repo = relationship('Repository', backref='review_rules')
3653
3711
3654 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3712 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3655 default=u'*') # glob
3713 default=u'*') # glob
3656 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3714 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3657 default=u'*') # glob
3715 default=u'*') # glob
3658
3716
3659 use_authors_for_review = Column("use_authors_for_review", Boolean(),
3717 use_authors_for_review = Column("use_authors_for_review", Boolean(),
3660 nullable=False, default=False)
3718 nullable=False, default=False)
3661 rule_users = relationship('RepoReviewRuleUser')
3719 rule_users = relationship('RepoReviewRuleUser')
3662 rule_user_groups = relationship('RepoReviewRuleUserGroup')
3720 rule_user_groups = relationship('RepoReviewRuleUserGroup')
3663
3721
3664 @hybrid_property
3722 @hybrid_property
3665 def branch_pattern(self):
3723 def branch_pattern(self):
3666 return self._branch_pattern or '*'
3724 return self._branch_pattern or '*'
3667
3725
3668 def _validate_glob(self, value):
3726 def _validate_glob(self, value):
3669 re.compile('^' + glob2re(value) + '$')
3727 re.compile('^' + glob2re(value) + '$')
3670
3728
3671 @branch_pattern.setter
3729 @branch_pattern.setter
3672 def branch_pattern(self, value):
3730 def branch_pattern(self, value):
3673 self._validate_glob(value)
3731 self._validate_glob(value)
3674 self._branch_pattern = value or '*'
3732 self._branch_pattern = value or '*'
3675
3733
3676 @hybrid_property
3734 @hybrid_property
3677 def file_pattern(self):
3735 def file_pattern(self):
3678 return self._file_pattern or '*'
3736 return self._file_pattern or '*'
3679
3737
3680 @file_pattern.setter
3738 @file_pattern.setter
3681 def file_pattern(self, value):
3739 def file_pattern(self, value):
3682 self._validate_glob(value)
3740 self._validate_glob(value)
3683 self._file_pattern = value or '*'
3741 self._file_pattern = value or '*'
3684
3742
3685 def matches(self, branch, files_changed):
3743 def matches(self, branch, files_changed):
3686 """
3744 """
3687 Check if this review rule matches a branch/files in a pull request
3745 Check if this review rule matches a branch/files in a pull request
3688
3746
3689 :param branch: branch name for the commit
3747 :param branch: branch name for the commit
3690 :param files_changed: list of file paths changed in the pull request
3748 :param files_changed: list of file paths changed in the pull request
3691 """
3749 """
3692
3750
3693 branch = branch or ''
3751 branch = branch or ''
3694 files_changed = files_changed or []
3752 files_changed = files_changed or []
3695
3753
3696 branch_matches = True
3754 branch_matches = True
3697 if branch:
3755 if branch:
3698 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
3756 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
3699 branch_matches = bool(branch_regex.search(branch))
3757 branch_matches = bool(branch_regex.search(branch))
3700
3758
3701 files_matches = True
3759 files_matches = True
3702 if self.file_pattern != '*':
3760 if self.file_pattern != '*':
3703 files_matches = False
3761 files_matches = False
3704 file_regex = re.compile(glob2re(self.file_pattern))
3762 file_regex = re.compile(glob2re(self.file_pattern))
3705 for filename in files_changed:
3763 for filename in files_changed:
3706 if file_regex.search(filename):
3764 if file_regex.search(filename):
3707 files_matches = True
3765 files_matches = True
3708 break
3766 break
3709
3767
3710 return branch_matches and files_matches
3768 return branch_matches and files_matches
3711
3769
3712 @property
3770 @property
3713 def review_users(self):
3771 def review_users(self):
3714 """ Returns the users which this rule applies to """
3772 """ Returns the users which this rule applies to """
3715
3773
3716 users = set()
3774 users = set()
3717 users |= set([
3775 users |= set([
3718 rule_user.user for rule_user in self.rule_users
3776 rule_user.user for rule_user in self.rule_users
3719 if rule_user.user.active])
3777 if rule_user.user.active])
3720 users |= set(
3778 users |= set(
3721 member.user
3779 member.user
3722 for rule_user_group in self.rule_user_groups
3780 for rule_user_group in self.rule_user_groups
3723 for member in rule_user_group.users_group.members
3781 for member in rule_user_group.users_group.members
3724 if member.user.active
3782 if member.user.active
3725 )
3783 )
3726 return users
3784 return users
3727
3785
3728 def __repr__(self):
3786 def __repr__(self):
3729 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
3787 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
3730 self.repo_review_rule_id, self.repo)
3788 self.repo_review_rule_id, self.repo)
@@ -1,2206 +1,2216 b''
1 //Primary CSS
1 //Primary CSS
2
2
3 //--- IMPORTS ------------------//
3 //--- IMPORTS ------------------//
4
4
5 @import 'helpers';
5 @import 'helpers';
6 @import 'mixins';
6 @import 'mixins';
7 @import 'rcicons';
7 @import 'rcicons';
8 @import 'fonts';
8 @import 'fonts';
9 @import 'variables';
9 @import 'variables';
10 @import 'bootstrap-variables';
10 @import 'bootstrap-variables';
11 @import 'form-bootstrap';
11 @import 'form-bootstrap';
12 @import 'codemirror';
12 @import 'codemirror';
13 @import 'legacy_code_styles';
13 @import 'legacy_code_styles';
14 @import 'progress-bar';
14 @import 'progress-bar';
15
15
16 @import 'type';
16 @import 'type';
17 @import 'alerts';
17 @import 'alerts';
18 @import 'buttons';
18 @import 'buttons';
19 @import 'tags';
19 @import 'tags';
20 @import 'code-block';
20 @import 'code-block';
21 @import 'examples';
21 @import 'examples';
22 @import 'login';
22 @import 'login';
23 @import 'main-content';
23 @import 'main-content';
24 @import 'select2';
24 @import 'select2';
25 @import 'comments';
25 @import 'comments';
26 @import 'panels-bootstrap';
26 @import 'panels-bootstrap';
27 @import 'panels';
27 @import 'panels';
28 @import 'deform';
28 @import 'deform';
29
29
30 //--- BASE ------------------//
30 //--- BASE ------------------//
31 .noscript-error {
31 .noscript-error {
32 top: 0;
32 top: 0;
33 left: 0;
33 left: 0;
34 width: 100%;
34 width: 100%;
35 z-index: 101;
35 z-index: 101;
36 text-align: center;
36 text-align: center;
37 font-family: @text-semibold;
37 font-family: @text-semibold;
38 font-size: 120%;
38 font-size: 120%;
39 color: white;
39 color: white;
40 background-color: @alert2;
40 background-color: @alert2;
41 padding: 5px 0 5px 0;
41 padding: 5px 0 5px 0;
42 }
42 }
43
43
44 html {
44 html {
45 display: table;
45 display: table;
46 height: 100%;
46 height: 100%;
47 width: 100%;
47 width: 100%;
48 }
48 }
49
49
50 body {
50 body {
51 display: table-cell;
51 display: table-cell;
52 width: 100%;
52 width: 100%;
53 }
53 }
54
54
55 //--- LAYOUT ------------------//
55 //--- LAYOUT ------------------//
56
56
57 .hidden{
57 .hidden{
58 display: none !important;
58 display: none !important;
59 }
59 }
60
60
61 .box{
61 .box{
62 float: left;
62 float: left;
63 width: 100%;
63 width: 100%;
64 }
64 }
65
65
66 .browser-header {
66 .browser-header {
67 clear: both;
67 clear: both;
68 }
68 }
69 .main {
69 .main {
70 clear: both;
70 clear: both;
71 padding:0 0 @pagepadding;
71 padding:0 0 @pagepadding;
72 height: auto;
72 height: auto;
73
73
74 &:after { //clearfix
74 &:after { //clearfix
75 content:"";
75 content:"";
76 clear:both;
76 clear:both;
77 width:100%;
77 width:100%;
78 display:block;
78 display:block;
79 }
79 }
80 }
80 }
81
81
82 .action-link{
82 .action-link{
83 margin-left: @padding;
83 margin-left: @padding;
84 padding-left: @padding;
84 padding-left: @padding;
85 border-left: @border-thickness solid @border-default-color;
85 border-left: @border-thickness solid @border-default-color;
86 }
86 }
87
87
88 input + .action-link, .action-link.first{
88 input + .action-link, .action-link.first{
89 border-left: none;
89 border-left: none;
90 }
90 }
91
91
92 .action-link.last{
92 .action-link.last{
93 margin-right: @padding;
93 margin-right: @padding;
94 padding-right: @padding;
94 padding-right: @padding;
95 }
95 }
96
96
97 .action-link.active,
97 .action-link.active,
98 .action-link.active a{
98 .action-link.active a{
99 color: @grey4;
99 color: @grey4;
100 }
100 }
101
101
102 ul.simple-list{
102 ul.simple-list{
103 list-style: none;
103 list-style: none;
104 margin: 0;
104 margin: 0;
105 padding: 0;
105 padding: 0;
106 }
106 }
107
107
108 .main-content {
108 .main-content {
109 padding-bottom: @pagepadding;
109 padding-bottom: @pagepadding;
110 }
110 }
111
111
112 .wide-mode-wrapper {
112 .wide-mode-wrapper {
113 max-width:2400px !important;
113 max-width:2400px !important;
114 }
114 }
115
115
116 .wrapper {
116 .wrapper {
117 position: relative;
117 position: relative;
118 max-width: @wrapper-maxwidth;
118 max-width: @wrapper-maxwidth;
119 margin: 0 auto;
119 margin: 0 auto;
120 }
120 }
121
121
122 #content {
122 #content {
123 clear: both;
123 clear: both;
124 padding: 0 @contentpadding;
124 padding: 0 @contentpadding;
125 }
125 }
126
126
127 .advanced-settings-fields{
127 .advanced-settings-fields{
128 input{
128 input{
129 margin-left: @textmargin;
129 margin-left: @textmargin;
130 margin-right: @padding/2;
130 margin-right: @padding/2;
131 }
131 }
132 }
132 }
133
133
134 .cs_files_title {
134 .cs_files_title {
135 margin: @pagepadding 0 0;
135 margin: @pagepadding 0 0;
136 }
136 }
137
137
138 input.inline[type="file"] {
138 input.inline[type="file"] {
139 display: inline;
139 display: inline;
140 }
140 }
141
141
142 .error_page {
142 .error_page {
143 margin: 10% auto;
143 margin: 10% auto;
144
144
145 h1 {
145 h1 {
146 color: @grey2;
146 color: @grey2;
147 }
147 }
148
148
149 .alert {
149 .alert {
150 margin: @padding 0;
150 margin: @padding 0;
151 }
151 }
152
152
153 .error-branding {
153 .error-branding {
154 font-family: @text-semibold;
154 font-family: @text-semibold;
155 color: @grey4;
155 color: @grey4;
156 }
156 }
157
157
158 .error_message {
158 .error_message {
159 font-family: @text-regular;
159 font-family: @text-regular;
160 }
160 }
161
161
162 .sidebar {
162 .sidebar {
163 min-height: 275px;
163 min-height: 275px;
164 margin: 0;
164 margin: 0;
165 padding: 0 0 @sidebarpadding @sidebarpadding;
165 padding: 0 0 @sidebarpadding @sidebarpadding;
166 border: none;
166 border: none;
167 }
167 }
168
168
169 .main-content {
169 .main-content {
170 position: relative;
170 position: relative;
171 margin: 0 @sidebarpadding @sidebarpadding;
171 margin: 0 @sidebarpadding @sidebarpadding;
172 padding: 0 0 0 @sidebarpadding;
172 padding: 0 0 0 @sidebarpadding;
173 border-left: @border-thickness solid @grey5;
173 border-left: @border-thickness solid @grey5;
174
174
175 @media (max-width:767px) {
175 @media (max-width:767px) {
176 clear: both;
176 clear: both;
177 width: 100%;
177 width: 100%;
178 margin: 0;
178 margin: 0;
179 border: none;
179 border: none;
180 }
180 }
181 }
181 }
182
182
183 .inner-column {
183 .inner-column {
184 float: left;
184 float: left;
185 width: 29.75%;
185 width: 29.75%;
186 min-height: 150px;
186 min-height: 150px;
187 margin: @sidebarpadding 2% 0 0;
187 margin: @sidebarpadding 2% 0 0;
188 padding: 0 2% 0 0;
188 padding: 0 2% 0 0;
189 border-right: @border-thickness solid @grey5;
189 border-right: @border-thickness solid @grey5;
190
190
191 @media (max-width:767px) {
191 @media (max-width:767px) {
192 clear: both;
192 clear: both;
193 width: 100%;
193 width: 100%;
194 border: none;
194 border: none;
195 }
195 }
196
196
197 ul {
197 ul {
198 padding-left: 1.25em;
198 padding-left: 1.25em;
199 }
199 }
200
200
201 &:last-child {
201 &:last-child {
202 margin: @sidebarpadding 0 0;
202 margin: @sidebarpadding 0 0;
203 border: none;
203 border: none;
204 }
204 }
205
205
206 h4 {
206 h4 {
207 margin: 0 0 @padding;
207 margin: 0 0 @padding;
208 font-family: @text-semibold;
208 font-family: @text-semibold;
209 }
209 }
210 }
210 }
211 }
211 }
212 .error-page-logo {
212 .error-page-logo {
213 width: 130px;
213 width: 130px;
214 height: 160px;
214 height: 160px;
215 }
215 }
216
216
217 // HEADER
217 // HEADER
218 .header {
218 .header {
219
219
220 // TODO: johbo: Fix login pages, so that they work without a min-height
220 // TODO: johbo: Fix login pages, so that they work without a min-height
221 // for the header and then remove the min-height. I chose a smaller value
221 // for the header and then remove the min-height. I chose a smaller value
222 // intentionally here to avoid rendering issues in the main navigation.
222 // intentionally here to avoid rendering issues in the main navigation.
223 min-height: 49px;
223 min-height: 49px;
224
224
225 position: relative;
225 position: relative;
226 vertical-align: bottom;
226 vertical-align: bottom;
227 padding: 0 @header-padding;
227 padding: 0 @header-padding;
228 background-color: @grey2;
228 background-color: @grey2;
229 color: @grey5;
229 color: @grey5;
230
230
231 .title {
231 .title {
232 overflow: visible;
232 overflow: visible;
233 }
233 }
234
234
235 &:before,
235 &:before,
236 &:after {
236 &:after {
237 content: "";
237 content: "";
238 clear: both;
238 clear: both;
239 width: 100%;
239 width: 100%;
240 }
240 }
241
241
242 // TODO: johbo: Avoids breaking "Repositories" chooser
242 // TODO: johbo: Avoids breaking "Repositories" chooser
243 .select2-container .select2-choice .select2-arrow {
243 .select2-container .select2-choice .select2-arrow {
244 display: none;
244 display: none;
245 }
245 }
246 }
246 }
247
247
248 #header-inner {
248 #header-inner {
249 &.title {
249 &.title {
250 margin: 0;
250 margin: 0;
251 }
251 }
252 &:before,
252 &:before,
253 &:after {
253 &:after {
254 content: "";
254 content: "";
255 clear: both;
255 clear: both;
256 }
256 }
257 }
257 }
258
258
259 // Gists
259 // Gists
260 #files_data {
260 #files_data {
261 clear: both; //for firefox
261 clear: both; //for firefox
262 }
262 }
263 #gistid {
263 #gistid {
264 margin-right: @padding;
264 margin-right: @padding;
265 }
265 }
266
266
267 // Global Settings Editor
267 // Global Settings Editor
268 .textarea.editor {
268 .textarea.editor {
269 float: left;
269 float: left;
270 position: relative;
270 position: relative;
271 max-width: @texteditor-width;
271 max-width: @texteditor-width;
272
272
273 select {
273 select {
274 position: absolute;
274 position: absolute;
275 top:10px;
275 top:10px;
276 right:0;
276 right:0;
277 }
277 }
278
278
279 .CodeMirror {
279 .CodeMirror {
280 margin: 0;
280 margin: 0;
281 }
281 }
282
282
283 .help-block {
283 .help-block {
284 margin: 0 0 @padding;
284 margin: 0 0 @padding;
285 padding:.5em;
285 padding:.5em;
286 background-color: @grey6;
286 background-color: @grey6;
287 }
287 }
288 }
288 }
289
289
290 ul.auth_plugins {
290 ul.auth_plugins {
291 margin: @padding 0 @padding @legend-width;
291 margin: @padding 0 @padding @legend-width;
292 padding: 0;
292 padding: 0;
293
293
294 li {
294 li {
295 margin-bottom: @padding;
295 margin-bottom: @padding;
296 line-height: 1em;
296 line-height: 1em;
297 list-style-type: none;
297 list-style-type: none;
298
298
299 .auth_buttons .btn {
299 .auth_buttons .btn {
300 margin-right: @padding;
300 margin-right: @padding;
301 }
301 }
302
302
303 &:before { content: none; }
303 &:before { content: none; }
304 }
304 }
305 }
305 }
306
306
307
307
308 // My Account PR list
308 // My Account PR list
309
309
310 #show_closed {
310 #show_closed {
311 margin: 0 1em 0 0;
311 margin: 0 1em 0 0;
312 }
312 }
313
313
314 .pullrequestlist {
314 .pullrequestlist {
315 .closed {
315 .closed {
316 background-color: @grey6;
316 background-color: @grey6;
317 }
317 }
318 .td-status {
318 .td-status {
319 padding-left: .5em;
319 padding-left: .5em;
320 }
320 }
321 .log-container .truncate {
321 .log-container .truncate {
322 height: 2.75em;
322 height: 2.75em;
323 white-space: pre-line;
323 white-space: pre-line;
324 }
324 }
325 table.rctable .user {
325 table.rctable .user {
326 padding-left: 0;
326 padding-left: 0;
327 }
327 }
328 table.rctable {
328 table.rctable {
329 td.td-description,
329 td.td-description,
330 .rc-user {
330 .rc-user {
331 min-width: auto;
331 min-width: auto;
332 }
332 }
333 }
333 }
334 }
334 }
335
335
336 // Pull Requests
336 // Pull Requests
337
337
338 .pullrequests_section_head {
338 .pullrequests_section_head {
339 display: block;
339 display: block;
340 clear: both;
340 clear: both;
341 margin: @padding 0;
341 margin: @padding 0;
342 font-family: @text-bold;
342 font-family: @text-bold;
343 }
343 }
344
344
345 .pr-origininfo, .pr-targetinfo {
345 .pr-origininfo, .pr-targetinfo {
346 position: relative;
346 position: relative;
347
347
348 .tag {
348 .tag {
349 display: inline-block;
349 display: inline-block;
350 margin: 0 1em .5em 0;
350 margin: 0 1em .5em 0;
351 }
351 }
352
352
353 .clone-url {
353 .clone-url {
354 display: inline-block;
354 display: inline-block;
355 margin: 0 0 .5em 0;
355 margin: 0 0 .5em 0;
356 padding: 0;
356 padding: 0;
357 line-height: 1.2em;
357 line-height: 1.2em;
358 }
358 }
359 }
359 }
360
360
361 .pr-pullinfo {
361 .pr-pullinfo {
362 clear: both;
362 clear: both;
363 margin: .5em 0;
363 margin: .5em 0;
364 }
364 }
365
365
366 #pr-title-input {
366 #pr-title-input {
367 width: 72%;
367 width: 72%;
368 font-size: 1em;
368 font-size: 1em;
369 font-family: @text-bold;
369 font-family: @text-bold;
370 margin: 0;
370 margin: 0;
371 padding: 0 0 0 @padding/4;
371 padding: 0 0 0 @padding/4;
372 line-height: 1.7em;
372 line-height: 1.7em;
373 color: @text-color;
373 color: @text-color;
374 letter-spacing: .02em;
374 letter-spacing: .02em;
375 }
375 }
376
376
377 #pullrequest_title {
377 #pullrequest_title {
378 width: 100%;
378 width: 100%;
379 box-sizing: border-box;
379 box-sizing: border-box;
380 }
380 }
381
381
382 #pr_open_message {
382 #pr_open_message {
383 border: @border-thickness solid #fff;
383 border: @border-thickness solid #fff;
384 border-radius: @border-radius;
384 border-radius: @border-radius;
385 padding: @padding-large-vertical @padding-large-vertical @padding-large-vertical 0;
385 padding: @padding-large-vertical @padding-large-vertical @padding-large-vertical 0;
386 text-align: right;
386 text-align: right;
387 overflow: hidden;
387 overflow: hidden;
388 }
388 }
389
389
390 .pr-submit-button {
390 .pr-submit-button {
391 float: right;
391 float: right;
392 margin: 0 0 0 5px;
392 margin: 0 0 0 5px;
393 }
393 }
394
394
395 .pr-spacing-container {
395 .pr-spacing-container {
396 padding: 20px;
396 padding: 20px;
397 clear: both
397 clear: both
398 }
398 }
399
399
400 #pr-description-input {
400 #pr-description-input {
401 margin-bottom: 0;
401 margin-bottom: 0;
402 }
402 }
403
403
404 .pr-description-label {
404 .pr-description-label {
405 vertical-align: top;
405 vertical-align: top;
406 }
406 }
407
407
408 .perms_section_head {
408 .perms_section_head {
409 min-width: 625px;
409 min-width: 625px;
410
410
411 h2 {
411 h2 {
412 margin-bottom: 0;
412 margin-bottom: 0;
413 }
413 }
414
414
415 .label-checkbox {
415 .label-checkbox {
416 float: left;
416 float: left;
417 }
417 }
418
418
419 &.field {
419 &.field {
420 margin: @space 0 @padding;
420 margin: @space 0 @padding;
421 }
421 }
422
422
423 &:first-child.field {
423 &:first-child.field {
424 margin-top: 0;
424 margin-top: 0;
425
425
426 .label {
426 .label {
427 margin-top: 0;
427 margin-top: 0;
428 padding-top: 0;
428 padding-top: 0;
429 }
429 }
430
430
431 .radios {
431 .radios {
432 padding-top: 0;
432 padding-top: 0;
433 }
433 }
434 }
434 }
435
435
436 .radios {
436 .radios {
437 float: right;
437 float: right;
438 position: relative;
438 position: relative;
439 width: 405px;
439 width: 405px;
440 }
440 }
441 }
441 }
442
442
443 //--- MODULES ------------------//
443 //--- MODULES ------------------//
444
444
445
445
446 // Server Announcement
446 // Server Announcement
447 #server-announcement {
447 #server-announcement {
448 width: 95%;
448 width: 95%;
449 margin: @padding auto;
449 margin: @padding auto;
450 padding: @padding;
450 padding: @padding;
451 border-width: 2px;
451 border-width: 2px;
452 border-style: solid;
452 border-style: solid;
453 .border-radius(2px);
453 .border-radius(2px);
454 font-family: @text-bold;
454 font-family: @text-bold;
455
455
456 &.info { border-color: @alert4; background-color: @alert4-inner; }
456 &.info { border-color: @alert4; background-color: @alert4-inner; }
457 &.warning { border-color: @alert3; background-color: @alert3-inner; }
457 &.warning { border-color: @alert3; background-color: @alert3-inner; }
458 &.error { border-color: @alert2; background-color: @alert2-inner; }
458 &.error { border-color: @alert2; background-color: @alert2-inner; }
459 &.success { border-color: @alert1; background-color: @alert1-inner; }
459 &.success { border-color: @alert1; background-color: @alert1-inner; }
460 &.neutral { border-color: @grey3; background-color: @grey6; }
460 &.neutral { border-color: @grey3; background-color: @grey6; }
461 }
461 }
462
462
463 // Fixed Sidebar Column
463 // Fixed Sidebar Column
464 .sidebar-col-wrapper {
464 .sidebar-col-wrapper {
465 padding-left: @sidebar-all-width;
465 padding-left: @sidebar-all-width;
466
466
467 .sidebar {
467 .sidebar {
468 width: @sidebar-width;
468 width: @sidebar-width;
469 margin-left: -@sidebar-all-width;
469 margin-left: -@sidebar-all-width;
470 }
470 }
471 }
471 }
472
472
473 .sidebar-col-wrapper.scw-small {
473 .sidebar-col-wrapper.scw-small {
474 padding-left: @sidebar-small-all-width;
474 padding-left: @sidebar-small-all-width;
475
475
476 .sidebar {
476 .sidebar {
477 width: @sidebar-small-width;
477 width: @sidebar-small-width;
478 margin-left: -@sidebar-small-all-width;
478 margin-left: -@sidebar-small-all-width;
479 }
479 }
480 }
480 }
481
481
482
482
483 // FOOTER
483 // FOOTER
484 #footer {
484 #footer {
485 padding: 0;
485 padding: 0;
486 text-align: center;
486 text-align: center;
487 vertical-align: middle;
487 vertical-align: middle;
488 color: @grey2;
488 color: @grey2;
489 background-color: @grey6;
489 background-color: @grey6;
490
490
491 p {
491 p {
492 margin: 0;
492 margin: 0;
493 padding: 1em;
493 padding: 1em;
494 line-height: 1em;
494 line-height: 1em;
495 }
495 }
496
496
497 .server-instance { //server instance
497 .server-instance { //server instance
498 display: none;
498 display: none;
499 }
499 }
500
500
501 .title {
501 .title {
502 float: none;
502 float: none;
503 margin: 0 auto;
503 margin: 0 auto;
504 }
504 }
505 }
505 }
506
506
507 button.close {
507 button.close {
508 padding: 0;
508 padding: 0;
509 cursor: pointer;
509 cursor: pointer;
510 background: transparent;
510 background: transparent;
511 border: 0;
511 border: 0;
512 .box-shadow(none);
512 .box-shadow(none);
513 -webkit-appearance: none;
513 -webkit-appearance: none;
514 }
514 }
515
515
516 .close {
516 .close {
517 float: right;
517 float: right;
518 font-size: 21px;
518 font-size: 21px;
519 font-family: @text-bootstrap;
519 font-family: @text-bootstrap;
520 line-height: 1em;
520 line-height: 1em;
521 font-weight: bold;
521 font-weight: bold;
522 color: @grey2;
522 color: @grey2;
523
523
524 &:hover,
524 &:hover,
525 &:focus {
525 &:focus {
526 color: @grey1;
526 color: @grey1;
527 text-decoration: none;
527 text-decoration: none;
528 cursor: pointer;
528 cursor: pointer;
529 }
529 }
530 }
530 }
531
531
532 // GRID
532 // GRID
533 .sorting,
533 .sorting,
534 .sorting_desc,
534 .sorting_desc,
535 .sorting_asc {
535 .sorting_asc {
536 cursor: pointer;
536 cursor: pointer;
537 }
537 }
538 .sorting_desc:after {
538 .sorting_desc:after {
539 content: "\00A0\25B2";
539 content: "\00A0\25B2";
540 font-size: .75em;
540 font-size: .75em;
541 }
541 }
542 .sorting_asc:after {
542 .sorting_asc:after {
543 content: "\00A0\25BC";
543 content: "\00A0\25BC";
544 font-size: .68em;
544 font-size: .68em;
545 }
545 }
546
546
547
547
548 .user_auth_tokens {
548 .user_auth_tokens {
549
549
550 &.truncate {
550 &.truncate {
551 white-space: nowrap;
551 white-space: nowrap;
552 overflow: hidden;
552 overflow: hidden;
553 text-overflow: ellipsis;
553 text-overflow: ellipsis;
554 }
554 }
555
555
556 .fields .field .input {
556 .fields .field .input {
557 margin: 0;
557 margin: 0;
558 }
558 }
559
559
560 input#description {
560 input#description {
561 width: 100px;
561 width: 100px;
562 margin: 0;
562 margin: 0;
563 }
563 }
564
564
565 .drop-menu {
565 .drop-menu {
566 // TODO: johbo: Remove this, should work out of the box when
566 // TODO: johbo: Remove this, should work out of the box when
567 // having multiple inputs inline
567 // having multiple inputs inline
568 margin: 0 0 0 5px;
568 margin: 0 0 0 5px;
569 }
569 }
570 }
570 }
571 #user_list_table {
571 #user_list_table {
572 .closed {
572 .closed {
573 background-color: @grey6;
573 background-color: @grey6;
574 }
574 }
575 }
575 }
576
576
577
577
578 input {
578 input {
579 &.disabled {
579 &.disabled {
580 opacity: .5;
580 opacity: .5;
581 }
581 }
582 }
582 }
583
583
584 // remove extra padding in firefox
584 // remove extra padding in firefox
585 input::-moz-focus-inner { border:0; padding:0 }
585 input::-moz-focus-inner { border:0; padding:0 }
586
586
587 .adjacent input {
587 .adjacent input {
588 margin-bottom: @padding;
588 margin-bottom: @padding;
589 }
589 }
590
590
591 .permissions_boxes {
591 .permissions_boxes {
592 display: block;
592 display: block;
593 }
593 }
594
594
595 //TODO: lisa: this should be in tables
595 //TODO: lisa: this should be in tables
596 .show_more_col {
596 .show_more_col {
597 width: 20px;
597 width: 20px;
598 }
598 }
599
599
600 //FORMS
600 //FORMS
601
601
602 .medium-inline,
602 .medium-inline,
603 input#description.medium-inline {
603 input#description.medium-inline {
604 display: inline;
604 display: inline;
605 width: @medium-inline-input-width;
605 width: @medium-inline-input-width;
606 min-width: 100px;
606 min-width: 100px;
607 }
607 }
608
608
609 select {
609 select {
610 //reset
610 //reset
611 -webkit-appearance: none;
611 -webkit-appearance: none;
612 -moz-appearance: none;
612 -moz-appearance: none;
613
613
614 display: inline-block;
614 display: inline-block;
615 height: 28px;
615 height: 28px;
616 width: auto;
616 width: auto;
617 margin: 0 @padding @padding 0;
617 margin: 0 @padding @padding 0;
618 padding: 0 18px 0 8px;
618 padding: 0 18px 0 8px;
619 line-height:1em;
619 line-height:1em;
620 font-size: @basefontsize;
620 font-size: @basefontsize;
621 border: @border-thickness solid @rcblue;
621 border: @border-thickness solid @rcblue;
622 background:white url("../images/dt-arrow-dn.png") no-repeat 100% 50%;
622 background:white url("../images/dt-arrow-dn.png") no-repeat 100% 50%;
623 color: @rcblue;
623 color: @rcblue;
624
624
625 &:after {
625 &:after {
626 content: "\00A0\25BE";
626 content: "\00A0\25BE";
627 }
627 }
628
628
629 &:focus {
629 &:focus {
630 outline: none;
630 outline: none;
631 }
631 }
632 }
632 }
633
633
634 option {
634 option {
635 &:focus {
635 &:focus {
636 outline: none;
636 outline: none;
637 }
637 }
638 }
638 }
639
639
640 input,
640 input,
641 textarea {
641 textarea {
642 padding: @input-padding;
642 padding: @input-padding;
643 border: @input-border-thickness solid @border-highlight-color;
643 border: @input-border-thickness solid @border-highlight-color;
644 .border-radius (@border-radius);
644 .border-radius (@border-radius);
645 font-family: @text-light;
645 font-family: @text-light;
646 font-size: @basefontsize;
646 font-size: @basefontsize;
647
647
648 &.input-sm {
648 &.input-sm {
649 padding: 5px;
649 padding: 5px;
650 }
650 }
651
651
652 &#description {
652 &#description {
653 min-width: @input-description-minwidth;
653 min-width: @input-description-minwidth;
654 min-height: 1em;
654 min-height: 1em;
655 padding: 10px;
655 padding: 10px;
656 }
656 }
657 }
657 }
658
658
659 .field-sm {
659 .field-sm {
660 input,
660 input,
661 textarea {
661 textarea {
662 padding: 5px;
662 padding: 5px;
663 }
663 }
664 }
664 }
665
665
666 textarea {
666 textarea {
667 display: block;
667 display: block;
668 clear: both;
668 clear: both;
669 width: 100%;
669 width: 100%;
670 min-height: 100px;
670 min-height: 100px;
671 margin-bottom: @padding;
671 margin-bottom: @padding;
672 .box-sizing(border-box);
672 .box-sizing(border-box);
673 overflow: auto;
673 overflow: auto;
674 }
674 }
675
675
676 label {
676 label {
677 font-family: @text-light;
677 font-family: @text-light;
678 }
678 }
679
679
680 // GRAVATARS
680 // GRAVATARS
681 // centers gravatar on username to the right
681 // centers gravatar on username to the right
682
682
683 .gravatar {
683 .gravatar {
684 display: inline;
684 display: inline;
685 min-width: 16px;
685 min-width: 16px;
686 min-height: 16px;
686 min-height: 16px;
687 margin: -5px 0;
687 margin: -5px 0;
688 padding: 0;
688 padding: 0;
689 line-height: 1em;
689 line-height: 1em;
690 border: 1px solid @grey4;
690 border: 1px solid @grey4;
691
691
692 &.gravatar-large {
692 &.gravatar-large {
693 margin: -0.5em .25em -0.5em 0;
693 margin: -0.5em .25em -0.5em 0;
694 }
694 }
695
695
696 & + .user {
696 & + .user {
697 display: inline;
697 display: inline;
698 margin: 0;
698 margin: 0;
699 padding: 0 0 0 .17em;
699 padding: 0 0 0 .17em;
700 line-height: 1em;
700 line-height: 1em;
701 }
701 }
702 }
702 }
703
703
704 .user-inline-data {
704 .user-inline-data {
705 display: inline-block;
705 display: inline-block;
706 float: left;
706 float: left;
707 padding-left: .5em;
707 padding-left: .5em;
708 line-height: 1.3em;
708 line-height: 1.3em;
709 }
709 }
710
710
711 .rc-user { // gravatar + user wrapper
711 .rc-user { // gravatar + user wrapper
712 float: left;
712 float: left;
713 position: relative;
713 position: relative;
714 min-width: 100px;
714 min-width: 100px;
715 max-width: 200px;
715 max-width: 200px;
716 min-height: (@gravatar-size + @border-thickness * 2); // account for border
716 min-height: (@gravatar-size + @border-thickness * 2); // account for border
717 display: block;
717 display: block;
718 padding: 0 0 0 (@gravatar-size + @basefontsize/2 + @border-thickness * 2);
718 padding: 0 0 0 (@gravatar-size + @basefontsize/2 + @border-thickness * 2);
719
719
720
720
721 .gravatar {
721 .gravatar {
722 display: block;
722 display: block;
723 position: absolute;
723 position: absolute;
724 top: 0;
724 top: 0;
725 left: 0;
725 left: 0;
726 min-width: @gravatar-size;
726 min-width: @gravatar-size;
727 min-height: @gravatar-size;
727 min-height: @gravatar-size;
728 margin: 0;
728 margin: 0;
729 }
729 }
730
730
731 .user {
731 .user {
732 display: block;
732 display: block;
733 max-width: 175px;
733 max-width: 175px;
734 padding-top: 2px;
734 padding-top: 2px;
735 overflow: hidden;
735 overflow: hidden;
736 text-overflow: ellipsis;
736 text-overflow: ellipsis;
737 }
737 }
738 }
738 }
739
739
740 .gist-gravatar,
740 .gist-gravatar,
741 .journal_container {
741 .journal_container {
742 .gravatar-large {
742 .gravatar-large {
743 margin: 0 .5em -10px 0;
743 margin: 0 .5em -10px 0;
744 }
744 }
745 }
745 }
746
746
747
747
748 // ADMIN SETTINGS
748 // ADMIN SETTINGS
749
749
750 // Tag Patterns
750 // Tag Patterns
751 .tag_patterns {
751 .tag_patterns {
752 .tag_input {
752 .tag_input {
753 margin-bottom: @padding;
753 margin-bottom: @padding;
754 }
754 }
755 }
755 }
756
756
757 .locked_input {
757 .locked_input {
758 position: relative;
758 position: relative;
759
759
760 input {
760 input {
761 display: inline;
761 display: inline;
762 margin-top: 3px;
762 margin-top: 3px;
763 }
763 }
764
764
765 br {
765 br {
766 display: none;
766 display: none;
767 }
767 }
768
768
769 .error-message {
769 .error-message {
770 float: left;
770 float: left;
771 width: 100%;
771 width: 100%;
772 }
772 }
773
773
774 .lock_input_button {
774 .lock_input_button {
775 display: inline;
775 display: inline;
776 }
776 }
777
777
778 .help-block {
778 .help-block {
779 clear: both;
779 clear: both;
780 }
780 }
781 }
781 }
782
782
783 // Notifications
783 // Notifications
784
784
785 .notifications_buttons {
785 .notifications_buttons {
786 margin: 0 0 @space 0;
786 margin: 0 0 @space 0;
787 padding: 0;
787 padding: 0;
788
788
789 .btn {
789 .btn {
790 display: inline-block;
790 display: inline-block;
791 }
791 }
792 }
792 }
793
793
794 .notification-list {
794 .notification-list {
795
795
796 div {
796 div {
797 display: inline-block;
797 display: inline-block;
798 vertical-align: middle;
798 vertical-align: middle;
799 }
799 }
800
800
801 .container {
801 .container {
802 display: block;
802 display: block;
803 margin: 0 0 @padding 0;
803 margin: 0 0 @padding 0;
804 }
804 }
805
805
806 .delete-notifications {
806 .delete-notifications {
807 margin-left: @padding;
807 margin-left: @padding;
808 text-align: right;
808 text-align: right;
809 cursor: pointer;
809 cursor: pointer;
810 }
810 }
811
811
812 .read-notifications {
812 .read-notifications {
813 margin-left: @padding/2;
813 margin-left: @padding/2;
814 text-align: right;
814 text-align: right;
815 width: 35px;
815 width: 35px;
816 cursor: pointer;
816 cursor: pointer;
817 }
817 }
818
818
819 .icon-minus-sign {
819 .icon-minus-sign {
820 color: @alert2;
820 color: @alert2;
821 }
821 }
822
822
823 .icon-ok-sign {
823 .icon-ok-sign {
824 color: @alert1;
824 color: @alert1;
825 }
825 }
826 }
826 }
827
827
828 .user_settings {
828 .user_settings {
829 float: left;
829 float: left;
830 clear: both;
830 clear: both;
831 display: block;
831 display: block;
832 width: 100%;
832 width: 100%;
833
833
834 .gravatar_box {
834 .gravatar_box {
835 margin-bottom: @padding;
835 margin-bottom: @padding;
836
836
837 &:after {
837 &:after {
838 content: " ";
838 content: " ";
839 clear: both;
839 clear: both;
840 width: 100%;
840 width: 100%;
841 }
841 }
842 }
842 }
843
843
844 .fields .field {
844 .fields .field {
845 clear: both;
845 clear: both;
846 }
846 }
847 }
847 }
848
848
849 .advanced_settings {
849 .advanced_settings {
850 margin-bottom: @space;
850 margin-bottom: @space;
851
851
852 .help-block {
852 .help-block {
853 margin-left: 0;
853 margin-left: 0;
854 }
854 }
855
855
856 button + .help-block {
856 button + .help-block {
857 margin-top: @padding;
857 margin-top: @padding;
858 }
858 }
859 }
859 }
860
860
861 // admin settings radio buttons and labels
861 // admin settings radio buttons and labels
862 .label-2 {
862 .label-2 {
863 float: left;
863 float: left;
864 width: @label2-width;
864 width: @label2-width;
865
865
866 label {
866 label {
867 color: @grey1;
867 color: @grey1;
868 }
868 }
869 }
869 }
870 .checkboxes {
870 .checkboxes {
871 float: left;
871 float: left;
872 width: @checkboxes-width;
872 width: @checkboxes-width;
873 margin-bottom: @padding;
873 margin-bottom: @padding;
874
874
875 .checkbox {
875 .checkbox {
876 width: 100%;
876 width: 100%;
877
877
878 label {
878 label {
879 margin: 0;
879 margin: 0;
880 padding: 0;
880 padding: 0;
881 }
881 }
882 }
882 }
883
883
884 .checkbox + .checkbox {
884 .checkbox + .checkbox {
885 display: inline-block;
885 display: inline-block;
886 }
886 }
887
887
888 label {
888 label {
889 margin-right: 1em;
889 margin-right: 1em;
890 }
890 }
891 }
891 }
892
892
893 // CHANGELOG
893 // CHANGELOG
894 .container_header {
894 .container_header {
895 float: left;
895 float: left;
896 display: block;
896 display: block;
897 width: 100%;
897 width: 100%;
898 margin: @padding 0 @padding;
898 margin: @padding 0 @padding;
899
899
900 #filter_changelog {
900 #filter_changelog {
901 float: left;
901 float: left;
902 margin-right: @padding;
902 margin-right: @padding;
903 }
903 }
904
904
905 .breadcrumbs_light {
905 .breadcrumbs_light {
906 display: inline-block;
906 display: inline-block;
907 }
907 }
908 }
908 }
909
909
910 .info_box {
910 .info_box {
911 float: right;
911 float: right;
912 }
912 }
913
913
914
914
915 #graph_nodes {
915 #graph_nodes {
916 padding-top: 43px;
916 padding-top: 43px;
917 }
917 }
918
918
919 #graph_content{
919 #graph_content{
920
920
921 // adjust for table headers so that graph renders properly
921 // adjust for table headers so that graph renders properly
922 // #graph_nodes padding - table cell padding
922 // #graph_nodes padding - table cell padding
923 padding-top: (@space - (@basefontsize * 2.4));
923 padding-top: (@space - (@basefontsize * 2.4));
924
924
925 &.graph_full_width {
925 &.graph_full_width {
926 width: 100%;
926 width: 100%;
927 max-width: 100%;
927 max-width: 100%;
928 }
928 }
929 }
929 }
930
930
931 #graph {
931 #graph {
932 .flag_status {
932 .flag_status {
933 margin: 0;
933 margin: 0;
934 }
934 }
935
935
936 .pagination-left {
936 .pagination-left {
937 float: left;
937 float: left;
938 clear: both;
938 clear: both;
939 }
939 }
940
940
941 .log-container {
941 .log-container {
942 max-width: 345px;
942 max-width: 345px;
943
943
944 .message{
944 .message{
945 max-width: 340px;
945 max-width: 340px;
946 }
946 }
947 }
947 }
948
948
949 .graph-col-wrapper {
949 .graph-col-wrapper {
950 padding-left: 110px;
950 padding-left: 110px;
951
951
952 #graph_nodes {
952 #graph_nodes {
953 width: 100px;
953 width: 100px;
954 margin-left: -110px;
954 margin-left: -110px;
955 float: left;
955 float: left;
956 clear: left;
956 clear: left;
957 }
957 }
958 }
958 }
959 }
959 }
960
960
961 #filter_changelog {
961 #filter_changelog {
962 float: left;
962 float: left;
963 }
963 }
964
964
965
965
966 //--- THEME ------------------//
966 //--- THEME ------------------//
967
967
968 #logo {
968 #logo {
969 float: left;
969 float: left;
970 margin: 9px 0 0 0;
970 margin: 9px 0 0 0;
971
971
972 .header {
972 .header {
973 background-color: transparent;
973 background-color: transparent;
974 }
974 }
975
975
976 a {
976 a {
977 display: inline-block;
977 display: inline-block;
978 }
978 }
979
979
980 img {
980 img {
981 height:30px;
981 height:30px;
982 }
982 }
983 }
983 }
984
984
985 .logo-wrapper {
985 .logo-wrapper {
986 float:left;
986 float:left;
987 }
987 }
988
988
989 .branding{
989 .branding{
990 float: left;
990 float: left;
991 padding: 9px 2px;
991 padding: 9px 2px;
992 line-height: 1em;
992 line-height: 1em;
993 font-size: @navigation-fontsize;
993 font-size: @navigation-fontsize;
994 }
994 }
995
995
996 img {
996 img {
997 border: none;
997 border: none;
998 outline: none;
998 outline: none;
999 }
999 }
1000 user-profile-header
1000 user-profile-header
1001 label {
1001 label {
1002
1002
1003 input[type="checkbox"] {
1003 input[type="checkbox"] {
1004 margin-right: 1em;
1004 margin-right: 1em;
1005 }
1005 }
1006 input[type="radio"] {
1006 input[type="radio"] {
1007 margin-right: 1em;
1007 margin-right: 1em;
1008 }
1008 }
1009 }
1009 }
1010
1010
1011 .flag_status {
1011 .flag_status {
1012 margin: 2px 8px 6px 2px;
1012 margin: 2px 8px 6px 2px;
1013 &.under_review {
1013 &.under_review {
1014 .circle(5px, @alert3);
1014 .circle(5px, @alert3);
1015 }
1015 }
1016 &.approved {
1016 &.approved {
1017 .circle(5px, @alert1);
1017 .circle(5px, @alert1);
1018 }
1018 }
1019 &.rejected,
1019 &.rejected,
1020 &.forced_closed{
1020 &.forced_closed{
1021 .circle(5px, @alert2);
1021 .circle(5px, @alert2);
1022 }
1022 }
1023 &.not_reviewed {
1023 &.not_reviewed {
1024 .circle(5px, @grey5);
1024 .circle(5px, @grey5);
1025 }
1025 }
1026 }
1026 }
1027
1027
1028 .flag_status_comment_box {
1028 .flag_status_comment_box {
1029 margin: 5px 6px 0px 2px;
1029 margin: 5px 6px 0px 2px;
1030 }
1030 }
1031 .test_pattern_preview {
1031 .test_pattern_preview {
1032 margin: @space 0;
1032 margin: @space 0;
1033
1033
1034 p {
1034 p {
1035 margin-bottom: 0;
1035 margin-bottom: 0;
1036 border-bottom: @border-thickness solid @border-default-color;
1036 border-bottom: @border-thickness solid @border-default-color;
1037 color: @grey3;
1037 color: @grey3;
1038 }
1038 }
1039
1039
1040 .btn {
1040 .btn {
1041 margin-bottom: @padding;
1041 margin-bottom: @padding;
1042 }
1042 }
1043 }
1043 }
1044 #test_pattern_result {
1044 #test_pattern_result {
1045 display: none;
1045 display: none;
1046 &:extend(pre);
1046 &:extend(pre);
1047 padding: .9em;
1047 padding: .9em;
1048 color: @grey3;
1048 color: @grey3;
1049 background-color: @grey7;
1049 background-color: @grey7;
1050 border-right: @border-thickness solid @border-default-color;
1050 border-right: @border-thickness solid @border-default-color;
1051 border-bottom: @border-thickness solid @border-default-color;
1051 border-bottom: @border-thickness solid @border-default-color;
1052 border-left: @border-thickness solid @border-default-color;
1052 border-left: @border-thickness solid @border-default-color;
1053 }
1053 }
1054
1054
1055 #repo_vcs_settings {
1055 #repo_vcs_settings {
1056 #inherit_overlay_vcs_default {
1056 #inherit_overlay_vcs_default {
1057 display: none;
1057 display: none;
1058 }
1058 }
1059 #inherit_overlay_vcs_custom {
1059 #inherit_overlay_vcs_custom {
1060 display: custom;
1060 display: custom;
1061 }
1061 }
1062 &.inherited {
1062 &.inherited {
1063 #inherit_overlay_vcs_default {
1063 #inherit_overlay_vcs_default {
1064 display: block;
1064 display: block;
1065 }
1065 }
1066 #inherit_overlay_vcs_custom {
1066 #inherit_overlay_vcs_custom {
1067 display: none;
1067 display: none;
1068 }
1068 }
1069 }
1069 }
1070 }
1070 }
1071
1071
1072 .issue-tracker-link {
1072 .issue-tracker-link {
1073 color: @rcblue;
1073 color: @rcblue;
1074 }
1074 }
1075
1075
1076 // Issue Tracker Table Show/Hide
1076 // Issue Tracker Table Show/Hide
1077 #repo_issue_tracker {
1077 #repo_issue_tracker {
1078 #inherit_overlay {
1078 #inherit_overlay {
1079 display: none;
1079 display: none;
1080 }
1080 }
1081 #custom_overlay {
1081 #custom_overlay {
1082 display: custom;
1082 display: custom;
1083 }
1083 }
1084 &.inherited {
1084 &.inherited {
1085 #inherit_overlay {
1085 #inherit_overlay {
1086 display: block;
1086 display: block;
1087 }
1087 }
1088 #custom_overlay {
1088 #custom_overlay {
1089 display: none;
1089 display: none;
1090 }
1090 }
1091 }
1091 }
1092 }
1092 }
1093 table.issuetracker {
1093 table.issuetracker {
1094 &.readonly {
1094 &.readonly {
1095 tr, td {
1095 tr, td {
1096 color: @grey3;
1096 color: @grey3;
1097 }
1097 }
1098 }
1098 }
1099 .edit {
1099 .edit {
1100 display: none;
1100 display: none;
1101 }
1101 }
1102 .editopen {
1102 .editopen {
1103 .edit {
1103 .edit {
1104 display: inline;
1104 display: inline;
1105 }
1105 }
1106 .entry {
1106 .entry {
1107 display: none;
1107 display: none;
1108 }
1108 }
1109 }
1109 }
1110 tr td.td-action {
1110 tr td.td-action {
1111 min-width: 117px;
1111 min-width: 117px;
1112 }
1112 }
1113 td input {
1113 td input {
1114 max-width: none;
1114 max-width: none;
1115 min-width: 30px;
1115 min-width: 30px;
1116 width: 80%;
1116 width: 80%;
1117 }
1117 }
1118 .issuetracker_pref input {
1118 .issuetracker_pref input {
1119 width: 40%;
1119 width: 40%;
1120 }
1120 }
1121 input.edit_issuetracker_update {
1121 input.edit_issuetracker_update {
1122 margin-right: 0;
1122 margin-right: 0;
1123 width: auto;
1123 width: auto;
1124 }
1124 }
1125 }
1125 }
1126
1126
1127 table.integrations {
1127 table.integrations {
1128 .td-icon {
1128 .td-icon {
1129 width: 20px;
1129 width: 20px;
1130 .integration-icon {
1130 .integration-icon {
1131 height: 20px;
1131 height: 20px;
1132 width: 20px;
1132 width: 20px;
1133 }
1133 }
1134 }
1134 }
1135 }
1135 }
1136
1136
1137 .integrations {
1137 .integrations {
1138 a.integration-box {
1138 a.integration-box {
1139 color: @text-color;
1139 color: @text-color;
1140 &:hover {
1140 &:hover {
1141 .panel {
1141 .panel {
1142 background: #fbfbfb;
1142 background: #fbfbfb;
1143 }
1143 }
1144 }
1144 }
1145 .integration-icon {
1145 .integration-icon {
1146 width: 30px;
1146 width: 30px;
1147 height: 30px;
1147 height: 30px;
1148 margin-right: 20px;
1148 margin-right: 20px;
1149 float: left;
1149 float: left;
1150 }
1150 }
1151
1151
1152 .panel-body {
1152 .panel-body {
1153 padding: 10px;
1153 padding: 10px;
1154 }
1154 }
1155 .panel {
1155 .panel {
1156 margin-bottom: 10px;
1156 margin-bottom: 10px;
1157 }
1157 }
1158 h2 {
1158 h2 {
1159 display: inline-block;
1159 display: inline-block;
1160 margin: 0;
1160 margin: 0;
1161 min-width: 140px;
1161 min-width: 140px;
1162 }
1162 }
1163 }
1163 }
1164 }
1164 }
1165
1165
1166 //Permissions Settings
1166 //Permissions Settings
1167 #add_perm {
1167 #add_perm {
1168 margin: 0 0 @padding;
1168 margin: 0 0 @padding;
1169 cursor: pointer;
1169 cursor: pointer;
1170 }
1170 }
1171
1171
1172 .perm_ac {
1172 .perm_ac {
1173 input {
1173 input {
1174 width: 95%;
1174 width: 95%;
1175 }
1175 }
1176 }
1176 }
1177
1177
1178 .autocomplete-suggestions {
1178 .autocomplete-suggestions {
1179 width: auto !important; // overrides autocomplete.js
1179 width: auto !important; // overrides autocomplete.js
1180 margin: 0;
1180 margin: 0;
1181 border: @border-thickness solid @rcblue;
1181 border: @border-thickness solid @rcblue;
1182 border-radius: @border-radius;
1182 border-radius: @border-radius;
1183 color: @rcblue;
1183 color: @rcblue;
1184 background-color: white;
1184 background-color: white;
1185 }
1185 }
1186 .autocomplete-selected {
1186 .autocomplete-selected {
1187 background: #F0F0F0;
1187 background: #F0F0F0;
1188 }
1188 }
1189 .ac-container-wrap {
1189 .ac-container-wrap {
1190 margin: 0;
1190 margin: 0;
1191 padding: 8px;
1191 padding: 8px;
1192 border-bottom: @border-thickness solid @rclightblue;
1192 border-bottom: @border-thickness solid @rclightblue;
1193 list-style-type: none;
1193 list-style-type: none;
1194 cursor: pointer;
1194 cursor: pointer;
1195
1195
1196 &:hover {
1196 &:hover {
1197 background-color: @rclightblue;
1197 background-color: @rclightblue;
1198 }
1198 }
1199
1199
1200 img {
1200 img {
1201 height: @gravatar-size;
1201 height: @gravatar-size;
1202 width: @gravatar-size;
1202 width: @gravatar-size;
1203 margin-right: 1em;
1203 margin-right: 1em;
1204 }
1204 }
1205
1205
1206 strong {
1206 strong {
1207 font-weight: normal;
1207 font-weight: normal;
1208 }
1208 }
1209 }
1209 }
1210
1210
1211 // Settings Dropdown
1211 // Settings Dropdown
1212 .user-menu .container {
1212 .user-menu .container {
1213 padding: 0 4px;
1213 padding: 0 4px;
1214 margin: 0;
1214 margin: 0;
1215 }
1215 }
1216
1216
1217 .user-menu .gravatar {
1217 .user-menu .gravatar {
1218 cursor: pointer;
1218 cursor: pointer;
1219 }
1219 }
1220
1220
1221 .codeblock {
1221 .codeblock {
1222 margin-bottom: @padding;
1222 margin-bottom: @padding;
1223 clear: both;
1223 clear: both;
1224
1224
1225 .stats{
1225 .stats{
1226 overflow: hidden;
1226 overflow: hidden;
1227 }
1227 }
1228
1228
1229 .message{
1229 .message{
1230 textarea{
1230 textarea{
1231 margin: 0;
1231 margin: 0;
1232 }
1232 }
1233 }
1233 }
1234
1234
1235 .code-header {
1235 .code-header {
1236 .stats {
1236 .stats {
1237 line-height: 2em;
1237 line-height: 2em;
1238
1238
1239 .revision_id {
1239 .revision_id {
1240 margin-left: 0;
1240 margin-left: 0;
1241 }
1241 }
1242 .buttons {
1242 .buttons {
1243 padding-right: 0;
1243 padding-right: 0;
1244 }
1244 }
1245 }
1245 }
1246
1246
1247 .item{
1247 .item{
1248 margin-right: 0.5em;
1248 margin-right: 0.5em;
1249 }
1249 }
1250 }
1250 }
1251
1251
1252 #editor_container{
1252 #editor_container{
1253 position: relative;
1253 position: relative;
1254 margin: @padding;
1254 margin: @padding;
1255 }
1255 }
1256 }
1256 }
1257
1257
1258 #file_history_container {
1258 #file_history_container {
1259 display: none;
1259 display: none;
1260 }
1260 }
1261
1261
1262 .file-history-inner {
1262 .file-history-inner {
1263 margin-bottom: 10px;
1263 margin-bottom: 10px;
1264 }
1264 }
1265
1265
1266 // Pull Requests
1266 // Pull Requests
1267 .summary-details {
1267 .summary-details {
1268 width: 72%;
1268 width: 72%;
1269 }
1269 }
1270 .pr-summary {
1270 .pr-summary {
1271 border-bottom: @border-thickness solid @grey5;
1271 border-bottom: @border-thickness solid @grey5;
1272 margin-bottom: @space;
1272 margin-bottom: @space;
1273 }
1273 }
1274 .reviewers-title {
1274 .reviewers-title {
1275 width: 25%;
1275 width: 25%;
1276 min-width: 200px;
1276 min-width: 200px;
1277 }
1277 }
1278 .reviewers {
1278 .reviewers {
1279 width: 25%;
1279 width: 25%;
1280 min-width: 200px;
1280 min-width: 200px;
1281 }
1281 }
1282 .reviewers ul li {
1282 .reviewers ul li {
1283 position: relative;
1283 position: relative;
1284 width: 100%;
1284 width: 100%;
1285 margin-bottom: 8px;
1285 margin-bottom: 8px;
1286 }
1286 }
1287 .reviewers_member {
1287 .reviewers_member {
1288 width: 100%;
1288 width: 100%;
1289 overflow: auto;
1289 overflow: auto;
1290 }
1290 }
1291 .reviewer_reason {
1291 .reviewer_reason {
1292 padding-left: 20px;
1292 padding-left: 20px;
1293 }
1293 }
1294 .reviewer_status {
1294 .reviewer_status {
1295 display: inline-block;
1295 display: inline-block;
1296 vertical-align: top;
1296 vertical-align: top;
1297 width: 7%;
1297 width: 7%;
1298 min-width: 20px;
1298 min-width: 20px;
1299 height: 1.2em;
1299 height: 1.2em;
1300 margin-top: 3px;
1300 margin-top: 3px;
1301 line-height: 1em;
1301 line-height: 1em;
1302 }
1302 }
1303
1303
1304 .reviewer_name {
1304 .reviewer_name {
1305 display: inline-block;
1305 display: inline-block;
1306 max-width: 83%;
1306 max-width: 83%;
1307 padding-right: 20px;
1307 padding-right: 20px;
1308 vertical-align: middle;
1308 vertical-align: middle;
1309 line-height: 1;
1309 line-height: 1;
1310
1310
1311 .rc-user {
1311 .rc-user {
1312 min-width: 0;
1312 min-width: 0;
1313 margin: -2px 1em 0 0;
1313 margin: -2px 1em 0 0;
1314 }
1314 }
1315
1315
1316 .reviewer {
1316 .reviewer {
1317 float: left;
1317 float: left;
1318 }
1318 }
1319
1319
1320 &.to-delete {
1320 &.to-delete {
1321 .user,
1321 .user,
1322 .reviewer {
1322 .reviewer {
1323 text-decoration: line-through;
1323 text-decoration: line-through;
1324 }
1324 }
1325 }
1325 }
1326 }
1326 }
1327
1327
1328 .reviewer_member_remove {
1328 .reviewer_member_remove {
1329 position: absolute;
1329 position: absolute;
1330 right: 0;
1330 right: 0;
1331 top: 0;
1331 top: 0;
1332 width: 16px;
1332 width: 16px;
1333 margin-bottom: 10px;
1333 margin-bottom: 10px;
1334 padding: 0;
1334 padding: 0;
1335 color: black;
1335 color: black;
1336 }
1336 }
1337 .reviewer_member_status {
1337 .reviewer_member_status {
1338 margin-top: 5px;
1338 margin-top: 5px;
1339 }
1339 }
1340 .pr-summary #summary{
1340 .pr-summary #summary{
1341 width: 100%;
1341 width: 100%;
1342 }
1342 }
1343 .pr-summary .action_button:hover {
1343 .pr-summary .action_button:hover {
1344 border: 0;
1344 border: 0;
1345 cursor: pointer;
1345 cursor: pointer;
1346 }
1346 }
1347 .pr-details-title {
1347 .pr-details-title {
1348 padding-bottom: 8px;
1348 padding-bottom: 8px;
1349 border-bottom: @border-thickness solid @grey5;
1349 border-bottom: @border-thickness solid @grey5;
1350
1350
1351 .action_button.disabled {
1351 .action_button.disabled {
1352 color: @grey4;
1352 color: @grey4;
1353 cursor: inherit;
1353 cursor: inherit;
1354 }
1354 }
1355 .action_button {
1355 .action_button {
1356 color: @rcblue;
1356 color: @rcblue;
1357 }
1357 }
1358 }
1358 }
1359 .pr-details-content {
1359 .pr-details-content {
1360 margin-top: @textmargin;
1360 margin-top: @textmargin;
1361 margin-bottom: @textmargin;
1361 margin-bottom: @textmargin;
1362 }
1362 }
1363 .pr-description {
1363 .pr-description {
1364 white-space:pre-wrap;
1364 white-space:pre-wrap;
1365 }
1365 }
1366 .group_members {
1366 .group_members {
1367 margin-top: 0;
1367 margin-top: 0;
1368 padding: 0;
1368 padding: 0;
1369 list-style: outside none none;
1369 list-style: outside none none;
1370
1370
1371 img {
1371 img {
1372 height: @gravatar-size;
1372 height: @gravatar-size;
1373 width: @gravatar-size;
1373 width: @gravatar-size;
1374 margin-right: .5em;
1374 margin-right: .5em;
1375 margin-left: 3px;
1375 margin-left: 3px;
1376 }
1376 }
1377
1377
1378 .to-delete {
1378 .to-delete {
1379 .user {
1379 .user {
1380 text-decoration: line-through;
1380 text-decoration: line-through;
1381 }
1381 }
1382 }
1382 }
1383 }
1383 }
1384
1384
1385 .compare_view_commits_title {
1386 .disabled {
1387 cursor: inherit;
1388 &:hover{
1389 background-color: inherit;
1390 color: inherit;
1391 }
1392 }
1393 }
1394
1385 // new entry in group_members
1395 // new entry in group_members
1386 .td-author-new-entry {
1396 .td-author-new-entry {
1387 background-color: rgba(red(@alert1), green(@alert1), blue(@alert1), 0.3);
1397 background-color: rgba(red(@alert1), green(@alert1), blue(@alert1), 0.3);
1388 }
1398 }
1389
1399
1390 .usergroup_member_remove {
1400 .usergroup_member_remove {
1391 width: 16px;
1401 width: 16px;
1392 margin-bottom: 10px;
1402 margin-bottom: 10px;
1393 padding: 0;
1403 padding: 0;
1394 color: black !important;
1404 color: black !important;
1395 cursor: pointer;
1405 cursor: pointer;
1396 }
1406 }
1397
1407
1398 .reviewer_ac .ac-input {
1408 .reviewer_ac .ac-input {
1399 width: 92%;
1409 width: 92%;
1400 margin-bottom: 1em;
1410 margin-bottom: 1em;
1401 }
1411 }
1402
1412
1403 .compare_view_commits tr{
1413 .compare_view_commits tr{
1404 height: 20px;
1414 height: 20px;
1405 }
1415 }
1406 .compare_view_commits td {
1416 .compare_view_commits td {
1407 vertical-align: top;
1417 vertical-align: top;
1408 padding-top: 10px;
1418 padding-top: 10px;
1409 }
1419 }
1410 .compare_view_commits .author {
1420 .compare_view_commits .author {
1411 margin-left: 5px;
1421 margin-left: 5px;
1412 }
1422 }
1413
1423
1414 .compare_view_files {
1424 .compare_view_files {
1415 width: 100%;
1425 width: 100%;
1416
1426
1417 td {
1427 td {
1418 vertical-align: middle;
1428 vertical-align: middle;
1419 }
1429 }
1420 }
1430 }
1421
1431
1422 .compare_view_filepath {
1432 .compare_view_filepath {
1423 color: @grey1;
1433 color: @grey1;
1424 }
1434 }
1425
1435
1426 .show_more {
1436 .show_more {
1427 display: inline-block;
1437 display: inline-block;
1428 position: relative;
1438 position: relative;
1429 vertical-align: middle;
1439 vertical-align: middle;
1430 width: 4px;
1440 width: 4px;
1431 height: @basefontsize;
1441 height: @basefontsize;
1432
1442
1433 &:after {
1443 &:after {
1434 content: "\00A0\25BE";
1444 content: "\00A0\25BE";
1435 display: inline-block;
1445 display: inline-block;
1436 width:10px;
1446 width:10px;
1437 line-height: 5px;
1447 line-height: 5px;
1438 font-size: 12px;
1448 font-size: 12px;
1439 cursor: pointer;
1449 cursor: pointer;
1440 }
1450 }
1441 }
1451 }
1442
1452
1443 .journal_more .show_more {
1453 .journal_more .show_more {
1444 display: inline;
1454 display: inline;
1445
1455
1446 &:after {
1456 &:after {
1447 content: none;
1457 content: none;
1448 }
1458 }
1449 }
1459 }
1450
1460
1451 .open .show_more:after,
1461 .open .show_more:after,
1452 .select2-dropdown-open .show_more:after {
1462 .select2-dropdown-open .show_more:after {
1453 .rotate(180deg);
1463 .rotate(180deg);
1454 margin-left: 4px;
1464 margin-left: 4px;
1455 }
1465 }
1456
1466
1457
1467
1458 .compare_view_commits .collapse_commit:after {
1468 .compare_view_commits .collapse_commit:after {
1459 cursor: pointer;
1469 cursor: pointer;
1460 content: "\00A0\25B4";
1470 content: "\00A0\25B4";
1461 margin-left: -3px;
1471 margin-left: -3px;
1462 font-size: 17px;
1472 font-size: 17px;
1463 color: @grey4;
1473 color: @grey4;
1464 }
1474 }
1465
1475
1466 .diff_links {
1476 .diff_links {
1467 margin-left: 8px;
1477 margin-left: 8px;
1468 }
1478 }
1469
1479
1470 p.ancestor {
1480 p.ancestor {
1471 margin: @padding 0;
1481 margin: @padding 0;
1472 }
1482 }
1473
1483
1474 .cs_icon_td input[type="checkbox"] {
1484 .cs_icon_td input[type="checkbox"] {
1475 display: none;
1485 display: none;
1476 }
1486 }
1477
1487
1478 .cs_icon_td .expand_file_icon:after {
1488 .cs_icon_td .expand_file_icon:after {
1479 cursor: pointer;
1489 cursor: pointer;
1480 content: "\00A0\25B6";
1490 content: "\00A0\25B6";
1481 font-size: 12px;
1491 font-size: 12px;
1482 color: @grey4;
1492 color: @grey4;
1483 }
1493 }
1484
1494
1485 .cs_icon_td .collapse_file_icon:after {
1495 .cs_icon_td .collapse_file_icon:after {
1486 cursor: pointer;
1496 cursor: pointer;
1487 content: "\00A0\25BC";
1497 content: "\00A0\25BC";
1488 font-size: 12px;
1498 font-size: 12px;
1489 color: @grey4;
1499 color: @grey4;
1490 }
1500 }
1491
1501
1492 /*new binary
1502 /*new binary
1493 NEW_FILENODE = 1
1503 NEW_FILENODE = 1
1494 DEL_FILENODE = 2
1504 DEL_FILENODE = 2
1495 MOD_FILENODE = 3
1505 MOD_FILENODE = 3
1496 RENAMED_FILENODE = 4
1506 RENAMED_FILENODE = 4
1497 COPIED_FILENODE = 5
1507 COPIED_FILENODE = 5
1498 CHMOD_FILENODE = 6
1508 CHMOD_FILENODE = 6
1499 BIN_FILENODE = 7
1509 BIN_FILENODE = 7
1500 */
1510 */
1501 .cs_files_expand {
1511 .cs_files_expand {
1502 font-size: @basefontsize + 5px;
1512 font-size: @basefontsize + 5px;
1503 line-height: 1.8em;
1513 line-height: 1.8em;
1504 float: right;
1514 float: right;
1505 }
1515 }
1506
1516
1507 .cs_files_expand span{
1517 .cs_files_expand span{
1508 color: @rcblue;
1518 color: @rcblue;
1509 cursor: pointer;
1519 cursor: pointer;
1510 }
1520 }
1511 .cs_files {
1521 .cs_files {
1512 clear: both;
1522 clear: both;
1513 padding-bottom: @padding;
1523 padding-bottom: @padding;
1514
1524
1515 .cur_cs {
1525 .cur_cs {
1516 margin: 10px 2px;
1526 margin: 10px 2px;
1517 font-weight: bold;
1527 font-weight: bold;
1518 }
1528 }
1519
1529
1520 .node {
1530 .node {
1521 float: left;
1531 float: left;
1522 }
1532 }
1523
1533
1524 .changes {
1534 .changes {
1525 float: right;
1535 float: right;
1526 color: white;
1536 color: white;
1527 font-size: @basefontsize - 4px;
1537 font-size: @basefontsize - 4px;
1528 margin-top: 4px;
1538 margin-top: 4px;
1529 opacity: 0.6;
1539 opacity: 0.6;
1530 filter: Alpha(opacity=60); /* IE8 and earlier */
1540 filter: Alpha(opacity=60); /* IE8 and earlier */
1531
1541
1532 .added {
1542 .added {
1533 background-color: @alert1;
1543 background-color: @alert1;
1534 float: left;
1544 float: left;
1535 text-align: center;
1545 text-align: center;
1536 }
1546 }
1537
1547
1538 .deleted {
1548 .deleted {
1539 background-color: @alert2;
1549 background-color: @alert2;
1540 float: left;
1550 float: left;
1541 text-align: center;
1551 text-align: center;
1542 }
1552 }
1543
1553
1544 .bin {
1554 .bin {
1545 background-color: @alert1;
1555 background-color: @alert1;
1546 text-align: center;
1556 text-align: center;
1547 }
1557 }
1548
1558
1549 /*new binary*/
1559 /*new binary*/
1550 .bin.bin1 {
1560 .bin.bin1 {
1551 background-color: @alert1;
1561 background-color: @alert1;
1552 text-align: center;
1562 text-align: center;
1553 }
1563 }
1554
1564
1555 /*deleted binary*/
1565 /*deleted binary*/
1556 .bin.bin2 {
1566 .bin.bin2 {
1557 background-color: @alert2;
1567 background-color: @alert2;
1558 text-align: center;
1568 text-align: center;
1559 }
1569 }
1560
1570
1561 /*mod binary*/
1571 /*mod binary*/
1562 .bin.bin3 {
1572 .bin.bin3 {
1563 background-color: @grey2;
1573 background-color: @grey2;
1564 text-align: center;
1574 text-align: center;
1565 }
1575 }
1566
1576
1567 /*rename file*/
1577 /*rename file*/
1568 .bin.bin4 {
1578 .bin.bin4 {
1569 background-color: @alert4;
1579 background-color: @alert4;
1570 text-align: center;
1580 text-align: center;
1571 }
1581 }
1572
1582
1573 /*copied file*/
1583 /*copied file*/
1574 .bin.bin5 {
1584 .bin.bin5 {
1575 background-color: @alert4;
1585 background-color: @alert4;
1576 text-align: center;
1586 text-align: center;
1577 }
1587 }
1578
1588
1579 /*chmod file*/
1589 /*chmod file*/
1580 .bin.bin6 {
1590 .bin.bin6 {
1581 background-color: @grey2;
1591 background-color: @grey2;
1582 text-align: center;
1592 text-align: center;
1583 }
1593 }
1584 }
1594 }
1585 }
1595 }
1586
1596
1587 .cs_files .cs_added, .cs_files .cs_A,
1597 .cs_files .cs_added, .cs_files .cs_A,
1588 .cs_files .cs_added, .cs_files .cs_M,
1598 .cs_files .cs_added, .cs_files .cs_M,
1589 .cs_files .cs_added, .cs_files .cs_D {
1599 .cs_files .cs_added, .cs_files .cs_D {
1590 height: 16px;
1600 height: 16px;
1591 padding-right: 10px;
1601 padding-right: 10px;
1592 margin-top: 7px;
1602 margin-top: 7px;
1593 text-align: left;
1603 text-align: left;
1594 }
1604 }
1595
1605
1596 .cs_icon_td {
1606 .cs_icon_td {
1597 min-width: 16px;
1607 min-width: 16px;
1598 width: 16px;
1608 width: 16px;
1599 }
1609 }
1600
1610
1601 .pull-request-merge {
1611 .pull-request-merge {
1602 padding: 10px 0;
1612 padding: 10px 0;
1603 margin-top: 10px;
1613 margin-top: 10px;
1604 margin-bottom: 20px;
1614 margin-bottom: 20px;
1605 }
1615 }
1606
1616
1607 .pull-request-merge .pull-request-wrap {
1617 .pull-request-merge .pull-request-wrap {
1608 height: 25px;
1618 height: 25px;
1609 padding: 5px 0;
1619 padding: 5px 0;
1610 }
1620 }
1611
1621
1612 .pull-request-merge span {
1622 .pull-request-merge span {
1613 margin-right: 10px;
1623 margin-right: 10px;
1614 }
1624 }
1615 #close_pull_request {
1625 #close_pull_request {
1616 margin-right: 0px;
1626 margin-right: 0px;
1617 }
1627 }
1618
1628
1619 .empty_data {
1629 .empty_data {
1620 color: @grey4;
1630 color: @grey4;
1621 }
1631 }
1622
1632
1623 #changeset_compare_view_content {
1633 #changeset_compare_view_content {
1624 margin-bottom: @space;
1634 margin-bottom: @space;
1625 clear: both;
1635 clear: both;
1626 width: 100%;
1636 width: 100%;
1627 box-sizing: border-box;
1637 box-sizing: border-box;
1628 .border-radius(@border-radius);
1638 .border-radius(@border-radius);
1629
1639
1630 .help-block {
1640 .help-block {
1631 margin: @padding 0;
1641 margin: @padding 0;
1632 color: @text-color;
1642 color: @text-color;
1633 }
1643 }
1634
1644
1635 .empty_data {
1645 .empty_data {
1636 margin: @padding 0;
1646 margin: @padding 0;
1637 }
1647 }
1638
1648
1639 .alert {
1649 .alert {
1640 margin-bottom: @space;
1650 margin-bottom: @space;
1641 }
1651 }
1642 }
1652 }
1643
1653
1644 .table_disp {
1654 .table_disp {
1645 .status {
1655 .status {
1646 width: auto;
1656 width: auto;
1647
1657
1648 .flag_status {
1658 .flag_status {
1649 float: left;
1659 float: left;
1650 }
1660 }
1651 }
1661 }
1652 }
1662 }
1653
1663
1654 .status_box_menu {
1664 .status_box_menu {
1655 margin: 0;
1665 margin: 0;
1656 }
1666 }
1657
1667
1658 .notification-table{
1668 .notification-table{
1659 margin-bottom: @space;
1669 margin-bottom: @space;
1660 display: table;
1670 display: table;
1661 width: 100%;
1671 width: 100%;
1662
1672
1663 .container{
1673 .container{
1664 display: table-row;
1674 display: table-row;
1665
1675
1666 .notification-header{
1676 .notification-header{
1667 border-bottom: @border-thickness solid @border-default-color;
1677 border-bottom: @border-thickness solid @border-default-color;
1668 }
1678 }
1669
1679
1670 .notification-subject{
1680 .notification-subject{
1671 display: table-cell;
1681 display: table-cell;
1672 }
1682 }
1673 }
1683 }
1674 }
1684 }
1675
1685
1676 // Notifications
1686 // Notifications
1677 .notification-header{
1687 .notification-header{
1678 display: table;
1688 display: table;
1679 width: 100%;
1689 width: 100%;
1680 padding: floor(@basefontsize/2) 0;
1690 padding: floor(@basefontsize/2) 0;
1681 line-height: 1em;
1691 line-height: 1em;
1682
1692
1683 .desc, .delete-notifications, .read-notifications{
1693 .desc, .delete-notifications, .read-notifications{
1684 display: table-cell;
1694 display: table-cell;
1685 text-align: left;
1695 text-align: left;
1686 }
1696 }
1687
1697
1688 .desc{
1698 .desc{
1689 width: 1163px;
1699 width: 1163px;
1690 }
1700 }
1691
1701
1692 .delete-notifications, .read-notifications{
1702 .delete-notifications, .read-notifications{
1693 width: 35px;
1703 width: 35px;
1694 min-width: 35px; //fixes when only one button is displayed
1704 min-width: 35px; //fixes when only one button is displayed
1695 }
1705 }
1696 }
1706 }
1697
1707
1698 .notification-body {
1708 .notification-body {
1699 .markdown-block,
1709 .markdown-block,
1700 .rst-block {
1710 .rst-block {
1701 padding: @padding 0;
1711 padding: @padding 0;
1702 }
1712 }
1703
1713
1704 .notification-subject {
1714 .notification-subject {
1705 padding: @textmargin 0;
1715 padding: @textmargin 0;
1706 border-bottom: @border-thickness solid @border-default-color;
1716 border-bottom: @border-thickness solid @border-default-color;
1707 }
1717 }
1708 }
1718 }
1709
1719
1710
1720
1711 .notifications_buttons{
1721 .notifications_buttons{
1712 float: right;
1722 float: right;
1713 }
1723 }
1714
1724
1715 #notification-status{
1725 #notification-status{
1716 display: inline;
1726 display: inline;
1717 }
1727 }
1718
1728
1719 // Repositories
1729 // Repositories
1720
1730
1721 #summary.fields{
1731 #summary.fields{
1722 display: table;
1732 display: table;
1723
1733
1724 .field{
1734 .field{
1725 display: table-row;
1735 display: table-row;
1726
1736
1727 .label-summary{
1737 .label-summary{
1728 display: table-cell;
1738 display: table-cell;
1729 min-width: @label-summary-minwidth;
1739 min-width: @label-summary-minwidth;
1730 padding-top: @padding/2;
1740 padding-top: @padding/2;
1731 padding-bottom: @padding/2;
1741 padding-bottom: @padding/2;
1732 padding-right: @padding/2;
1742 padding-right: @padding/2;
1733 }
1743 }
1734
1744
1735 .input{
1745 .input{
1736 display: table-cell;
1746 display: table-cell;
1737 padding: @padding/2;
1747 padding: @padding/2;
1738
1748
1739 input{
1749 input{
1740 min-width: 29em;
1750 min-width: 29em;
1741 padding: @padding/4;
1751 padding: @padding/4;
1742 }
1752 }
1743 }
1753 }
1744 .statistics, .downloads{
1754 .statistics, .downloads{
1745 .disabled{
1755 .disabled{
1746 color: @grey4;
1756 color: @grey4;
1747 }
1757 }
1748 }
1758 }
1749 }
1759 }
1750 }
1760 }
1751
1761
1752 #summary{
1762 #summary{
1753 width: 70%;
1763 width: 70%;
1754 }
1764 }
1755
1765
1756
1766
1757 // Journal
1767 // Journal
1758 .journal.title {
1768 .journal.title {
1759 h5 {
1769 h5 {
1760 float: left;
1770 float: left;
1761 margin: 0;
1771 margin: 0;
1762 width: 70%;
1772 width: 70%;
1763 }
1773 }
1764
1774
1765 ul {
1775 ul {
1766 float: right;
1776 float: right;
1767 display: inline-block;
1777 display: inline-block;
1768 margin: 0;
1778 margin: 0;
1769 width: 30%;
1779 width: 30%;
1770 text-align: right;
1780 text-align: right;
1771
1781
1772 li {
1782 li {
1773 display: inline;
1783 display: inline;
1774 font-size: @journal-fontsize;
1784 font-size: @journal-fontsize;
1775 line-height: 1em;
1785 line-height: 1em;
1776
1786
1777 &:before { content: none; }
1787 &:before { content: none; }
1778 }
1788 }
1779 }
1789 }
1780 }
1790 }
1781
1791
1782 .filterexample {
1792 .filterexample {
1783 position: absolute;
1793 position: absolute;
1784 top: 95px;
1794 top: 95px;
1785 left: @contentpadding;
1795 left: @contentpadding;
1786 color: @rcblue;
1796 color: @rcblue;
1787 font-size: 11px;
1797 font-size: 11px;
1788 font-family: @text-regular;
1798 font-family: @text-regular;
1789 cursor: help;
1799 cursor: help;
1790
1800
1791 &:hover {
1801 &:hover {
1792 color: @rcdarkblue;
1802 color: @rcdarkblue;
1793 }
1803 }
1794
1804
1795 @media (max-width:768px) {
1805 @media (max-width:768px) {
1796 position: relative;
1806 position: relative;
1797 top: auto;
1807 top: auto;
1798 left: auto;
1808 left: auto;
1799 display: block;
1809 display: block;
1800 }
1810 }
1801 }
1811 }
1802
1812
1803
1813
1804 #journal{
1814 #journal{
1805 margin-bottom: @space;
1815 margin-bottom: @space;
1806
1816
1807 .journal_day{
1817 .journal_day{
1808 margin-bottom: @textmargin/2;
1818 margin-bottom: @textmargin/2;
1809 padding-bottom: @textmargin/2;
1819 padding-bottom: @textmargin/2;
1810 font-size: @journal-fontsize;
1820 font-size: @journal-fontsize;
1811 border-bottom: @border-thickness solid @border-default-color;
1821 border-bottom: @border-thickness solid @border-default-color;
1812 }
1822 }
1813
1823
1814 .journal_container{
1824 .journal_container{
1815 margin-bottom: @space;
1825 margin-bottom: @space;
1816
1826
1817 .journal_user{
1827 .journal_user{
1818 display: inline-block;
1828 display: inline-block;
1819 }
1829 }
1820 .journal_action_container{
1830 .journal_action_container{
1821 display: block;
1831 display: block;
1822 margin-top: @textmargin;
1832 margin-top: @textmargin;
1823
1833
1824 div{
1834 div{
1825 display: inline;
1835 display: inline;
1826 }
1836 }
1827
1837
1828 div.journal_action_params{
1838 div.journal_action_params{
1829 display: block;
1839 display: block;
1830 }
1840 }
1831
1841
1832 div.journal_repo:after{
1842 div.journal_repo:after{
1833 content: "\A";
1843 content: "\A";
1834 white-space: pre;
1844 white-space: pre;
1835 }
1845 }
1836
1846
1837 div.date{
1847 div.date{
1838 display: block;
1848 display: block;
1839 margin-bottom: @textmargin;
1849 margin-bottom: @textmargin;
1840 }
1850 }
1841 }
1851 }
1842 }
1852 }
1843 }
1853 }
1844
1854
1845 // Files
1855 // Files
1846 .edit-file-title {
1856 .edit-file-title {
1847 border-bottom: @border-thickness solid @border-default-color;
1857 border-bottom: @border-thickness solid @border-default-color;
1848
1858
1849 .breadcrumbs {
1859 .breadcrumbs {
1850 margin-bottom: 0;
1860 margin-bottom: 0;
1851 }
1861 }
1852 }
1862 }
1853
1863
1854 .edit-file-fieldset {
1864 .edit-file-fieldset {
1855 margin-top: @sidebarpadding;
1865 margin-top: @sidebarpadding;
1856
1866
1857 .fieldset {
1867 .fieldset {
1858 .left-label {
1868 .left-label {
1859 width: 13%;
1869 width: 13%;
1860 }
1870 }
1861 .right-content {
1871 .right-content {
1862 width: 87%;
1872 width: 87%;
1863 max-width: 100%;
1873 max-width: 100%;
1864 }
1874 }
1865 .filename-label {
1875 .filename-label {
1866 margin-top: 13px;
1876 margin-top: 13px;
1867 }
1877 }
1868 .commit-message-label {
1878 .commit-message-label {
1869 margin-top: 4px;
1879 margin-top: 4px;
1870 }
1880 }
1871 .file-upload-input {
1881 .file-upload-input {
1872 input {
1882 input {
1873 display: none;
1883 display: none;
1874 }
1884 }
1875 }
1885 }
1876 p {
1886 p {
1877 margin-top: 5px;
1887 margin-top: 5px;
1878 }
1888 }
1879
1889
1880 }
1890 }
1881 .custom-path-link {
1891 .custom-path-link {
1882 margin-left: 5px;
1892 margin-left: 5px;
1883 }
1893 }
1884 #commit {
1894 #commit {
1885 resize: vertical;
1895 resize: vertical;
1886 }
1896 }
1887 }
1897 }
1888
1898
1889 .delete-file-preview {
1899 .delete-file-preview {
1890 max-height: 250px;
1900 max-height: 250px;
1891 }
1901 }
1892
1902
1893 .new-file,
1903 .new-file,
1894 #filter_activate,
1904 #filter_activate,
1895 #filter_deactivate {
1905 #filter_deactivate {
1896 float: left;
1906 float: left;
1897 margin: 0 0 0 15px;
1907 margin: 0 0 0 15px;
1898 }
1908 }
1899
1909
1900 h3.files_location{
1910 h3.files_location{
1901 line-height: 2.4em;
1911 line-height: 2.4em;
1902 }
1912 }
1903
1913
1904 .browser-nav {
1914 .browser-nav {
1905 display: table;
1915 display: table;
1906 margin-bottom: @space;
1916 margin-bottom: @space;
1907
1917
1908
1918
1909 .info_box {
1919 .info_box {
1910 display: inline-table;
1920 display: inline-table;
1911 height: 2.5em;
1921 height: 2.5em;
1912
1922
1913 .browser-cur-rev, .info_box_elem {
1923 .browser-cur-rev, .info_box_elem {
1914 display: table-cell;
1924 display: table-cell;
1915 vertical-align: middle;
1925 vertical-align: middle;
1916 }
1926 }
1917
1927
1918 .info_box_elem {
1928 .info_box_elem {
1919 border-top: @border-thickness solid @rcblue;
1929 border-top: @border-thickness solid @rcblue;
1920 border-bottom: @border-thickness solid @rcblue;
1930 border-bottom: @border-thickness solid @rcblue;
1921
1931
1922 #at_rev, a {
1932 #at_rev, a {
1923 padding: 0.6em 0.9em;
1933 padding: 0.6em 0.9em;
1924 margin: 0;
1934 margin: 0;
1925 .box-shadow(none);
1935 .box-shadow(none);
1926 border: 0;
1936 border: 0;
1927 height: 12px;
1937 height: 12px;
1928 }
1938 }
1929
1939
1930 input#at_rev {
1940 input#at_rev {
1931 max-width: 50px;
1941 max-width: 50px;
1932 text-align: right;
1942 text-align: right;
1933 }
1943 }
1934
1944
1935 &.previous {
1945 &.previous {
1936 border: @border-thickness solid @rcblue;
1946 border: @border-thickness solid @rcblue;
1937 .disabled {
1947 .disabled {
1938 color: @grey4;
1948 color: @grey4;
1939 cursor: not-allowed;
1949 cursor: not-allowed;
1940 }
1950 }
1941 }
1951 }
1942
1952
1943 &.next {
1953 &.next {
1944 border: @border-thickness solid @rcblue;
1954 border: @border-thickness solid @rcblue;
1945 .disabled {
1955 .disabled {
1946 color: @grey4;
1956 color: @grey4;
1947 cursor: not-allowed;
1957 cursor: not-allowed;
1948 }
1958 }
1949 }
1959 }
1950 }
1960 }
1951
1961
1952 .browser-cur-rev {
1962 .browser-cur-rev {
1953
1963
1954 span{
1964 span{
1955 margin: 0;
1965 margin: 0;
1956 color: @rcblue;
1966 color: @rcblue;
1957 height: 12px;
1967 height: 12px;
1958 display: inline-block;
1968 display: inline-block;
1959 padding: 0.7em 1em ;
1969 padding: 0.7em 1em ;
1960 border: @border-thickness solid @rcblue;
1970 border: @border-thickness solid @rcblue;
1961 margin-right: @padding;
1971 margin-right: @padding;
1962 }
1972 }
1963 }
1973 }
1964 }
1974 }
1965
1975
1966 .search_activate {
1976 .search_activate {
1967 display: table-cell;
1977 display: table-cell;
1968 vertical-align: middle;
1978 vertical-align: middle;
1969
1979
1970 input, label{
1980 input, label{
1971 margin: 0;
1981 margin: 0;
1972 padding: 0;
1982 padding: 0;
1973 }
1983 }
1974
1984
1975 input{
1985 input{
1976 margin-left: @textmargin;
1986 margin-left: @textmargin;
1977 }
1987 }
1978
1988
1979 }
1989 }
1980 }
1990 }
1981
1991
1982 .browser-cur-rev{
1992 .browser-cur-rev{
1983 margin-bottom: @textmargin;
1993 margin-bottom: @textmargin;
1984 }
1994 }
1985
1995
1986 #node_filter_box_loading{
1996 #node_filter_box_loading{
1987 .info_text;
1997 .info_text;
1988 }
1998 }
1989
1999
1990 .browser-search {
2000 .browser-search {
1991 margin: -25px 0px 5px 0px;
2001 margin: -25px 0px 5px 0px;
1992 }
2002 }
1993
2003
1994 .node-filter {
2004 .node-filter {
1995 font-size: @repo-title-fontsize;
2005 font-size: @repo-title-fontsize;
1996 padding: 4px 0px 0px 0px;
2006 padding: 4px 0px 0px 0px;
1997
2007
1998 .node-filter-path {
2008 .node-filter-path {
1999 float: left;
2009 float: left;
2000 color: @grey4;
2010 color: @grey4;
2001 }
2011 }
2002 .node-filter-input {
2012 .node-filter-input {
2003 float: left;
2013 float: left;
2004 margin: -2px 0px 0px 2px;
2014 margin: -2px 0px 0px 2px;
2005 input {
2015 input {
2006 padding: 2px;
2016 padding: 2px;
2007 border: none;
2017 border: none;
2008 font-size: @repo-title-fontsize;
2018 font-size: @repo-title-fontsize;
2009 }
2019 }
2010 }
2020 }
2011 }
2021 }
2012
2022
2013
2023
2014 .browser-result{
2024 .browser-result{
2015 td a{
2025 td a{
2016 margin-left: 0.5em;
2026 margin-left: 0.5em;
2017 display: inline-block;
2027 display: inline-block;
2018
2028
2019 em{
2029 em{
2020 font-family: @text-bold;
2030 font-family: @text-bold;
2021 }
2031 }
2022 }
2032 }
2023 }
2033 }
2024
2034
2025 .browser-highlight{
2035 .browser-highlight{
2026 background-color: @grey5-alpha;
2036 background-color: @grey5-alpha;
2027 }
2037 }
2028
2038
2029
2039
2030 // Search
2040 // Search
2031
2041
2032 .search-form{
2042 .search-form{
2033 #q {
2043 #q {
2034 width: @search-form-width;
2044 width: @search-form-width;
2035 }
2045 }
2036 .fields{
2046 .fields{
2037 margin: 0 0 @space;
2047 margin: 0 0 @space;
2038 }
2048 }
2039
2049
2040 label{
2050 label{
2041 display: inline-block;
2051 display: inline-block;
2042 margin-right: @textmargin;
2052 margin-right: @textmargin;
2043 padding-top: 0.25em;
2053 padding-top: 0.25em;
2044 }
2054 }
2045
2055
2046
2056
2047 .results{
2057 .results{
2048 clear: both;
2058 clear: both;
2049 margin: 0 0 @padding;
2059 margin: 0 0 @padding;
2050 }
2060 }
2051 }
2061 }
2052
2062
2053 div.search-feedback-items {
2063 div.search-feedback-items {
2054 display: inline-block;
2064 display: inline-block;
2055 padding:0px 0px 0px 96px;
2065 padding:0px 0px 0px 96px;
2056 }
2066 }
2057
2067
2058 div.search-code-body {
2068 div.search-code-body {
2059 background-color: #ffffff; padding: 5px 0 5px 10px;
2069 background-color: #ffffff; padding: 5px 0 5px 10px;
2060 pre {
2070 pre {
2061 .match { background-color: #faffa6;}
2071 .match { background-color: #faffa6;}
2062 .break { display: block; width: 100%; background-color: #DDE7EF; color: #747474; }
2072 .break { display: block; width: 100%; background-color: #DDE7EF; color: #747474; }
2063 }
2073 }
2064 }
2074 }
2065
2075
2066 .expand_commit.search {
2076 .expand_commit.search {
2067 .show_more.open {
2077 .show_more.open {
2068 height: auto;
2078 height: auto;
2069 max-height: none;
2079 max-height: none;
2070 }
2080 }
2071 }
2081 }
2072
2082
2073 .search-results {
2083 .search-results {
2074
2084
2075 h2 {
2085 h2 {
2076 margin-bottom: 0;
2086 margin-bottom: 0;
2077 }
2087 }
2078 .codeblock {
2088 .codeblock {
2079 border: none;
2089 border: none;
2080 background: transparent;
2090 background: transparent;
2081 }
2091 }
2082
2092
2083 .codeblock-header {
2093 .codeblock-header {
2084 border: none;
2094 border: none;
2085 background: transparent;
2095 background: transparent;
2086 }
2096 }
2087
2097
2088 .code-body {
2098 .code-body {
2089 border: @border-thickness solid @border-default-color;
2099 border: @border-thickness solid @border-default-color;
2090 .border-radius(@border-radius);
2100 .border-radius(@border-radius);
2091 }
2101 }
2092
2102
2093 .td-commit {
2103 .td-commit {
2094 &:extend(pre);
2104 &:extend(pre);
2095 border-bottom: @border-thickness solid @border-default-color;
2105 border-bottom: @border-thickness solid @border-default-color;
2096 }
2106 }
2097
2107
2098 .message {
2108 .message {
2099 height: auto;
2109 height: auto;
2100 max-width: 350px;
2110 max-width: 350px;
2101 white-space: normal;
2111 white-space: normal;
2102 text-overflow: initial;
2112 text-overflow: initial;
2103 overflow: visible;
2113 overflow: visible;
2104
2114
2105 .match { background-color: #faffa6;}
2115 .match { background-color: #faffa6;}
2106 .break { background-color: #DDE7EF; width: 100%; color: #747474; display: block; }
2116 .break { background-color: #DDE7EF; width: 100%; color: #747474; display: block; }
2107 }
2117 }
2108
2118
2109 }
2119 }
2110
2120
2111 table.rctable td.td-search-results div {
2121 table.rctable td.td-search-results div {
2112 max-width: 100%;
2122 max-width: 100%;
2113 }
2123 }
2114
2124
2115 #tip-box, .tip-box{
2125 #tip-box, .tip-box{
2116 padding: @menupadding/2;
2126 padding: @menupadding/2;
2117 display: block;
2127 display: block;
2118 border: @border-thickness solid @border-highlight-color;
2128 border: @border-thickness solid @border-highlight-color;
2119 .border-radius(@border-radius);
2129 .border-radius(@border-radius);
2120 background-color: white;
2130 background-color: white;
2121 z-index: 99;
2131 z-index: 99;
2122 white-space: pre-wrap;
2132 white-space: pre-wrap;
2123 }
2133 }
2124
2134
2125 #linktt {
2135 #linktt {
2126 width: 79px;
2136 width: 79px;
2127 }
2137 }
2128
2138
2129 #help_kb .modal-content{
2139 #help_kb .modal-content{
2130 max-width: 750px;
2140 max-width: 750px;
2131 margin: 10% auto;
2141 margin: 10% auto;
2132
2142
2133 table{
2143 table{
2134 td,th{
2144 td,th{
2135 border-bottom: none;
2145 border-bottom: none;
2136 line-height: 2.5em;
2146 line-height: 2.5em;
2137 }
2147 }
2138 th{
2148 th{
2139 padding-bottom: @textmargin/2;
2149 padding-bottom: @textmargin/2;
2140 }
2150 }
2141 td.keys{
2151 td.keys{
2142 text-align: center;
2152 text-align: center;
2143 }
2153 }
2144 }
2154 }
2145
2155
2146 .block-left{
2156 .block-left{
2147 width: 45%;
2157 width: 45%;
2148 margin-right: 5%;
2158 margin-right: 5%;
2149 }
2159 }
2150 .modal-footer{
2160 .modal-footer{
2151 clear: both;
2161 clear: both;
2152 }
2162 }
2153 .key.tag{
2163 .key.tag{
2154 padding: 0.5em;
2164 padding: 0.5em;
2155 background-color: @rcblue;
2165 background-color: @rcblue;
2156 color: white;
2166 color: white;
2157 border-color: @rcblue;
2167 border-color: @rcblue;
2158 .box-shadow(none);
2168 .box-shadow(none);
2159 }
2169 }
2160 }
2170 }
2161
2171
2162
2172
2163
2173
2164 //--- IMPORTS FOR REFACTORED STYLES ------------------//
2174 //--- IMPORTS FOR REFACTORED STYLES ------------------//
2165
2175
2166 @import 'statistics-graph';
2176 @import 'statistics-graph';
2167 @import 'tables';
2177 @import 'tables';
2168 @import 'forms';
2178 @import 'forms';
2169 @import 'diff';
2179 @import 'diff';
2170 @import 'summary';
2180 @import 'summary';
2171 @import 'navigation';
2181 @import 'navigation';
2172
2182
2173 //--- SHOW/HIDE SECTIONS --//
2183 //--- SHOW/HIDE SECTIONS --//
2174
2184
2175 .btn-collapse {
2185 .btn-collapse {
2176 float: right;
2186 float: right;
2177 text-align: right;
2187 text-align: right;
2178 font-family: @text-light;
2188 font-family: @text-light;
2179 font-size: @basefontsize;
2189 font-size: @basefontsize;
2180 cursor: pointer;
2190 cursor: pointer;
2181 border: none;
2191 border: none;
2182 color: @rcblue;
2192 color: @rcblue;
2183 }
2193 }
2184
2194
2185 table.rctable,
2195 table.rctable,
2186 table.dataTable {
2196 table.dataTable {
2187 .btn-collapse {
2197 .btn-collapse {
2188 float: right;
2198 float: right;
2189 text-align: right;
2199 text-align: right;
2190 }
2200 }
2191 }
2201 }
2192
2202
2193
2203
2194 // TODO: johbo: Fix for IE10, this avoids that we see a border
2204 // TODO: johbo: Fix for IE10, this avoids that we see a border
2195 // and padding around checkboxes and radio boxes. Move to the right place,
2205 // and padding around checkboxes and radio boxes. Move to the right place,
2196 // or better: Remove this once we did the form refactoring.
2206 // or better: Remove this once we did the form refactoring.
2197 input[type=checkbox],
2207 input[type=checkbox],
2198 input[type=radio] {
2208 input[type=radio] {
2199 padding: 0;
2209 padding: 0;
2200 border: none;
2210 border: none;
2201 }
2211 }
2202
2212
2203 .toggle-ajax-spinner{
2213 .toggle-ajax-spinner{
2204 height: 16px;
2214 height: 16px;
2205 width: 16px;
2215 width: 16px;
2206 }
2216 }
@@ -1,527 +1,559 b''
1 <%inherit file="/base/base.html"/>
1 <%inherit file="/base/base.html"/>
2
2
3 <%def name="title()">
3 <%def name="title()">
4 ${_('%s Pull Request #%s') % (c.repo_name, c.pull_request.pull_request_id)}
4 ${_('%s Pull Request #%s') % (c.repo_name, c.pull_request.pull_request_id)}
5 %if c.rhodecode_name:
5 %if c.rhodecode_name:
6 &middot; ${h.branding(c.rhodecode_name)}
6 &middot; ${h.branding(c.rhodecode_name)}
7 %endif
7 %endif
8 </%def>
8 </%def>
9
9
10 <%def name="breadcrumbs_links()">
10 <%def name="breadcrumbs_links()">
11 <span id="pr-title">
11 <span id="pr-title">
12 ${c.pull_request.title}
12 ${c.pull_request.title}
13 %if c.pull_request.is_closed():
13 %if c.pull_request.is_closed():
14 (${_('Closed')})
14 (${_('Closed')})
15 %endif
15 %endif
16 </span>
16 </span>
17 <div id="pr-title-edit" class="input" style="display: none;">
17 <div id="pr-title-edit" class="input" style="display: none;">
18 ${h.text('pullrequest_title', id_="pr-title-input", class_="large", value=c.pull_request.title)}
18 ${h.text('pullrequest_title', id_="pr-title-input", class_="large", value=c.pull_request.title)}
19 </div>
19 </div>
20 </%def>
20 </%def>
21
21
22 <%def name="menu_bar_nav()">
22 <%def name="menu_bar_nav()">
23 ${self.menu_items(active='repositories')}
23 ${self.menu_items(active='repositories')}
24 </%def>
24 </%def>
25
25
26 <%def name="menu_bar_subnav()">
26 <%def name="menu_bar_subnav()">
27 ${self.repo_menu(active='showpullrequest')}
27 ${self.repo_menu(active='showpullrequest')}
28 </%def>
28 </%def>
29
29
30 <%def name="main()">
30 <%def name="main()">
31 <script type="text/javascript">
31 <script type="text/javascript">
32 // TODO: marcink switch this to pyroutes
32 // TODO: marcink switch this to pyroutes
33 AJAX_COMMENT_DELETE_URL = "${url('pullrequest_comment_delete',repo_name=c.repo_name,comment_id='__COMMENT_ID__')}";
33 AJAX_COMMENT_DELETE_URL = "${url('pullrequest_comment_delete',repo_name=c.repo_name,comment_id='__COMMENT_ID__')}";
34 templateContext.pull_request_data.pull_request_id = ${c.pull_request.pull_request_id};
34 templateContext.pull_request_data.pull_request_id = ${c.pull_request.pull_request_id};
35 </script>
35 </script>
36 <div class="box">
36 <div class="box">
37 <div class="title">
37 <div class="title">
38 ${self.repo_page_title(c.rhodecode_db_repo)}
38 ${self.repo_page_title(c.rhodecode_db_repo)}
39 </div>
39 </div>
40
40
41 ${self.breadcrumbs()}
41 ${self.breadcrumbs()}
42
42
43
43
44 <div class="box pr-summary">
44 <div class="box pr-summary">
45 <div class="summary-details block-left">
45 <div class="summary-details block-left">
46 <%summary = lambda n:{False:'summary-short'}.get(n)%>
46 <%summary = lambda n:{False:'summary-short'}.get(n)%>
47 <div class="pr-details-title">
47 <div class="pr-details-title">
48 ${_('Pull request #%s') % c.pull_request.pull_request_id} ${_('From')} ${h.format_date(c.pull_request.created_on)}
48 <a href="${h.url('pull_requests_global', pull_request_id=c.pull_request.pull_request_id)}">${_('Pull request #%s') % c.pull_request.pull_request_id}</a> ${_('From')} ${h.format_date(c.pull_request.created_on)}
49 %if c.allowed_to_update:
49 %if c.allowed_to_update:
50 <div id="delete_pullrequest" class="pull-right action_button ${'' if c.allowed_to_delete else 'disabled' }" style="clear:inherit;padding: 0">
50 <div id="delete_pullrequest" class="pull-right action_button ${'' if c.allowed_to_delete else 'disabled' }" style="clear:inherit;padding: 0">
51 % if c.allowed_to_delete:
51 % if c.allowed_to_delete:
52 ${h.secure_form(url('pullrequest_delete', repo_name=c.pull_request.target_repo.repo_name, pull_request_id=c.pull_request.pull_request_id),method='delete')}
52 ${h.secure_form(url('pullrequest_delete', repo_name=c.pull_request.target_repo.repo_name, pull_request_id=c.pull_request.pull_request_id),method='delete')}
53 ${h.submit('remove_%s' % c.pull_request.pull_request_id, _('Delete'),
53 ${h.submit('remove_%s' % c.pull_request.pull_request_id, _('Delete'),
54 class_="btn btn-link btn-danger",onclick="return confirm('"+_('Confirm to delete this pull request')+"');")}
54 class_="btn btn-link btn-danger",onclick="return confirm('"+_('Confirm to delete this pull request')+"');")}
55 ${h.end_form()}
55 ${h.end_form()}
56 % else:
56 % else:
57 ${_('Delete')}
57 ${_('Delete')}
58 % endif
58 % endif
59 </div>
59 </div>
60 <div id="open_edit_pullrequest" class="pull-right action_button">${_('Edit')}</div>
60 <div id="open_edit_pullrequest" class="pull-right action_button">${_('Edit')}</div>
61 <div id="close_edit_pullrequest" class="pull-right action_button" style="display: none;padding: 0">${_('Cancel edit')}</div>
61 <div id="close_edit_pullrequest" class="pull-right action_button" style="display: none;padding: 0">${_('Cancel edit')}</div>
62 %endif
62 %endif
63 </div>
63 </div>
64
64
65 <div id="summary" class="fields pr-details-content">
65 <div id="summary" class="fields pr-details-content">
66 <div class="field">
66 <div class="field">
67 <div class="label-summary">
67 <div class="label-summary">
68 <label>${_('Origin')}:</label>
68 <label>${_('Origin')}:</label>
69 </div>
69 </div>
70 <div class="input">
70 <div class="input">
71 <div class="pr-origininfo">
71 <div class="pr-origininfo">
72 ## branch link is only valid if it is a branch
72 ## branch link is only valid if it is a branch
73 <span class="tag">
73 <span class="tag">
74 %if c.pull_request.source_ref_parts.type == 'branch':
74 %if c.pull_request.source_ref_parts.type == 'branch':
75 <a href="${h.url('changelog_home', repo_name=c.pull_request.source_repo.repo_name, branch=c.pull_request.source_ref_parts.name)}">${c.pull_request.source_ref_parts.type}: ${c.pull_request.source_ref_parts.name}</a>
75 <a href="${h.url('changelog_home', repo_name=c.pull_request.source_repo.repo_name, branch=c.pull_request.source_ref_parts.name)}">${c.pull_request.source_ref_parts.type}: ${c.pull_request.source_ref_parts.name}</a>
76 %else:
76 %else:
77 ${c.pull_request.source_ref_parts.type}: ${c.pull_request.source_ref_parts.name}
77 ${c.pull_request.source_ref_parts.type}: ${c.pull_request.source_ref_parts.name}
78 %endif
78 %endif
79 </span>
79 </span>
80 <span class="clone-url">
80 <span class="clone-url">
81 <a href="${h.url('summary_home', repo_name=c.pull_request.source_repo.repo_name)}">${c.pull_request.source_repo.clone_url()}</a>
81 <a href="${h.url('summary_home', repo_name=c.pull_request.source_repo.repo_name)}">${c.pull_request.source_repo.clone_url()}</a>
82 </span>
82 </span>
83 </div>
83 </div>
84 <div class="pr-pullinfo">
84 <div class="pr-pullinfo">
85 %if h.is_hg(c.pull_request.source_repo):
85 %if h.is_hg(c.pull_request.source_repo):
86 <input type="text" value="hg pull -r ${h.short_id(c.source_ref)} ${c.pull_request.source_repo.clone_url()}" readonly="readonly">
86 <input type="text" value="hg pull -r ${h.short_id(c.source_ref)} ${c.pull_request.source_repo.clone_url()}" readonly="readonly">
87 %elif h.is_git(c.pull_request.source_repo):
87 %elif h.is_git(c.pull_request.source_repo):
88 <input type="text" value="git pull ${c.pull_request.source_repo.clone_url()} ${c.pull_request.source_ref_parts.name}" readonly="readonly">
88 <input type="text" value="git pull ${c.pull_request.source_repo.clone_url()} ${c.pull_request.source_ref_parts.name}" readonly="readonly">
89 %endif
89 %endif
90 </div>
90 </div>
91 </div>
91 </div>
92 </div>
92 </div>
93 <div class="field">
93 <div class="field">
94 <div class="label-summary">
94 <div class="label-summary">
95 <label>${_('Target')}:</label>
95 <label>${_('Target')}:</label>
96 </div>
96 </div>
97 <div class="input">
97 <div class="input">
98 <div class="pr-targetinfo">
98 <div class="pr-targetinfo">
99 ## branch link is only valid if it is a branch
99 ## branch link is only valid if it is a branch
100 <span class="tag">
100 <span class="tag">
101 %if c.pull_request.target_ref_parts.type == 'branch':
101 %if c.pull_request.target_ref_parts.type == 'branch':
102 <a href="${h.url('changelog_home', repo_name=c.pull_request.target_repo.repo_name, branch=c.pull_request.target_ref_parts.name)}">${c.pull_request.target_ref_parts.type}: ${c.pull_request.target_ref_parts.name}</a>
102 <a href="${h.url('changelog_home', repo_name=c.pull_request.target_repo.repo_name, branch=c.pull_request.target_ref_parts.name)}">${c.pull_request.target_ref_parts.type}: ${c.pull_request.target_ref_parts.name}</a>
103 %else:
103 %else:
104 ${c.pull_request.target_ref_parts.type}: ${c.pull_request.target_ref_parts.name}
104 ${c.pull_request.target_ref_parts.type}: ${c.pull_request.target_ref_parts.name}
105 %endif
105 %endif
106 </span>
106 </span>
107 <span class="clone-url">
107 <span class="clone-url">
108 <a href="${h.url('summary_home', repo_name=c.pull_request.target_repo.repo_name)}">${c.pull_request.target_repo.clone_url()}</a>
108 <a href="${h.url('summary_home', repo_name=c.pull_request.target_repo.repo_name)}">${c.pull_request.target_repo.clone_url()}</a>
109 </span>
109 </span>
110 </div>
110 </div>
111 </div>
111 </div>
112 </div>
112 </div>
113
113
114 ## Link to the shadow repository.
114 ## Link to the shadow repository.
115 %if not c.pull_request.is_closed() and c.pull_request.shadow_merge_ref:
116 <div class="field">
115 <div class="field">
117 <div class="label-summary">
116 <div class="label-summary">
118 <label>Merge:</label>
117 <label>${_('Merge')}:</label>
119 </div>
118 </div>
120 <div class="input">
119 <div class="input">
120 % if not c.pull_request.is_closed() and c.pull_request.shadow_merge_ref:
121 <div class="pr-mergeinfo">
121 <div class="pr-mergeinfo">
122 %if h.is_hg(c.pull_request.target_repo):
122 %if h.is_hg(c.pull_request.target_repo):
123 <input type="text" value="hg clone -u ${c.pull_request.shadow_merge_ref.name} ${c.shadow_clone_url} pull-request-${c.pull_request.pull_request_id}" readonly="readonly">
123 <input type="text" value="hg clone -u ${c.pull_request.shadow_merge_ref.name} ${c.shadow_clone_url} pull-request-${c.pull_request.pull_request_id}" readonly="readonly">
124 %elif h.is_git(c.pull_request.target_repo):
124 %elif h.is_git(c.pull_request.target_repo):
125 <input type="text" value="git clone --branch ${c.pull_request.shadow_merge_ref.name} ${c.shadow_clone_url} pull-request-${c.pull_request.pull_request_id}" readonly="readonly">
125 <input type="text" value="git clone --branch ${c.pull_request.shadow_merge_ref.name} ${c.shadow_clone_url} pull-request-${c.pull_request.pull_request_id}" readonly="readonly">
126 %endif
126 %endif
127 </div>
127 </div>
128 % else:
129 <div class="">
130 ${_('Shadow repository data not available')}.
131 </div>
132 % endif
128 </div>
133 </div>
129 </div>
134 </div>
130 %endif
131
135
132 <div class="field">
136 <div class="field">
133 <div class="label-summary">
137 <div class="label-summary">
134 <label>${_('Review')}:</label>
138 <label>${_('Review')}:</label>
135 </div>
139 </div>
136 <div class="input">
140 <div class="input">
137 %if c.pull_request_review_status:
141 %if c.pull_request_review_status:
138 <div class="${'flag_status %s' % c.pull_request_review_status} tooltip pull-left"></div>
142 <div class="${'flag_status %s' % c.pull_request_review_status} tooltip pull-left"></div>
139 <span class="changeset-status-lbl tooltip">
143 <span class="changeset-status-lbl tooltip">
140 %if c.pull_request.is_closed():
144 %if c.pull_request.is_closed():
141 ${_('Closed')},
145 ${_('Closed')},
142 %endif
146 %endif
143 ${h.commit_status_lbl(c.pull_request_review_status)}
147 ${h.commit_status_lbl(c.pull_request_review_status)}
144 </span>
148 </span>
145 - ${ungettext('calculated based on %s reviewer vote', 'calculated based on %s reviewers votes', len(c.pull_request_reviewers)) % len(c.pull_request_reviewers)}
149 - ${ungettext('calculated based on %s reviewer vote', 'calculated based on %s reviewers votes', len(c.pull_request_reviewers)) % len(c.pull_request_reviewers)}
146 %endif
150 %endif
147 </div>
151 </div>
148 </div>
152 </div>
149 <div class="field">
153 <div class="field">
150 <div class="pr-description-label label-summary">
154 <div class="pr-description-label label-summary">
151 <label>${_('Description')}:</label>
155 <label>${_('Description')}:</label>
152 </div>
156 </div>
153 <div id="pr-desc" class="input">
157 <div id="pr-desc" class="input">
154 <div class="pr-description">${h.urlify_commit_message(c.pull_request.description, c.repo_name)}</div>
158 <div class="pr-description">${h.urlify_commit_message(c.pull_request.description, c.repo_name)}</div>
155 </div>
159 </div>
156 <div id="pr-desc-edit" class="input textarea editor" style="display: none;">
160 <div id="pr-desc-edit" class="input textarea editor" style="display: none;">
157 <textarea id="pr-description-input" size="30">${c.pull_request.description}</textarea>
161 <textarea id="pr-description-input" size="30">${c.pull_request.description}</textarea>
158 </div>
162 </div>
159 </div>
163 </div>
160 <div class="field">
164 <div class="field">
161 <div class="label-summary">
165 <div class="label-summary">
162 <label>${_('Comments')}:</label>
166 <label>${_('Comments')}:</label>
163 </div>
167 </div>
164 <div class="input">
168 <div class="input">
165 <div>
169 <div>
166 <div class="comments-number">
170 <div class="comments-number">
167 %if c.comments:
171 %if c.comments:
168 <a href="#comments">${ungettext("%d General Comment", "%d General Comments", len(c.comments)) % len(c.comments)}</a>,
172 <a href="#comments">${ungettext("%d General Comment", "%d General Comments", len(c.comments)) % len(c.comments)}</a>,
169 %else:
173 %else:
170 ${ungettext("%d General Comment", "%d General Comments", len(c.comments)) % len(c.comments)}
174 ${ungettext("%d General Comment", "%d General Comments", len(c.comments)) % len(c.comments)}
171 %endif
175 %endif
172
176
173 %if c.inline_cnt:
177 %if c.inline_cnt:
174 <a href="#" onclick="return Rhodecode.comments.nextComment();" id="inline-comments-counter">${ungettext("%d Inline Comment", "%d Inline Comments", c.inline_cnt) % c.inline_cnt}</a>
178 <a href="#" onclick="return Rhodecode.comments.nextComment();" id="inline-comments-counter">${ungettext("%d Inline Comment", "%d Inline Comments", c.inline_cnt) % c.inline_cnt}</a>
175 %else:
179 %else:
176 ${ungettext("%d Inline Comment", "%d Inline Comments", c.inline_cnt) % c.inline_cnt}
180 ${ungettext("%d Inline Comment", "%d Inline Comments", c.inline_cnt) % c.inline_cnt}
177 %endif
181 %endif
178
182
179 %if c.outdated_cnt:
183 %if c.outdated_cnt:
180 , ${ungettext("%d Outdated Comment", "%d Outdated Comments", c.outdated_cnt) % c.outdated_cnt} <span id="show-outdated-comments" class="btn btn-link">${_('(Show)')}</span>
184 , ${ungettext("%d Outdated Comment", "%d Outdated Comments", c.outdated_cnt) % c.outdated_cnt} <span id="show-outdated-comments" class="btn btn-link">${_('(Show)')}</span>
181 %endif
185 %endif
182 </div>
186 </div>
183 </div>
187 </div>
184 </div>
188 </div>
185
189
186 </div>
190 </div>
187
191
188 <div class="field">
192 <div class="field">
189 <div class="label-summary">
193 <div class="label-summary">
190 <label>${_('Versions')}:</label>
194 <label>${_('Versions')} (${len(c.versions)}):</label>
191 </div>
195 </div>
196
192 <div>
197 <div>
198 % if c.show_version_changes:
193 <table>
199 <table>
194 <tr>
200 <tr>
195 <td>
201 <td>
196 % if c.at_version == None:
202 % if c.at_version in [None, 'latest']:
197 <i class="icon-ok link"></i>
203 <i class="icon-ok link"></i>
198 % endif
204 % endif
199 </td>
205 </td>
200 <td><code><a href="${h.url.current()}">latest</a></code></td>
206 <td><code><a href="${h.url.current(version='latest')}">latest</a></code></td>
201 <td>
207 <td>
202 <code>${c.pull_request_latest.source_ref_parts.commit_id[:6]}</code>
208 <code>${c.pull_request_latest.source_ref_parts.commit_id[:6]}</code>
203 </td>
209 </td>
204 <td>${_('created')} ${h.age_component(c.pull_request.created_on)}</td>
210 <td>${_('created')} ${h.age_component(c.pull_request_latest.updated_on)}</td>
205 </tr>
211 </tr>
206 % for ver in reversed(c.pull_request.versions()):
212 % for ver in reversed(c.pull_request.versions()):
207 <tr>
213 <tr>
208 <td>
214 <td>
209 % if c.at_version == ver.pull_request_version_id:
215 % if c.at_version == ver.pull_request_version_id:
210 <i class="icon-ok link"></i>
216 <i class="icon-ok link"></i>
211 % endif
217 % endif
212 </td>
218 </td>
213 <td><code><a href="${h.url.current(version=ver.pull_request_version_id)}">version ${ver.pull_request_version_id}</a></code></td>
219 <td><code><a href="${h.url.current(version=ver.pull_request_version_id)}">version ${ver.pull_request_version_id}</a></code></td>
214 <td>
220 <td>
215 <code>${ver.source_ref_parts.commit_id[:6]}</code>
221 <code>${ver.source_ref_parts.commit_id[:6]}</code>
216 </td>
222 </td>
217 <td>${_('created')} ${h.age_component(ver.created_on)}</td>
223 <td>${_('created')} ${h.age_component(ver.updated_on)}</td>
218 </tr>
224 </tr>
219 % endfor
225 % endfor
220 </table>
226 </table>
227
228 % if c.at_version:
229 <pre>
230 Changed commits:
231 * added: ${len(c.changes.added)}
232 * removed: ${len(c.changes.removed)}
233
234 % if not (c.file_changes.added+c.file_changes.modified+c.file_changes.removed):
235 No file changes found
236 % else:
237 Changed files:
238 %for file_name in c.file_changes.added:
239 * A <a href="#${'a_' + h.FID('', file_name)}">${file_name}</a>
240 %endfor
241 %for file_name in c.file_changes.modified:
242 * M <a href="#${'a_' + h.FID('', file_name)}">${file_name}</a>
243 %endfor
244 %for file_name in c.file_changes.removed:
245 * R ${file_name}
246 %endfor
247 % endif
248 </pre>
249 % endif
250 % else:
251 ${_('Pull request versions not available')}.
252 % endif
221 </div>
253 </div>
222 </div>
254 </div>
223
255
224 <div id="pr-save" class="field" style="display: none;">
256 <div id="pr-save" class="field" style="display: none;">
225 <div class="label-summary"></div>
257 <div class="label-summary"></div>
226 <div class="input">
258 <div class="input">
227 <span id="edit_pull_request" class="btn btn-small">${_('Save Changes')}</span>
259 <span id="edit_pull_request" class="btn btn-small">${_('Save Changes')}</span>
228 </div>
260 </div>
229 </div>
261 </div>
230 </div>
262 </div>
231 </div>
263 </div>
232 <div>
264 <div>
233 ## AUTHOR
265 ## AUTHOR
234 <div class="reviewers-title block-right">
266 <div class="reviewers-title block-right">
235 <div class="pr-details-title">
267 <div class="pr-details-title">
236 ${_('Author')}
268 ${_('Author')}
237 </div>
269 </div>
238 </div>
270 </div>
239 <div class="block-right pr-details-content reviewers">
271 <div class="block-right pr-details-content reviewers">
240 <ul class="group_members">
272 <ul class="group_members">
241 <li>
273 <li>
242 ${self.gravatar_with_user(c.pull_request.author.email, 16)}
274 ${self.gravatar_with_user(c.pull_request.author.email, 16)}
243 </li>
275 </li>
244 </ul>
276 </ul>
245 </div>
277 </div>
246 ## REVIEWERS
278 ## REVIEWERS
247 <div class="reviewers-title block-right">
279 <div class="reviewers-title block-right">
248 <div class="pr-details-title">
280 <div class="pr-details-title">
249 ${_('Pull request reviewers')}
281 ${_('Pull request reviewers')}
250 %if c.allowed_to_update:
282 %if c.allowed_to_update:
251 <span id="open_edit_reviewers" class="block-right action_button">${_('Edit')}</span>
283 <span id="open_edit_reviewers" class="block-right action_button">${_('Edit')}</span>
252 <span id="close_edit_reviewers" class="block-right action_button" style="display: none;">${_('Close')}</span>
284 <span id="close_edit_reviewers" class="block-right action_button" style="display: none;">${_('Close')}</span>
253 %endif
285 %endif
254 </div>
286 </div>
255 </div>
287 </div>
256 <div id="reviewers" class="block-right pr-details-content reviewers">
288 <div id="reviewers" class="block-right pr-details-content reviewers">
257 ## members goes here !
289 ## members goes here !
258 <input type="hidden" name="__start__" value="review_members:sequence">
290 <input type="hidden" name="__start__" value="review_members:sequence">
259 <ul id="review_members" class="group_members">
291 <ul id="review_members" class="group_members">
260 %for member,reasons,status in c.pull_request_reviewers:
292 %for member,reasons,status in c.pull_request_reviewers:
261 <li id="reviewer_${member.user_id}">
293 <li id="reviewer_${member.user_id}">
262 <div class="reviewers_member">
294 <div class="reviewers_member">
263 <div class="reviewer_status tooltip" title="${h.tooltip(h.commit_status_lbl(status[0][1].status if status else 'not_reviewed'))}">
295 <div class="reviewer_status tooltip" title="${h.tooltip(h.commit_status_lbl(status[0][1].status if status else 'not_reviewed'))}">
264 <div class="${'flag_status %s' % (status[0][1].status if status else 'not_reviewed')} pull-left reviewer_member_status"></div>
296 <div class="${'flag_status %s' % (status[0][1].status if status else 'not_reviewed')} pull-left reviewer_member_status"></div>
265 </div>
297 </div>
266 <div id="reviewer_${member.user_id}_name" class="reviewer_name">
298 <div id="reviewer_${member.user_id}_name" class="reviewer_name">
267 ${self.gravatar_with_user(member.email, 16)}
299 ${self.gravatar_with_user(member.email, 16)}
268 </div>
300 </div>
269 <input type="hidden" name="__start__" value="reviewer:mapping">
301 <input type="hidden" name="__start__" value="reviewer:mapping">
270 <input type="hidden" name="__start__" value="reasons:sequence">
302 <input type="hidden" name="__start__" value="reasons:sequence">
271 %for reason in reasons:
303 %for reason in reasons:
272 <div class="reviewer_reason">- ${reason}</div>
304 <div class="reviewer_reason">- ${reason}</div>
273 <input type="hidden" name="reason" value="${reason}">
305 <input type="hidden" name="reason" value="${reason}">
274
306
275 %endfor
307 %endfor
276 <input type="hidden" name="__end__" value="reasons:sequence">
308 <input type="hidden" name="__end__" value="reasons:sequence">
277 <input id="reviewer_${member.user_id}_input" type="hidden" value="${member.user_id}" name="user_id" />
309 <input id="reviewer_${member.user_id}_input" type="hidden" value="${member.user_id}" name="user_id" />
278 <input type="hidden" name="__end__" value="reviewer:mapping">
310 <input type="hidden" name="__end__" value="reviewer:mapping">
279 %if c.allowed_to_update:
311 %if c.allowed_to_update:
280 <div class="reviewer_member_remove action_button" onclick="removeReviewMember(${member.user_id}, true)" style="visibility: hidden;">
312 <div class="reviewer_member_remove action_button" onclick="removeReviewMember(${member.user_id}, true)" style="visibility: hidden;">
281 <i class="icon-remove-sign" ></i>
313 <i class="icon-remove-sign" ></i>
282 </div>
314 </div>
283 %endif
315 %endif
284 </div>
316 </div>
285 </li>
317 </li>
286 %endfor
318 %endfor
287 </ul>
319 </ul>
288 <input type="hidden" name="__end__" value="review_members:sequence">
320 <input type="hidden" name="__end__" value="review_members:sequence">
289 %if not c.pull_request.is_closed():
321 %if not c.pull_request.is_closed():
290 <div id="add_reviewer_input" class='ac' style="display: none;">
322 <div id="add_reviewer_input" class='ac' style="display: none;">
291 %if c.allowed_to_update:
323 %if c.allowed_to_update:
292 <div class="reviewer_ac">
324 <div class="reviewer_ac">
293 ${h.text('user', class_='ac-input', placeholder=_('Add reviewer'))}
325 ${h.text('user', class_='ac-input', placeholder=_('Add reviewer'))}
294 <div id="reviewers_container"></div>
326 <div id="reviewers_container"></div>
295 </div>
327 </div>
296 <div>
328 <div>
297 <span id="update_pull_request" class="btn btn-small">${_('Save Changes')}</span>
329 <span id="update_pull_request" class="btn btn-small">${_('Save Changes')}</span>
298 </div>
330 </div>
299 %endif
331 %endif
300 </div>
332 </div>
301 %endif
333 %endif
302 </div>
334 </div>
303 </div>
335 </div>
304 </div>
336 </div>
305 <div class="box">
337 <div class="box">
306 ##DIFF
338 ##DIFF
307 <div class="table" >
339 <div class="table" >
308 <div id="changeset_compare_view_content">
340 <div id="changeset_compare_view_content">
309 ##CS
341 ##CS
310 % if c.missing_requirements:
342 % if c.missing_requirements:
311 <div class="box">
343 <div class="box">
312 <div class="alert alert-warning">
344 <div class="alert alert-warning">
313 <div>
345 <div>
314 <strong>${_('Missing requirements:')}</strong>
346 <strong>${_('Missing requirements:')}</strong>
315 ${_('These commits cannot be displayed, because this repository uses the Mercurial largefiles extension, which was not enabled.')}
347 ${_('These commits cannot be displayed, because this repository uses the Mercurial largefiles extension, which was not enabled.')}
316 </div>
348 </div>
317 </div>
349 </div>
318 </div>
350 </div>
319 % elif c.missing_commits:
351 % elif c.missing_commits:
320 <div class="box">
352 <div class="box">
321 <div class="alert alert-warning">
353 <div class="alert alert-warning">
322 <div>
354 <div>
323 <strong>${_('Missing commits')}:</strong>
355 <strong>${_('Missing commits')}:</strong>
324 ${_('This pull request cannot be displayed, because one or more commits no longer exist in the source repository.')}
356 ${_('This pull request cannot be displayed, because one or more commits no longer exist in the source repository.')}
325 ${_('Please update this pull request, push the commits back into the source repository, or consider closing this pull request.')}
357 ${_('Please update this pull request, push the commits back into the source repository, or consider closing this pull request.')}
326 </div>
358 </div>
327 </div>
359 </div>
328 </div>
360 </div>
329 % endif
361 % endif
330 <div class="compare_view_commits_title">
362 <div class="compare_view_commits_title">
331 % if c.allowed_to_update and not c.pull_request.is_closed():
363 % if c.allowed_to_update and not c.pull_request.is_closed():
332 <button id="update_commits" class="btn pull-right">${_('Update commits')}</button>
364 <a id="update_commits" class="btn btn-primary pull-right">${_('Update commits')}</a>
333 % else:
365 % else:
334 <button class="btn disabled pull-right" disabled="disabled">${_('Update commits')}</button>
366 <a class="tooltip btn disabled pull-right" disabled="disabled" title="${_('Update is disabled for current view')}">${_('Update commits')}</a>
335 % endif
367 % endif
336 % if len(c.commit_ranges):
368 % if len(c.commit_ranges):
337 <h2>${ungettext('Compare View: %s commit','Compare View: %s commits', len(c.commit_ranges)) % len(c.commit_ranges)}</h2>
369 <h2>${ungettext('Compare View: %s commit','Compare View: %s commits', len(c.commit_ranges)) % len(c.commit_ranges)}</h2>
338 % endif
370 % endif
339 </div>
371 </div>
340 % if not c.missing_commits:
372 % if not c.missing_commits:
341 <%include file="/compare/compare_commits.html" />
373 <%include file="/compare/compare_commits.html" />
342 <div class="cs_files">
374 <div class="cs_files">
343 <%namespace name="cbdiffs" file="/codeblocks/diffs.html"/>
375 <%namespace name="cbdiffs" file="/codeblocks/diffs.html"/>
344 ${cbdiffs.render_diffset_menu()}
376 ${cbdiffs.render_diffset_menu()}
345 ${cbdiffs.render_diffset(
377 ${cbdiffs.render_diffset(
346 c.diffset, use_comments=True,
378 c.diffset, use_comments=True,
347 collapse_when_files_over=30,
379 collapse_when_files_over=30,
348 disable_new_comments=not c.allowed_to_comment)}
380 disable_new_comments=not c.allowed_to_comment)}
349
381
350 </div>
382 </div>
351 % endif
383 % endif
352 </div>
384 </div>
353
385
354 ## template for inline comment form
386 ## template for inline comment form
355 <%namespace name="comment" file="/changeset/changeset_file_comment.html"/>
387 <%namespace name="comment" file="/changeset/changeset_file_comment.html"/>
356
388
357 ## render general comments
389 ## render general comments
358 ${comment.generate_comments(include_pull_request=True, is_pull_request=True)}
390 ${comment.generate_comments(include_pull_request=True, is_pull_request=True)}
359
391
360 % if not c.pull_request.is_closed():
392 % if not c.pull_request.is_closed():
361 ## main comment form and it status
393 ## main comment form and it status
362 ${comment.comments(h.url('pullrequest_comment', repo_name=c.repo_name,
394 ${comment.comments(h.url('pullrequest_comment', repo_name=c.repo_name,
363 pull_request_id=c.pull_request.pull_request_id),
395 pull_request_id=c.pull_request.pull_request_id),
364 c.pull_request_review_status,
396 c.pull_request_review_status,
365 is_pull_request=True, change_status=c.allowed_to_change_status)}
397 is_pull_request=True, change_status=c.allowed_to_change_status)}
366 %endif
398 %endif
367
399
368 <script type="text/javascript">
400 <script type="text/javascript">
369 if (location.hash) {
401 if (location.hash) {
370 var result = splitDelimitedHash(location.hash);
402 var result = splitDelimitedHash(location.hash);
371 var line = $('html').find(result.loc);
403 var line = $('html').find(result.loc);
372 if (line.length > 0){
404 if (line.length > 0){
373 offsetScroll(line, 70);
405 offsetScroll(line, 70);
374 }
406 }
375 }
407 }
376 $(function(){
408 $(function(){
377 ReviewerAutoComplete('user');
409 ReviewerAutoComplete('user');
378 // custom code mirror
410 // custom code mirror
379 var codeMirrorInstance = initPullRequestsCodeMirror('#pr-description-input');
411 var codeMirrorInstance = initPullRequestsCodeMirror('#pr-description-input');
380
412
381 var PRDetails = {
413 var PRDetails = {
382 editButton: $('#open_edit_pullrequest'),
414 editButton: $('#open_edit_pullrequest'),
383 closeButton: $('#close_edit_pullrequest'),
415 closeButton: $('#close_edit_pullrequest'),
384 deleteButton: $('#delete_pullrequest'),
416 deleteButton: $('#delete_pullrequest'),
385 viewFields: $('#pr-desc, #pr-title'),
417 viewFields: $('#pr-desc, #pr-title'),
386 editFields: $('#pr-desc-edit, #pr-title-edit, #pr-save'),
418 editFields: $('#pr-desc-edit, #pr-title-edit, #pr-save'),
387
419
388 init: function() {
420 init: function() {
389 var that = this;
421 var that = this;
390 this.editButton.on('click', function(e) { that.edit(); });
422 this.editButton.on('click', function(e) { that.edit(); });
391 this.closeButton.on('click', function(e) { that.view(); });
423 this.closeButton.on('click', function(e) { that.view(); });
392 },
424 },
393
425
394 edit: function(event) {
426 edit: function(event) {
395 this.viewFields.hide();
427 this.viewFields.hide();
396 this.editButton.hide();
428 this.editButton.hide();
397 this.deleteButton.hide();
429 this.deleteButton.hide();
398 this.closeButton.show();
430 this.closeButton.show();
399 this.editFields.show();
431 this.editFields.show();
400 codeMirrorInstance.refresh();
432 codeMirrorInstance.refresh();
401 },
433 },
402
434
403 view: function(event) {
435 view: function(event) {
404 this.editButton.show();
436 this.editButton.show();
405 this.deleteButton.show();
437 this.deleteButton.show();
406 this.editFields.hide();
438 this.editFields.hide();
407 this.closeButton.hide();
439 this.closeButton.hide();
408 this.viewFields.show();
440 this.viewFields.show();
409 }
441 }
410 };
442 };
411
443
412 var ReviewersPanel = {
444 var ReviewersPanel = {
413 editButton: $('#open_edit_reviewers'),
445 editButton: $('#open_edit_reviewers'),
414 closeButton: $('#close_edit_reviewers'),
446 closeButton: $('#close_edit_reviewers'),
415 addButton: $('#add_reviewer_input'),
447 addButton: $('#add_reviewer_input'),
416 removeButtons: $('.reviewer_member_remove'),
448 removeButtons: $('.reviewer_member_remove'),
417
449
418 init: function() {
450 init: function() {
419 var that = this;
451 var that = this;
420 this.editButton.on('click', function(e) { that.edit(); });
452 this.editButton.on('click', function(e) { that.edit(); });
421 this.closeButton.on('click', function(e) { that.close(); });
453 this.closeButton.on('click', function(e) { that.close(); });
422 },
454 },
423
455
424 edit: function(event) {
456 edit: function(event) {
425 this.editButton.hide();
457 this.editButton.hide();
426 this.closeButton.show();
458 this.closeButton.show();
427 this.addButton.show();
459 this.addButton.show();
428 this.removeButtons.css('visibility', 'visible');
460 this.removeButtons.css('visibility', 'visible');
429 },
461 },
430
462
431 close: function(event) {
463 close: function(event) {
432 this.editButton.show();
464 this.editButton.show();
433 this.closeButton.hide();
465 this.closeButton.hide();
434 this.addButton.hide();
466 this.addButton.hide();
435 this.removeButtons.css('visibility', 'hidden');
467 this.removeButtons.css('visibility', 'hidden');
436 }
468 }
437 };
469 };
438
470
439 PRDetails.init();
471 PRDetails.init();
440 ReviewersPanel.init();
472 ReviewersPanel.init();
441
473
442 $('#show-outdated-comments').on('click', function(e){
474 $('#show-outdated-comments').on('click', function(e){
443 var button = $(this);
475 var button = $(this);
444 var outdated = $('.comment-outdated');
476 var outdated = $('.comment-outdated');
445 if (button.html() === "(Show)") {
477 if (button.html() === "(Show)") {
446 button.html("(Hide)");
478 button.html("(Hide)");
447 outdated.show();
479 outdated.show();
448 } else {
480 } else {
449 button.html("(Show)");
481 button.html("(Show)");
450 outdated.hide();
482 outdated.hide();
451 }
483 }
452 });
484 });
453
485
454 $('.show-inline-comments').on('change', function(e){
486 $('.show-inline-comments').on('change', function(e){
455 var show = 'none';
487 var show = 'none';
456 var target = e.currentTarget;
488 var target = e.currentTarget;
457 if(target.checked){
489 if(target.checked){
458 show = ''
490 show = ''
459 }
491 }
460 var boxid = $(target).attr('id_for');
492 var boxid = $(target).attr('id_for');
461 var comments = $('#{0} .inline-comments'.format(boxid));
493 var comments = $('#{0} .inline-comments'.format(boxid));
462 var fn_display = function(idx){
494 var fn_display = function(idx){
463 $(this).css('display', show);
495 $(this).css('display', show);
464 };
496 };
465 $(comments).each(fn_display);
497 $(comments).each(fn_display);
466 var btns = $('#{0} .inline-comments-button'.format(boxid));
498 var btns = $('#{0} .inline-comments-button'.format(boxid));
467 $(btns).each(fn_display);
499 $(btns).each(fn_display);
468 });
500 });
469
501
470 $('#merge_pull_request_form').submit(function() {
502 $('#merge_pull_request_form').submit(function() {
471 if (!$('#merge_pull_request').attr('disabled')) {
503 if (!$('#merge_pull_request').attr('disabled')) {
472 $('#merge_pull_request').attr('disabled', 'disabled');
504 $('#merge_pull_request').attr('disabled', 'disabled');
473 }
505 }
474 return true;
506 return true;
475 });
507 });
476
508
477 $('#edit_pull_request').on('click', function(e){
509 $('#edit_pull_request').on('click', function(e){
478 var title = $('#pr-title-input').val();
510 var title = $('#pr-title-input').val();
479 var description = codeMirrorInstance.getValue();
511 var description = codeMirrorInstance.getValue();
480 editPullRequest(
512 editPullRequest(
481 "${c.repo_name}", "${c.pull_request.pull_request_id}",
513 "${c.repo_name}", "${c.pull_request.pull_request_id}",
482 title, description);
514 title, description);
483 });
515 });
484
516
485 $('#update_pull_request').on('click', function(e){
517 $('#update_pull_request').on('click', function(e){
486 updateReviewers(undefined, "${c.repo_name}", "${c.pull_request.pull_request_id}");
518 updateReviewers(undefined, "${c.repo_name}", "${c.pull_request.pull_request_id}");
487 });
519 });
488
520
489 $('#update_commits').on('click', function(e){
521 $('#update_commits').on('click', function(e){
490 var isDisabled = !$(e.currentTarget).attr('disabled');
522 var isDisabled = !$(e.currentTarget).attr('disabled');
491 $(e.currentTarget).text(_gettext('Updating...'));
523 $(e.currentTarget).text(_gettext('Updating...'));
492 $(e.currentTarget).attr('disabled', 'disabled');
524 $(e.currentTarget).attr('disabled', 'disabled');
493 if(isDisabled){
525 if(isDisabled){
494 updateCommits("${c.repo_name}", "${c.pull_request.pull_request_id}");
526 updateCommits("${c.repo_name}", "${c.pull_request.pull_request_id}");
495 }
527 }
496
528
497 });
529 });
498 // fixing issue with caches on firefox
530 // fixing issue with caches on firefox
499 $('#update_commits').removeAttr("disabled");
531 $('#update_commits').removeAttr("disabled");
500
532
501 $('#close_pull_request').on('click', function(e){
533 $('#close_pull_request').on('click', function(e){
502 closePullRequest("${c.repo_name}", "${c.pull_request.pull_request_id}");
534 closePullRequest("${c.repo_name}", "${c.pull_request.pull_request_id}");
503 });
535 });
504
536
505 $('.show-inline-comments').on('click', function(e){
537 $('.show-inline-comments').on('click', function(e){
506 var boxid = $(this).attr('data-comment-id');
538 var boxid = $(this).attr('data-comment-id');
507 var button = $(this);
539 var button = $(this);
508
540
509 if(button.hasClass("comments-visible")) {
541 if(button.hasClass("comments-visible")) {
510 $('#{0} .inline-comments'.format(boxid)).each(function(index){
542 $('#{0} .inline-comments'.format(boxid)).each(function(index){
511 $(this).hide();
543 $(this).hide();
512 });
544 });
513 button.removeClass("comments-visible");
545 button.removeClass("comments-visible");
514 } else {
546 } else {
515 $('#{0} .inline-comments'.format(boxid)).each(function(index){
547 $('#{0} .inline-comments'.format(boxid)).each(function(index){
516 $(this).show();
548 $(this).show();
517 });
549 });
518 button.addClass("comments-visible");
550 button.addClass("comments-visible");
519 }
551 }
520 });
552 });
521 })
553 })
522 </script>
554 </script>
523
555
524 </div>
556 </div>
525 </div>
557 </div>
526
558
527 </%def>
559 </%def>
@@ -1,27 +1,27 b''
1 ## -*- coding: utf-8 -*-
1 ## -*- coding: utf-8 -*-
2 Auto status change to |under_review|
2 Pull request updated. Auto status change to |under_review|
3
3
4 .. role:: added
4 .. role:: added
5 .. role:: removed
5 .. role:: removed
6 .. parsed-literal::
6 .. parsed-literal::
7
7
8 Changed commits:
8 Changed commits:
9 * :added:`${len(added_commits)} added`
9 * :added:`${len(added_commits)} added`
10 * :removed:`${len(removed_commits)} removed`
10 * :removed:`${len(removed_commits)} removed`
11
11
12 %if not changed_files:
12 %if not changed_files:
13 No file changes found
13 No file changes found
14 %else:
14 %else:
15 Changed files:
15 Changed files:
16 %for file_name in added_files:
16 %for file_name in added_files:
17 * `A ${file_name} <#${'a_' + h.FID('', file_name)}>`_
17 * `A ${file_name} <#${'a_' + h.FID('', file_name)}>`_
18 %endfor
18 %endfor
19 %for file_name in modified_files:
19 %for file_name in modified_files:
20 * `M ${file_name} <#${'a_' + h.FID('', file_name)}>`_
20 * `M ${file_name} <#${'a_' + h.FID('', file_name)}>`_
21 %endfor
21 %endfor
22 %for file_name in removed_files:
22 %for file_name in removed_files:
23 * R ${file_name}
23 * R ${file_name}
24 %endfor
24 %endfor
25 %endif
25 %endif
26
26
27 .. |under_review| replace:: *"${under_review_label}"* No newline at end of file
27 .. |under_review| replace:: *"${under_review_label}"*
@@ -1,179 +1,179 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2016 RhodeCode GmbH
3 # Copyright (C) 2010-2016 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.lib.markup_renderer import MarkupRenderer, RstTemplateRenderer
23 from rhodecode.lib.markup_renderer import MarkupRenderer, RstTemplateRenderer
24
24
25
25
26 @pytest.mark.parametrize(
26 @pytest.mark.parametrize(
27 "filename, expected_renderer",
27 "filename, expected_renderer",
28 [
28 [
29 ('readme.md', 'markdown'),
29 ('readme.md', 'markdown'),
30 ('readme.Md', 'markdown'),
30 ('readme.Md', 'markdown'),
31 ('readme.MdoWn', 'markdown'),
31 ('readme.MdoWn', 'markdown'),
32 ('readme.rst', 'rst'),
32 ('readme.rst', 'rst'),
33 ('readme.Rst', 'rst'),
33 ('readme.Rst', 'rst'),
34 ('readme.rest', 'rst'),
34 ('readme.rest', 'rst'),
35 ('readme.rest', 'rst'),
35 ('readme.rest', 'rst'),
36 ('readme', 'rst'),
36 ('readme', 'rst'),
37 ('README', 'rst'),
37 ('README', 'rst'),
38
38
39 ('markdown.xml', 'plain'),
39 ('markdown.xml', 'plain'),
40 ('rest.xml', 'plain'),
40 ('rest.xml', 'plain'),
41 ('readme.xml', 'plain'),
41 ('readme.xml', 'plain'),
42
42
43 ('readme.mdx', 'plain'),
43 ('readme.mdx', 'plain'),
44 ('readme.rstx', 'plain'),
44 ('readme.rstx', 'plain'),
45 ('readmex', 'plain'),
45 ('readmex', 'plain'),
46 ])
46 ])
47 def test_detect_renderer(filename, expected_renderer):
47 def test_detect_renderer(filename, expected_renderer):
48 detected_renderer = MarkupRenderer()._detect_renderer(
48 detected_renderer = MarkupRenderer()._detect_renderer(
49 '', filename=filename).__name__
49 '', filename=filename).__name__
50 assert expected_renderer == detected_renderer
50 assert expected_renderer == detected_renderer
51
51
52
52
53 def test_markdown_xss_link():
53 def test_markdown_xss_link():
54 xss_md = "[link](javascript:alert('XSS: pwned!'))"
54 xss_md = "[link](javascript:alert('XSS: pwned!'))"
55 rendered_html = MarkupRenderer.markdown(xss_md)
55 rendered_html = MarkupRenderer.markdown(xss_md)
56 assert 'href="javascript:alert(\'XSS: pwned!\')"' not in rendered_html
56 assert 'href="javascript:alert(\'XSS: pwned!\')"' not in rendered_html
57
57
58
58
59 def test_markdown_xss_inline_html():
59 def test_markdown_xss_inline_html():
60 xss_md = '\n'.join([
60 xss_md = '\n'.join([
61 '> <a name="n"',
61 '> <a name="n"',
62 '> href="javascript:alert(\'XSS: pwned!\')">link</a>'])
62 '> href="javascript:alert(\'XSS: pwned!\')">link</a>'])
63 rendered_html = MarkupRenderer.markdown(xss_md)
63 rendered_html = MarkupRenderer.markdown(xss_md)
64 assert 'href="javascript:alert(\'XSS: pwned!\')">' not in rendered_html
64 assert 'href="javascript:alert(\'XSS: pwned!\')">' not in rendered_html
65
65
66
66
67 def test_markdown_inline_html():
67 def test_markdown_inline_html():
68 xss_md = '\n'.join(['> <a name="n"',
68 xss_md = '\n'.join(['> <a name="n"',
69 '> href="https://rhodecode.com">link</a>'])
69 '> href="https://rhodecode.com">link</a>'])
70 rendered_html = MarkupRenderer.markdown(xss_md)
70 rendered_html = MarkupRenderer.markdown(xss_md)
71 assert '[HTML_REMOVED]link[HTML_REMOVED]' in rendered_html
71 assert '[HTML_REMOVED]link[HTML_REMOVED]' in rendered_html
72
72
73
73
74 def test_rst_xss_link():
74 def test_rst_xss_link():
75 xss_rst = "`Link<javascript:alert('XSS: pwned!')>`_"
75 xss_rst = "`Link<javascript:alert('XSS: pwned!')>`_"
76 rendered_html = MarkupRenderer.rst(xss_rst)
76 rendered_html = MarkupRenderer.rst(xss_rst)
77 assert "href=javascript:alert('XSS: pwned!')" not in rendered_html
77 assert "href=javascript:alert('XSS: pwned!')" not in rendered_html
78
78
79
79
80 @pytest.mark.xfail(reason='Bug in docutils. Waiting answer from the author')
80 @pytest.mark.xfail(reason='Bug in docutils. Waiting answer from the author')
81 def test_rst_xss_inline_html():
81 def test_rst_xss_inline_html():
82 xss_rst = '<a href="javascript:alert(\'XSS: pwned!\')">link</a>'
82 xss_rst = '<a href="javascript:alert(\'XSS: pwned!\')">link</a>'
83 rendered_html = MarkupRenderer.rst(xss_rst)
83 rendered_html = MarkupRenderer.rst(xss_rst)
84 assert 'href="javascript:alert(' not in rendered_html
84 assert 'href="javascript:alert(' not in rendered_html
85
85
86
86
87 def test_rst_xss_raw_directive():
87 def test_rst_xss_raw_directive():
88 xss_rst = '\n'.join([
88 xss_rst = '\n'.join([
89 '.. raw:: html',
89 '.. raw:: html',
90 '',
90 '',
91 ' <a href="javascript:alert(\'XSS: pwned!\')">link</a>'])
91 ' <a href="javascript:alert(\'XSS: pwned!\')">link</a>'])
92 rendered_html = MarkupRenderer.rst(xss_rst)
92 rendered_html = MarkupRenderer.rst(xss_rst)
93 assert 'href="javascript:alert(' not in rendered_html
93 assert 'href="javascript:alert(' not in rendered_html
94
94
95
95
96 def test_render_rst_template_without_files():
96 def test_render_rst_template_without_files():
97 expected = u'''\
97 expected = u'''\
98 Auto status change to |under_review|
98 Pull request updated. Auto status change to |under_review|
99
99
100 .. role:: added
100 .. role:: added
101 .. role:: removed
101 .. role:: removed
102 .. parsed-literal::
102 .. parsed-literal::
103
103
104 Changed commits:
104 Changed commits:
105 * :added:`2 added`
105 * :added:`2 added`
106 * :removed:`3 removed`
106 * :removed:`3 removed`
107
107
108 No file changes found
108 No file changes found
109
109
110 .. |under_review| replace:: *"NEW STATUS"*'''
110 .. |under_review| replace:: *"NEW STATUS"*'''
111
111
112 params = {
112 params = {
113 'under_review_label': 'NEW STATUS',
113 'under_review_label': 'NEW STATUS',
114 'added_commits': ['a', 'b'],
114 'added_commits': ['a', 'b'],
115 'removed_commits': ['a', 'b', 'c'],
115 'removed_commits': ['a', 'b', 'c'],
116 'changed_files': [],
116 'changed_files': [],
117 'added_files': [],
117 'added_files': [],
118 'modified_files': [],
118 'modified_files': [],
119 'removed_files': [],
119 'removed_files': [],
120 }
120 }
121 renderer = RstTemplateRenderer()
121 renderer = RstTemplateRenderer()
122 rendered = renderer.render('pull_request_update.mako', **params)
122 rendered = renderer.render('pull_request_update.mako', **params)
123 assert expected == rendered
123 assert expected == rendered
124
124
125
125
126 def test_render_rst_template_with_files():
126 def test_render_rst_template_with_files():
127 expected = u'''\
127 expected = u'''\
128 Auto status change to |under_review|
128 Pull request updated. Auto status change to |under_review|
129
129
130 .. role:: added
130 .. role:: added
131 .. role:: removed
131 .. role:: removed
132 .. parsed-literal::
132 .. parsed-literal::
133
133
134 Changed commits:
134 Changed commits:
135 * :added:`1 added`
135 * :added:`1 added`
136 * :removed:`3 removed`
136 * :removed:`3 removed`
137
137
138 Changed files:
138 Changed files:
139 * `A /path/a.py <#a_c--68ed34923b68>`_
139 * `A /path/a.py <#a_c--68ed34923b68>`_
140 * `A /path/b.js <#a_c--64f90608b607>`_
140 * `A /path/b.js <#a_c--64f90608b607>`_
141 * `M /path/d.js <#a_c--85842bf30c6e>`_
141 * `M /path/d.js <#a_c--85842bf30c6e>`_
142 * `M /path/Δ™.py <#a_c--d713adf009cd>`_
142 * `M /path/Δ™.py <#a_c--d713adf009cd>`_
143 * R /path/ΕΊ.py
143 * R /path/ΕΊ.py
144
144
145 .. |under_review| replace:: *"NEW STATUS"*'''
145 .. |under_review| replace:: *"NEW STATUS"*'''
146
146
147 added = ['/path/a.py', '/path/b.js']
147 added = ['/path/a.py', '/path/b.js']
148 modified = ['/path/d.js', u'/path/Δ™.py']
148 modified = ['/path/d.js', u'/path/Δ™.py']
149 removed = [u'/path/ΕΊ.py']
149 removed = [u'/path/ΕΊ.py']
150
150
151 params = {
151 params = {
152 'under_review_label': 'NEW STATUS',
152 'under_review_label': 'NEW STATUS',
153 'added_commits': ['a'],
153 'added_commits': ['a'],
154 'removed_commits': ['a', 'b', 'c'],
154 'removed_commits': ['a', 'b', 'c'],
155 'changed_files': added + modified + removed,
155 'changed_files': added + modified + removed,
156 'added_files': added,
156 'added_files': added,
157 'modified_files': modified,
157 'modified_files': modified,
158 'removed_files': removed,
158 'removed_files': removed,
159 }
159 }
160 renderer = RstTemplateRenderer()
160 renderer = RstTemplateRenderer()
161 rendered = renderer.render('pull_request_update.mako', **params)
161 rendered = renderer.render('pull_request_update.mako', **params)
162
162
163 assert expected == rendered
163 assert expected == rendered
164
164
165
165
166 def test_render_rst_auto_status_template():
166 def test_render_rst_auto_status_template():
167 expected = u'''\
167 expected = u'''\
168 Auto status change to |new_status|
168 Auto status change to |new_status|
169
169
170 .. |new_status| replace:: *"NEW STATUS"*'''
170 .. |new_status| replace:: *"NEW STATUS"*'''
171
171
172 params = {
172 params = {
173 'new_status_label': 'NEW STATUS',
173 'new_status_label': 'NEW STATUS',
174 'pull_request': None,
174 'pull_request': None,
175 'commit_id': None,
175 'commit_id': None,
176 }
176 }
177 renderer = RstTemplateRenderer()
177 renderer = RstTemplateRenderer()
178 rendered = renderer.render('auto_status_change.mako', **params)
178 rendered = renderer.render('auto_status_change.mako', **params)
179 assert expected == rendered
179 assert expected == rendered
@@ -1,846 +1,846 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2016 RhodeCode GmbH
3 # Copyright (C) 2010-2016 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 mock
21 import mock
22 import pytest
22 import pytest
23 import textwrap
23 import textwrap
24
24
25 import rhodecode
25 import rhodecode
26 from rhodecode.lib.utils2 import safe_unicode
26 from rhodecode.lib.utils2 import safe_unicode
27 from rhodecode.lib.vcs.backends import get_backend
27 from rhodecode.lib.vcs.backends import get_backend
28 from rhodecode.lib.vcs.backends.base import (
28 from rhodecode.lib.vcs.backends.base import (
29 MergeResponse, MergeFailureReason, Reference)
29 MergeResponse, MergeFailureReason, Reference)
30 from rhodecode.lib.vcs.exceptions import RepositoryError
30 from rhodecode.lib.vcs.exceptions import RepositoryError
31 from rhodecode.lib.vcs.nodes import FileNode
31 from rhodecode.lib.vcs.nodes import FileNode
32 from rhodecode.model.comment import ChangesetCommentsModel
32 from rhodecode.model.comment import ChangesetCommentsModel
33 from rhodecode.model.db import PullRequest, Session
33 from rhodecode.model.db import PullRequest, Session
34 from rhodecode.model.pull_request import PullRequestModel
34 from rhodecode.model.pull_request import PullRequestModel
35 from rhodecode.model.user import UserModel
35 from rhodecode.model.user import UserModel
36 from rhodecode.tests import TEST_USER_ADMIN_LOGIN
36 from rhodecode.tests import TEST_USER_ADMIN_LOGIN
37
37
38
38
39 pytestmark = [
39 pytestmark = [
40 pytest.mark.backends("git", "hg"),
40 pytest.mark.backends("git", "hg"),
41 ]
41 ]
42
42
43
43
44 class TestPullRequestModel:
44 class TestPullRequestModel:
45
45
46 @pytest.fixture
46 @pytest.fixture
47 def pull_request(self, request, backend, pr_util):
47 def pull_request(self, request, backend, pr_util):
48 """
48 """
49 A pull request combined with multiples patches.
49 A pull request combined with multiples patches.
50 """
50 """
51 BackendClass = get_backend(backend.alias)
51 BackendClass = get_backend(backend.alias)
52 self.merge_patcher = mock.patch.object(BackendClass, 'merge')
52 self.merge_patcher = mock.patch.object(BackendClass, 'merge')
53 self.workspace_remove_patcher = mock.patch.object(
53 self.workspace_remove_patcher = mock.patch.object(
54 BackendClass, 'cleanup_merge_workspace')
54 BackendClass, 'cleanup_merge_workspace')
55
55
56 self.workspace_remove_mock = self.workspace_remove_patcher.start()
56 self.workspace_remove_mock = self.workspace_remove_patcher.start()
57 self.merge_mock = self.merge_patcher.start()
57 self.merge_mock = self.merge_patcher.start()
58 self.comment_patcher = mock.patch(
58 self.comment_patcher = mock.patch(
59 'rhodecode.model.changeset_status.ChangesetStatusModel.set_status')
59 'rhodecode.model.changeset_status.ChangesetStatusModel.set_status')
60 self.comment_patcher.start()
60 self.comment_patcher.start()
61 self.notification_patcher = mock.patch(
61 self.notification_patcher = mock.patch(
62 'rhodecode.model.notification.NotificationModel.create')
62 'rhodecode.model.notification.NotificationModel.create')
63 self.notification_patcher.start()
63 self.notification_patcher.start()
64 self.helper_patcher = mock.patch(
64 self.helper_patcher = mock.patch(
65 'rhodecode.lib.helpers.url')
65 'rhodecode.lib.helpers.url')
66 self.helper_patcher.start()
66 self.helper_patcher.start()
67
67
68 self.hook_patcher = mock.patch.object(PullRequestModel,
68 self.hook_patcher = mock.patch.object(PullRequestModel,
69 '_trigger_pull_request_hook')
69 '_trigger_pull_request_hook')
70 self.hook_mock = self.hook_patcher.start()
70 self.hook_mock = self.hook_patcher.start()
71
71
72 self.invalidation_patcher = mock.patch(
72 self.invalidation_patcher = mock.patch(
73 'rhodecode.model.pull_request.ScmModel.mark_for_invalidation')
73 'rhodecode.model.pull_request.ScmModel.mark_for_invalidation')
74 self.invalidation_mock = self.invalidation_patcher.start()
74 self.invalidation_mock = self.invalidation_patcher.start()
75
75
76 self.pull_request = pr_util.create_pull_request(
76 self.pull_request = pr_util.create_pull_request(
77 mergeable=True, name_suffix=u'Δ…Δ‡')
77 mergeable=True, name_suffix=u'Δ…Δ‡')
78 self.source_commit = self.pull_request.source_ref_parts.commit_id
78 self.source_commit = self.pull_request.source_ref_parts.commit_id
79 self.target_commit = self.pull_request.target_ref_parts.commit_id
79 self.target_commit = self.pull_request.target_ref_parts.commit_id
80 self.workspace_id = 'pr-%s' % self.pull_request.pull_request_id
80 self.workspace_id = 'pr-%s' % self.pull_request.pull_request_id
81
81
82 @request.addfinalizer
82 @request.addfinalizer
83 def cleanup_pull_request():
83 def cleanup_pull_request():
84 calls = [mock.call(
84 calls = [mock.call(
85 self.pull_request, self.pull_request.author, 'create')]
85 self.pull_request, self.pull_request.author, 'create')]
86 self.hook_mock.assert_has_calls(calls)
86 self.hook_mock.assert_has_calls(calls)
87
87
88 self.workspace_remove_patcher.stop()
88 self.workspace_remove_patcher.stop()
89 self.merge_patcher.stop()
89 self.merge_patcher.stop()
90 self.comment_patcher.stop()
90 self.comment_patcher.stop()
91 self.notification_patcher.stop()
91 self.notification_patcher.stop()
92 self.helper_patcher.stop()
92 self.helper_patcher.stop()
93 self.hook_patcher.stop()
93 self.hook_patcher.stop()
94 self.invalidation_patcher.stop()
94 self.invalidation_patcher.stop()
95
95
96 return self.pull_request
96 return self.pull_request
97
97
98 def test_get_all(self, pull_request):
98 def test_get_all(self, pull_request):
99 prs = PullRequestModel().get_all(pull_request.target_repo)
99 prs = PullRequestModel().get_all(pull_request.target_repo)
100 assert isinstance(prs, list)
100 assert isinstance(prs, list)
101 assert len(prs) == 1
101 assert len(prs) == 1
102
102
103 def test_count_all(self, pull_request):
103 def test_count_all(self, pull_request):
104 pr_count = PullRequestModel().count_all(pull_request.target_repo)
104 pr_count = PullRequestModel().count_all(pull_request.target_repo)
105 assert pr_count == 1
105 assert pr_count == 1
106
106
107 def test_get_awaiting_review(self, pull_request):
107 def test_get_awaiting_review(self, pull_request):
108 prs = PullRequestModel().get_awaiting_review(pull_request.target_repo)
108 prs = PullRequestModel().get_awaiting_review(pull_request.target_repo)
109 assert isinstance(prs, list)
109 assert isinstance(prs, list)
110 assert len(prs) == 1
110 assert len(prs) == 1
111
111
112 def test_count_awaiting_review(self, pull_request):
112 def test_count_awaiting_review(self, pull_request):
113 pr_count = PullRequestModel().count_awaiting_review(
113 pr_count = PullRequestModel().count_awaiting_review(
114 pull_request.target_repo)
114 pull_request.target_repo)
115 assert pr_count == 1
115 assert pr_count == 1
116
116
117 def test_get_awaiting_my_review(self, pull_request):
117 def test_get_awaiting_my_review(self, pull_request):
118 PullRequestModel().update_reviewers(
118 PullRequestModel().update_reviewers(
119 pull_request, [(pull_request.author, ['author'])])
119 pull_request, [(pull_request.author, ['author'])])
120 prs = PullRequestModel().get_awaiting_my_review(
120 prs = PullRequestModel().get_awaiting_my_review(
121 pull_request.target_repo, user_id=pull_request.author.user_id)
121 pull_request.target_repo, user_id=pull_request.author.user_id)
122 assert isinstance(prs, list)
122 assert isinstance(prs, list)
123 assert len(prs) == 1
123 assert len(prs) == 1
124
124
125 def test_count_awaiting_my_review(self, pull_request):
125 def test_count_awaiting_my_review(self, pull_request):
126 PullRequestModel().update_reviewers(
126 PullRequestModel().update_reviewers(
127 pull_request, [(pull_request.author, ['author'])])
127 pull_request, [(pull_request.author, ['author'])])
128 pr_count = PullRequestModel().count_awaiting_my_review(
128 pr_count = PullRequestModel().count_awaiting_my_review(
129 pull_request.target_repo, user_id=pull_request.author.user_id)
129 pull_request.target_repo, user_id=pull_request.author.user_id)
130 assert pr_count == 1
130 assert pr_count == 1
131
131
132 def test_delete_calls_cleanup_merge(self, pull_request):
132 def test_delete_calls_cleanup_merge(self, pull_request):
133 PullRequestModel().delete(pull_request)
133 PullRequestModel().delete(pull_request)
134
134
135 self.workspace_remove_mock.assert_called_once_with(
135 self.workspace_remove_mock.assert_called_once_with(
136 self.workspace_id)
136 self.workspace_id)
137
137
138 def test_close_calls_cleanup_and_hook(self, pull_request):
138 def test_close_calls_cleanup_and_hook(self, pull_request):
139 PullRequestModel().close_pull_request(
139 PullRequestModel().close_pull_request(
140 pull_request, pull_request.author)
140 pull_request, pull_request.author)
141
141
142 self.workspace_remove_mock.assert_called_once_with(
142 self.workspace_remove_mock.assert_called_once_with(
143 self.workspace_id)
143 self.workspace_id)
144 self.hook_mock.assert_called_with(
144 self.hook_mock.assert_called_with(
145 self.pull_request, self.pull_request.author, 'close')
145 self.pull_request, self.pull_request.author, 'close')
146
146
147 def test_merge_status(self, pull_request):
147 def test_merge_status(self, pull_request):
148 self.merge_mock.return_value = MergeResponse(
148 self.merge_mock.return_value = MergeResponse(
149 True, False, None, MergeFailureReason.NONE)
149 True, False, None, MergeFailureReason.NONE)
150
150
151 assert pull_request._last_merge_source_rev is None
151 assert pull_request._last_merge_source_rev is None
152 assert pull_request._last_merge_target_rev is None
152 assert pull_request._last_merge_target_rev is None
153 assert pull_request._last_merge_status is None
153 assert pull_request._last_merge_status is None
154
154
155 status, msg = PullRequestModel().merge_status(pull_request)
155 status, msg = PullRequestModel().merge_status(pull_request)
156 assert status is True
156 assert status is True
157 assert msg.eval() == 'This pull request can be automatically merged.'
157 assert msg.eval() == 'This pull request can be automatically merged.'
158 self.merge_mock.assert_called_once_with(
158 self.merge_mock.assert_called_once_with(
159 pull_request.target_ref_parts,
159 pull_request.target_ref_parts,
160 pull_request.source_repo.scm_instance(),
160 pull_request.source_repo.scm_instance(),
161 pull_request.source_ref_parts, self.workspace_id, dry_run=True,
161 pull_request.source_ref_parts, self.workspace_id, dry_run=True,
162 use_rebase=False)
162 use_rebase=False)
163
163
164 assert pull_request._last_merge_source_rev == self.source_commit
164 assert pull_request._last_merge_source_rev == self.source_commit
165 assert pull_request._last_merge_target_rev == self.target_commit
165 assert pull_request._last_merge_target_rev == self.target_commit
166 assert pull_request._last_merge_status is MergeFailureReason.NONE
166 assert pull_request._last_merge_status is MergeFailureReason.NONE
167
167
168 self.merge_mock.reset_mock()
168 self.merge_mock.reset_mock()
169 status, msg = PullRequestModel().merge_status(pull_request)
169 status, msg = PullRequestModel().merge_status(pull_request)
170 assert status is True
170 assert status is True
171 assert msg.eval() == 'This pull request can be automatically merged.'
171 assert msg.eval() == 'This pull request can be automatically merged.'
172 assert self.merge_mock.called is False
172 assert self.merge_mock.called is False
173
173
174 def test_merge_status_known_failure(self, pull_request):
174 def test_merge_status_known_failure(self, pull_request):
175 self.merge_mock.return_value = MergeResponse(
175 self.merge_mock.return_value = MergeResponse(
176 False, False, None, MergeFailureReason.MERGE_FAILED)
176 False, False, None, MergeFailureReason.MERGE_FAILED)
177
177
178 assert pull_request._last_merge_source_rev is None
178 assert pull_request._last_merge_source_rev is None
179 assert pull_request._last_merge_target_rev is None
179 assert pull_request._last_merge_target_rev is None
180 assert pull_request._last_merge_status is None
180 assert pull_request._last_merge_status is None
181
181
182 status, msg = PullRequestModel().merge_status(pull_request)
182 status, msg = PullRequestModel().merge_status(pull_request)
183 assert status is False
183 assert status is False
184 assert (
184 assert (
185 msg.eval() ==
185 msg.eval() ==
186 'This pull request cannot be merged because of conflicts.')
186 'This pull request cannot be merged because of conflicts.')
187 self.merge_mock.assert_called_once_with(
187 self.merge_mock.assert_called_once_with(
188 pull_request.target_ref_parts,
188 pull_request.target_ref_parts,
189 pull_request.source_repo.scm_instance(),
189 pull_request.source_repo.scm_instance(),
190 pull_request.source_ref_parts, self.workspace_id, dry_run=True,
190 pull_request.source_ref_parts, self.workspace_id, dry_run=True,
191 use_rebase=False)
191 use_rebase=False)
192
192
193 assert pull_request._last_merge_source_rev == self.source_commit
193 assert pull_request._last_merge_source_rev == self.source_commit
194 assert pull_request._last_merge_target_rev == self.target_commit
194 assert pull_request._last_merge_target_rev == self.target_commit
195 assert (
195 assert (
196 pull_request._last_merge_status is MergeFailureReason.MERGE_FAILED)
196 pull_request._last_merge_status is MergeFailureReason.MERGE_FAILED)
197
197
198 self.merge_mock.reset_mock()
198 self.merge_mock.reset_mock()
199 status, msg = PullRequestModel().merge_status(pull_request)
199 status, msg = PullRequestModel().merge_status(pull_request)
200 assert status is False
200 assert status is False
201 assert (
201 assert (
202 msg.eval() ==
202 msg.eval() ==
203 'This pull request cannot be merged because of conflicts.')
203 'This pull request cannot be merged because of conflicts.')
204 assert self.merge_mock.called is False
204 assert self.merge_mock.called is False
205
205
206 def test_merge_status_unknown_failure(self, pull_request):
206 def test_merge_status_unknown_failure(self, pull_request):
207 self.merge_mock.return_value = MergeResponse(
207 self.merge_mock.return_value = MergeResponse(
208 False, False, None, MergeFailureReason.UNKNOWN)
208 False, False, None, MergeFailureReason.UNKNOWN)
209
209
210 assert pull_request._last_merge_source_rev is None
210 assert pull_request._last_merge_source_rev is None
211 assert pull_request._last_merge_target_rev is None
211 assert pull_request._last_merge_target_rev is None
212 assert pull_request._last_merge_status is None
212 assert pull_request._last_merge_status is None
213
213
214 status, msg = PullRequestModel().merge_status(pull_request)
214 status, msg = PullRequestModel().merge_status(pull_request)
215 assert status is False
215 assert status is False
216 assert msg.eval() == (
216 assert msg.eval() == (
217 'This pull request cannot be merged because of an unhandled'
217 'This pull request cannot be merged because of an unhandled'
218 ' exception.')
218 ' exception.')
219 self.merge_mock.assert_called_once_with(
219 self.merge_mock.assert_called_once_with(
220 pull_request.target_ref_parts,
220 pull_request.target_ref_parts,
221 pull_request.source_repo.scm_instance(),
221 pull_request.source_repo.scm_instance(),
222 pull_request.source_ref_parts, self.workspace_id, dry_run=True,
222 pull_request.source_ref_parts, self.workspace_id, dry_run=True,
223 use_rebase=False)
223 use_rebase=False)
224
224
225 assert pull_request._last_merge_source_rev is None
225 assert pull_request._last_merge_source_rev is None
226 assert pull_request._last_merge_target_rev is None
226 assert pull_request._last_merge_target_rev is None
227 assert pull_request._last_merge_status is None
227 assert pull_request._last_merge_status is None
228
228
229 self.merge_mock.reset_mock()
229 self.merge_mock.reset_mock()
230 status, msg = PullRequestModel().merge_status(pull_request)
230 status, msg = PullRequestModel().merge_status(pull_request)
231 assert status is False
231 assert status is False
232 assert msg.eval() == (
232 assert msg.eval() == (
233 'This pull request cannot be merged because of an unhandled'
233 'This pull request cannot be merged because of an unhandled'
234 ' exception.')
234 ' exception.')
235 assert self.merge_mock.called is True
235 assert self.merge_mock.called is True
236
236
237 def test_merge_status_when_target_is_locked(self, pull_request):
237 def test_merge_status_when_target_is_locked(self, pull_request):
238 pull_request.target_repo.locked = [1, u'12345.50', 'lock_web']
238 pull_request.target_repo.locked = [1, u'12345.50', 'lock_web']
239 status, msg = PullRequestModel().merge_status(pull_request)
239 status, msg = PullRequestModel().merge_status(pull_request)
240 assert status is False
240 assert status is False
241 assert msg.eval() == (
241 assert msg.eval() == (
242 'This pull request cannot be merged because the target repository'
242 'This pull request cannot be merged because the target repository'
243 ' is locked.')
243 ' is locked.')
244
244
245 def test_merge_status_requirements_check_target(self, pull_request):
245 def test_merge_status_requirements_check_target(self, pull_request):
246
246
247 def has_largefiles(self, repo):
247 def has_largefiles(self, repo):
248 return repo == pull_request.source_repo
248 return repo == pull_request.source_repo
249
249
250 patcher = mock.patch.object(
250 patcher = mock.patch.object(
251 PullRequestModel, '_has_largefiles', has_largefiles)
251 PullRequestModel, '_has_largefiles', has_largefiles)
252 with patcher:
252 with patcher:
253 status, msg = PullRequestModel().merge_status(pull_request)
253 status, msg = PullRequestModel().merge_status(pull_request)
254
254
255 assert status is False
255 assert status is False
256 assert msg == 'Target repository large files support is disabled.'
256 assert msg == 'Target repository large files support is disabled.'
257
257
258 def test_merge_status_requirements_check_source(self, pull_request):
258 def test_merge_status_requirements_check_source(self, pull_request):
259
259
260 def has_largefiles(self, repo):
260 def has_largefiles(self, repo):
261 return repo == pull_request.target_repo
261 return repo == pull_request.target_repo
262
262
263 patcher = mock.patch.object(
263 patcher = mock.patch.object(
264 PullRequestModel, '_has_largefiles', has_largefiles)
264 PullRequestModel, '_has_largefiles', has_largefiles)
265 with patcher:
265 with patcher:
266 status, msg = PullRequestModel().merge_status(pull_request)
266 status, msg = PullRequestModel().merge_status(pull_request)
267
267
268 assert status is False
268 assert status is False
269 assert msg == 'Source repository large files support is disabled.'
269 assert msg == 'Source repository large files support is disabled.'
270
270
271 def test_merge(self, pull_request, merge_extras):
271 def test_merge(self, pull_request, merge_extras):
272 user = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
272 user = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
273 merge_ref = Reference(
273 merge_ref = Reference(
274 'type', 'name', '6126b7bfcc82ad2d3deaee22af926b082ce54cc6')
274 'type', 'name', '6126b7bfcc82ad2d3deaee22af926b082ce54cc6')
275 self.merge_mock.return_value = MergeResponse(
275 self.merge_mock.return_value = MergeResponse(
276 True, True, merge_ref, MergeFailureReason.NONE)
276 True, True, merge_ref, MergeFailureReason.NONE)
277
277
278 merge_extras['repository'] = pull_request.target_repo.repo_name
278 merge_extras['repository'] = pull_request.target_repo.repo_name
279 PullRequestModel().merge(
279 PullRequestModel().merge(
280 pull_request, pull_request.author, extras=merge_extras)
280 pull_request, pull_request.author, extras=merge_extras)
281
281
282 message = (
282 message = (
283 u'Merge pull request #{pr_id} from {source_repo} {source_ref_name}'
283 u'Merge pull request #{pr_id} from {source_repo} {source_ref_name}'
284 u'\n\n {pr_title}'.format(
284 u'\n\n {pr_title}'.format(
285 pr_id=pull_request.pull_request_id,
285 pr_id=pull_request.pull_request_id,
286 source_repo=safe_unicode(
286 source_repo=safe_unicode(
287 pull_request.source_repo.scm_instance().name),
287 pull_request.source_repo.scm_instance().name),
288 source_ref_name=pull_request.source_ref_parts.name,
288 source_ref_name=pull_request.source_ref_parts.name,
289 pr_title=safe_unicode(pull_request.title)
289 pr_title=safe_unicode(pull_request.title)
290 )
290 )
291 )
291 )
292 self.merge_mock.assert_called_once_with(
292 self.merge_mock.assert_called_once_with(
293 pull_request.target_ref_parts,
293 pull_request.target_ref_parts,
294 pull_request.source_repo.scm_instance(),
294 pull_request.source_repo.scm_instance(),
295 pull_request.source_ref_parts, self.workspace_id,
295 pull_request.source_ref_parts, self.workspace_id,
296 user_name=user.username, user_email=user.email, message=message,
296 user_name=user.username, user_email=user.email, message=message,
297 use_rebase=False
297 use_rebase=False
298 )
298 )
299 self.invalidation_mock.assert_called_once_with(
299 self.invalidation_mock.assert_called_once_with(
300 pull_request.target_repo.repo_name)
300 pull_request.target_repo.repo_name)
301
301
302 self.hook_mock.assert_called_with(
302 self.hook_mock.assert_called_with(
303 self.pull_request, self.pull_request.author, 'merge')
303 self.pull_request, self.pull_request.author, 'merge')
304
304
305 pull_request = PullRequest.get(pull_request.pull_request_id)
305 pull_request = PullRequest.get(pull_request.pull_request_id)
306 assert (
306 assert (
307 pull_request.merge_rev ==
307 pull_request.merge_rev ==
308 '6126b7bfcc82ad2d3deaee22af926b082ce54cc6')
308 '6126b7bfcc82ad2d3deaee22af926b082ce54cc6')
309
309
310 def test_merge_failed(self, pull_request, merge_extras):
310 def test_merge_failed(self, pull_request, merge_extras):
311 user = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
311 user = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
312 merge_ref = Reference(
312 merge_ref = Reference(
313 'type', 'name', '6126b7bfcc82ad2d3deaee22af926b082ce54cc6')
313 'type', 'name', '6126b7bfcc82ad2d3deaee22af926b082ce54cc6')
314 self.merge_mock.return_value = MergeResponse(
314 self.merge_mock.return_value = MergeResponse(
315 False, False, merge_ref, MergeFailureReason.MERGE_FAILED)
315 False, False, merge_ref, MergeFailureReason.MERGE_FAILED)
316
316
317 merge_extras['repository'] = pull_request.target_repo.repo_name
317 merge_extras['repository'] = pull_request.target_repo.repo_name
318 PullRequestModel().merge(
318 PullRequestModel().merge(
319 pull_request, pull_request.author, extras=merge_extras)
319 pull_request, pull_request.author, extras=merge_extras)
320
320
321 message = (
321 message = (
322 u'Merge pull request #{pr_id} from {source_repo} {source_ref_name}'
322 u'Merge pull request #{pr_id} from {source_repo} {source_ref_name}'
323 u'\n\n {pr_title}'.format(
323 u'\n\n {pr_title}'.format(
324 pr_id=pull_request.pull_request_id,
324 pr_id=pull_request.pull_request_id,
325 source_repo=safe_unicode(
325 source_repo=safe_unicode(
326 pull_request.source_repo.scm_instance().name),
326 pull_request.source_repo.scm_instance().name),
327 source_ref_name=pull_request.source_ref_parts.name,
327 source_ref_name=pull_request.source_ref_parts.name,
328 pr_title=safe_unicode(pull_request.title)
328 pr_title=safe_unicode(pull_request.title)
329 )
329 )
330 )
330 )
331 self.merge_mock.assert_called_once_with(
331 self.merge_mock.assert_called_once_with(
332 pull_request.target_ref_parts,
332 pull_request.target_ref_parts,
333 pull_request.source_repo.scm_instance(),
333 pull_request.source_repo.scm_instance(),
334 pull_request.source_ref_parts, self.workspace_id,
334 pull_request.source_ref_parts, self.workspace_id,
335 user_name=user.username, user_email=user.email, message=message,
335 user_name=user.username, user_email=user.email, message=message,
336 use_rebase=False
336 use_rebase=False
337 )
337 )
338
338
339 pull_request = PullRequest.get(pull_request.pull_request_id)
339 pull_request = PullRequest.get(pull_request.pull_request_id)
340 assert self.invalidation_mock.called is False
340 assert self.invalidation_mock.called is False
341 assert pull_request.merge_rev is None
341 assert pull_request.merge_rev is None
342
342
343 def test_get_commit_ids(self, pull_request):
343 def test_get_commit_ids(self, pull_request):
344 # The PR has been not merget yet, so expect an exception
344 # The PR has been not merget yet, so expect an exception
345 with pytest.raises(ValueError):
345 with pytest.raises(ValueError):
346 PullRequestModel()._get_commit_ids(pull_request)
346 PullRequestModel()._get_commit_ids(pull_request)
347
347
348 # Merge revision is in the revisions list
348 # Merge revision is in the revisions list
349 pull_request.merge_rev = pull_request.revisions[0]
349 pull_request.merge_rev = pull_request.revisions[0]
350 commit_ids = PullRequestModel()._get_commit_ids(pull_request)
350 commit_ids = PullRequestModel()._get_commit_ids(pull_request)
351 assert commit_ids == pull_request.revisions
351 assert commit_ids == pull_request.revisions
352
352
353 # Merge revision is not in the revisions list
353 # Merge revision is not in the revisions list
354 pull_request.merge_rev = 'f000' * 10
354 pull_request.merge_rev = 'f000' * 10
355 commit_ids = PullRequestModel()._get_commit_ids(pull_request)
355 commit_ids = PullRequestModel()._get_commit_ids(pull_request)
356 assert commit_ids == pull_request.revisions + [pull_request.merge_rev]
356 assert commit_ids == pull_request.revisions + [pull_request.merge_rev]
357
357
358 def test_get_diff_from_pr_version(self, pull_request):
358 def test_get_diff_from_pr_version(self, pull_request):
359 diff = PullRequestModel()._get_diff_from_pr_or_version(
359 diff = PullRequestModel()._get_diff_from_pr_or_version(
360 pull_request, context=6)
360 pull_request, context=6)
361 assert 'file_1' in diff.raw
361 assert 'file_1' in diff.raw
362
362
363 def test_generate_title_returns_unicode(self):
363 def test_generate_title_returns_unicode(self):
364 title = PullRequestModel().generate_pullrequest_title(
364 title = PullRequestModel().generate_pullrequest_title(
365 source='source-dummy',
365 source='source-dummy',
366 source_ref='source-ref-dummy',
366 source_ref='source-ref-dummy',
367 target='target-dummy',
367 target='target-dummy',
368 )
368 )
369 assert type(title) == unicode
369 assert type(title) == unicode
370
370
371
371
372 class TestIntegrationMerge(object):
372 class TestIntegrationMerge(object):
373 @pytest.mark.parametrize('extra_config', (
373 @pytest.mark.parametrize('extra_config', (
374 {'vcs.hooks.protocol': 'http', 'vcs.hooks.direct_calls': False},
374 {'vcs.hooks.protocol': 'http', 'vcs.hooks.direct_calls': False},
375 {'vcs.hooks.protocol': 'Pyro4', 'vcs.hooks.direct_calls': False},
375 {'vcs.hooks.protocol': 'Pyro4', 'vcs.hooks.direct_calls': False},
376 ))
376 ))
377 def test_merge_triggers_push_hooks(
377 def test_merge_triggers_push_hooks(
378 self, pr_util, user_admin, capture_rcextensions, merge_extras,
378 self, pr_util, user_admin, capture_rcextensions, merge_extras,
379 extra_config):
379 extra_config):
380 pull_request = pr_util.create_pull_request(
380 pull_request = pr_util.create_pull_request(
381 approved=True, mergeable=True)
381 approved=True, mergeable=True)
382 # TODO: johbo: Needed for sqlite, try to find an automatic way for it
382 # TODO: johbo: Needed for sqlite, try to find an automatic way for it
383 merge_extras['repository'] = pull_request.target_repo.repo_name
383 merge_extras['repository'] = pull_request.target_repo.repo_name
384 Session().commit()
384 Session().commit()
385
385
386 with mock.patch.dict(rhodecode.CONFIG, extra_config, clear=False):
386 with mock.patch.dict(rhodecode.CONFIG, extra_config, clear=False):
387 merge_state = PullRequestModel().merge(
387 merge_state = PullRequestModel().merge(
388 pull_request, user_admin, extras=merge_extras)
388 pull_request, user_admin, extras=merge_extras)
389
389
390 assert merge_state.executed
390 assert merge_state.executed
391 assert 'pre_push' in capture_rcextensions
391 assert 'pre_push' in capture_rcextensions
392 assert 'post_push' in capture_rcextensions
392 assert 'post_push' in capture_rcextensions
393
393
394 def test_merge_can_be_rejected_by_pre_push_hook(
394 def test_merge_can_be_rejected_by_pre_push_hook(
395 self, pr_util, user_admin, capture_rcextensions, merge_extras):
395 self, pr_util, user_admin, capture_rcextensions, merge_extras):
396 pull_request = pr_util.create_pull_request(
396 pull_request = pr_util.create_pull_request(
397 approved=True, mergeable=True)
397 approved=True, mergeable=True)
398 # TODO: johbo: Needed for sqlite, try to find an automatic way for it
398 # TODO: johbo: Needed for sqlite, try to find an automatic way for it
399 merge_extras['repository'] = pull_request.target_repo.repo_name
399 merge_extras['repository'] = pull_request.target_repo.repo_name
400 Session().commit()
400 Session().commit()
401
401
402 with mock.patch('rhodecode.EXTENSIONS.PRE_PUSH_HOOK') as pre_pull:
402 with mock.patch('rhodecode.EXTENSIONS.PRE_PUSH_HOOK') as pre_pull:
403 pre_pull.side_effect = RepositoryError("Disallow push!")
403 pre_pull.side_effect = RepositoryError("Disallow push!")
404 merge_status = PullRequestModel().merge(
404 merge_status = PullRequestModel().merge(
405 pull_request, user_admin, extras=merge_extras)
405 pull_request, user_admin, extras=merge_extras)
406
406
407 assert not merge_status.executed
407 assert not merge_status.executed
408 assert 'pre_push' not in capture_rcextensions
408 assert 'pre_push' not in capture_rcextensions
409 assert 'post_push' not in capture_rcextensions
409 assert 'post_push' not in capture_rcextensions
410
410
411 def test_merge_fails_if_target_is_locked(
411 def test_merge_fails_if_target_is_locked(
412 self, pr_util, user_regular, merge_extras):
412 self, pr_util, user_regular, merge_extras):
413 pull_request = pr_util.create_pull_request(
413 pull_request = pr_util.create_pull_request(
414 approved=True, mergeable=True)
414 approved=True, mergeable=True)
415 locked_by = [user_regular.user_id + 1, 12345.50, 'lock_web']
415 locked_by = [user_regular.user_id + 1, 12345.50, 'lock_web']
416 pull_request.target_repo.locked = locked_by
416 pull_request.target_repo.locked = locked_by
417 # TODO: johbo: Check if this can work based on the database, currently
417 # TODO: johbo: Check if this can work based on the database, currently
418 # all data is pre-computed, that's why just updating the DB is not
418 # all data is pre-computed, that's why just updating the DB is not
419 # enough.
419 # enough.
420 merge_extras['locked_by'] = locked_by
420 merge_extras['locked_by'] = locked_by
421 merge_extras['repository'] = pull_request.target_repo.repo_name
421 merge_extras['repository'] = pull_request.target_repo.repo_name
422 # TODO: johbo: Needed for sqlite, try to find an automatic way for it
422 # TODO: johbo: Needed for sqlite, try to find an automatic way for it
423 Session().commit()
423 Session().commit()
424 merge_status = PullRequestModel().merge(
424 merge_status = PullRequestModel().merge(
425 pull_request, user_regular, extras=merge_extras)
425 pull_request, user_regular, extras=merge_extras)
426 assert not merge_status.executed
426 assert not merge_status.executed
427
427
428
428
429 @pytest.mark.parametrize('use_outdated, inlines_count, outdated_count', [
429 @pytest.mark.parametrize('use_outdated, inlines_count, outdated_count', [
430 (False, 1, 0),
430 (False, 1, 0),
431 (True, 0, 1),
431 (True, 0, 1),
432 ])
432 ])
433 def test_outdated_comments(
433 def test_outdated_comments(
434 pr_util, use_outdated, inlines_count, outdated_count):
434 pr_util, use_outdated, inlines_count, outdated_count):
435 pull_request = pr_util.create_pull_request()
435 pull_request = pr_util.create_pull_request()
436 pr_util.create_inline_comment(file_path='not_in_updated_diff')
436 pr_util.create_inline_comment(file_path='not_in_updated_diff')
437
437
438 with outdated_comments_patcher(use_outdated) as outdated_comment_mock:
438 with outdated_comments_patcher(use_outdated) as outdated_comment_mock:
439 pr_util.add_one_commit()
439 pr_util.add_one_commit()
440 assert_inline_comments(
440 assert_inline_comments(
441 pull_request, visible=inlines_count, outdated=outdated_count)
441 pull_request, visible=inlines_count, outdated=outdated_count)
442 outdated_comment_mock.assert_called_with(pull_request)
442 outdated_comment_mock.assert_called_with(pull_request)
443
443
444
444
445 @pytest.fixture
445 @pytest.fixture
446 def merge_extras(user_regular):
446 def merge_extras(user_regular):
447 """
447 """
448 Context for the vcs operation when running a merge.
448 Context for the vcs operation when running a merge.
449 """
449 """
450 extras = {
450 extras = {
451 'ip': '127.0.0.1',
451 'ip': '127.0.0.1',
452 'username': user_regular.username,
452 'username': user_regular.username,
453 'action': 'push',
453 'action': 'push',
454 'repository': 'fake_target_repo_name',
454 'repository': 'fake_target_repo_name',
455 'scm': 'git',
455 'scm': 'git',
456 'config': 'fake_config_ini_path',
456 'config': 'fake_config_ini_path',
457 'make_lock': None,
457 'make_lock': None,
458 'locked_by': [None, None, None],
458 'locked_by': [None, None, None],
459 'server_url': 'http://test.example.com:5000',
459 'server_url': 'http://test.example.com:5000',
460 'hooks': ['push', 'pull'],
460 'hooks': ['push', 'pull'],
461 'is_shadow_repo': False,
461 'is_shadow_repo': False,
462 }
462 }
463 return extras
463 return extras
464
464
465
465
466 class TestUpdateCommentHandling(object):
466 class TestUpdateCommentHandling(object):
467
467
468 @pytest.fixture(autouse=True, scope='class')
468 @pytest.fixture(autouse=True, scope='class')
469 def enable_outdated_comments(self, request, pylonsapp):
469 def enable_outdated_comments(self, request, pylonsapp):
470 config_patch = mock.patch.dict(
470 config_patch = mock.patch.dict(
471 'rhodecode.CONFIG', {'rhodecode_use_outdated_comments': True})
471 'rhodecode.CONFIG', {'rhodecode_use_outdated_comments': True})
472 config_patch.start()
472 config_patch.start()
473
473
474 @request.addfinalizer
474 @request.addfinalizer
475 def cleanup():
475 def cleanup():
476 config_patch.stop()
476 config_patch.stop()
477
477
478 def test_comment_stays_unflagged_on_unchanged_diff(self, pr_util):
478 def test_comment_stays_unflagged_on_unchanged_diff(self, pr_util):
479 commits = [
479 commits = [
480 {'message': 'a'},
480 {'message': 'a'},
481 {'message': 'b', 'added': [FileNode('file_b', 'test_content\n')]},
481 {'message': 'b', 'added': [FileNode('file_b', 'test_content\n')]},
482 {'message': 'c', 'added': [FileNode('file_c', 'test_content\n')]},
482 {'message': 'c', 'added': [FileNode('file_c', 'test_content\n')]},
483 ]
483 ]
484 pull_request = pr_util.create_pull_request(
484 pull_request = pr_util.create_pull_request(
485 commits=commits, target_head='a', source_head='b', revisions=['b'])
485 commits=commits, target_head='a', source_head='b', revisions=['b'])
486 pr_util.create_inline_comment(file_path='file_b')
486 pr_util.create_inline_comment(file_path='file_b')
487 pr_util.add_one_commit(head='c')
487 pr_util.add_one_commit(head='c')
488
488
489 assert_inline_comments(pull_request, visible=1, outdated=0)
489 assert_inline_comments(pull_request, visible=1, outdated=0)
490
490
491 def test_comment_stays_unflagged_on_change_above(self, pr_util):
491 def test_comment_stays_unflagged_on_change_above(self, pr_util):
492 original_content = ''.join(
492 original_content = ''.join(
493 ['line {}\n'.format(x) for x in range(1, 11)])
493 ['line {}\n'.format(x) for x in range(1, 11)])
494 updated_content = 'new_line_at_top\n' + original_content
494 updated_content = 'new_line_at_top\n' + original_content
495 commits = [
495 commits = [
496 {'message': 'a'},
496 {'message': 'a'},
497 {'message': 'b', 'added': [FileNode('file_b', original_content)]},
497 {'message': 'b', 'added': [FileNode('file_b', original_content)]},
498 {'message': 'c', 'changed': [FileNode('file_b', updated_content)]},
498 {'message': 'c', 'changed': [FileNode('file_b', updated_content)]},
499 ]
499 ]
500 pull_request = pr_util.create_pull_request(
500 pull_request = pr_util.create_pull_request(
501 commits=commits, target_head='a', source_head='b', revisions=['b'])
501 commits=commits, target_head='a', source_head='b', revisions=['b'])
502
502
503 with outdated_comments_patcher():
503 with outdated_comments_patcher():
504 comment = pr_util.create_inline_comment(
504 comment = pr_util.create_inline_comment(
505 line_no=u'n8', file_path='file_b')
505 line_no=u'n8', file_path='file_b')
506 pr_util.add_one_commit(head='c')
506 pr_util.add_one_commit(head='c')
507
507
508 assert_inline_comments(pull_request, visible=1, outdated=0)
508 assert_inline_comments(pull_request, visible=1, outdated=0)
509 assert comment.line_no == u'n9'
509 assert comment.line_no == u'n9'
510
510
511 def test_comment_stays_unflagged_on_change_below(self, pr_util):
511 def test_comment_stays_unflagged_on_change_below(self, pr_util):
512 original_content = ''.join(['line {}\n'.format(x) for x in range(10)])
512 original_content = ''.join(['line {}\n'.format(x) for x in range(10)])
513 updated_content = original_content + 'new_line_at_end\n'
513 updated_content = original_content + 'new_line_at_end\n'
514 commits = [
514 commits = [
515 {'message': 'a'},
515 {'message': 'a'},
516 {'message': 'b', 'added': [FileNode('file_b', original_content)]},
516 {'message': 'b', 'added': [FileNode('file_b', original_content)]},
517 {'message': 'c', 'changed': [FileNode('file_b', updated_content)]},
517 {'message': 'c', 'changed': [FileNode('file_b', updated_content)]},
518 ]
518 ]
519 pull_request = pr_util.create_pull_request(
519 pull_request = pr_util.create_pull_request(
520 commits=commits, target_head='a', source_head='b', revisions=['b'])
520 commits=commits, target_head='a', source_head='b', revisions=['b'])
521 pr_util.create_inline_comment(file_path='file_b')
521 pr_util.create_inline_comment(file_path='file_b')
522 pr_util.add_one_commit(head='c')
522 pr_util.add_one_commit(head='c')
523
523
524 assert_inline_comments(pull_request, visible=1, outdated=0)
524 assert_inline_comments(pull_request, visible=1, outdated=0)
525
525
526 @pytest.mark.parametrize('line_no', ['n4', 'o4', 'n10', 'o9'])
526 @pytest.mark.parametrize('line_no', ['n4', 'o4', 'n10', 'o9'])
527 def test_comment_flagged_on_change_around_context(self, pr_util, line_no):
527 def test_comment_flagged_on_change_around_context(self, pr_util, line_no):
528 base_lines = ['line {}\n'.format(x) for x in range(1, 13)]
528 base_lines = ['line {}\n'.format(x) for x in range(1, 13)]
529 change_lines = list(base_lines)
529 change_lines = list(base_lines)
530 change_lines.insert(6, 'line 6a added\n')
530 change_lines.insert(6, 'line 6a added\n')
531
531
532 # Changes on the last line of sight
532 # Changes on the last line of sight
533 update_lines = list(change_lines)
533 update_lines = list(change_lines)
534 update_lines[0] = 'line 1 changed\n'
534 update_lines[0] = 'line 1 changed\n'
535 update_lines[-1] = 'line 12 changed\n'
535 update_lines[-1] = 'line 12 changed\n'
536
536
537 def file_b(lines):
537 def file_b(lines):
538 return FileNode('file_b', ''.join(lines))
538 return FileNode('file_b', ''.join(lines))
539
539
540 commits = [
540 commits = [
541 {'message': 'a', 'added': [file_b(base_lines)]},
541 {'message': 'a', 'added': [file_b(base_lines)]},
542 {'message': 'b', 'changed': [file_b(change_lines)]},
542 {'message': 'b', 'changed': [file_b(change_lines)]},
543 {'message': 'c', 'changed': [file_b(update_lines)]},
543 {'message': 'c', 'changed': [file_b(update_lines)]},
544 ]
544 ]
545
545
546 pull_request = pr_util.create_pull_request(
546 pull_request = pr_util.create_pull_request(
547 commits=commits, target_head='a', source_head='b', revisions=['b'])
547 commits=commits, target_head='a', source_head='b', revisions=['b'])
548 pr_util.create_inline_comment(line_no=line_no, file_path='file_b')
548 pr_util.create_inline_comment(line_no=line_no, file_path='file_b')
549
549
550 with outdated_comments_patcher():
550 with outdated_comments_patcher():
551 pr_util.add_one_commit(head='c')
551 pr_util.add_one_commit(head='c')
552 assert_inline_comments(pull_request, visible=0, outdated=1)
552 assert_inline_comments(pull_request, visible=0, outdated=1)
553
553
554 @pytest.mark.parametrize("change, content", [
554 @pytest.mark.parametrize("change, content", [
555 ('changed', 'changed\n'),
555 ('changed', 'changed\n'),
556 ('removed', ''),
556 ('removed', ''),
557 ], ids=['changed', 'removed'])
557 ], ids=['changed', 'removed'])
558 def test_comment_flagged_on_change(self, pr_util, change, content):
558 def test_comment_flagged_on_change(self, pr_util, change, content):
559 commits = [
559 commits = [
560 {'message': 'a'},
560 {'message': 'a'},
561 {'message': 'b', 'added': [FileNode('file_b', 'test_content\n')]},
561 {'message': 'b', 'added': [FileNode('file_b', 'test_content\n')]},
562 {'message': 'c', change: [FileNode('file_b', content)]},
562 {'message': 'c', change: [FileNode('file_b', content)]},
563 ]
563 ]
564 pull_request = pr_util.create_pull_request(
564 pull_request = pr_util.create_pull_request(
565 commits=commits, target_head='a', source_head='b', revisions=['b'])
565 commits=commits, target_head='a', source_head='b', revisions=['b'])
566 pr_util.create_inline_comment(file_path='file_b')
566 pr_util.create_inline_comment(file_path='file_b')
567
567
568 with outdated_comments_patcher():
568 with outdated_comments_patcher():
569 pr_util.add_one_commit(head='c')
569 pr_util.add_one_commit(head='c')
570 assert_inline_comments(pull_request, visible=0, outdated=1)
570 assert_inline_comments(pull_request, visible=0, outdated=1)
571
571
572
572
573 class TestUpdateChangedFiles(object):
573 class TestUpdateChangedFiles(object):
574
574
575 def test_no_changes_on_unchanged_diff(self, pr_util):
575 def test_no_changes_on_unchanged_diff(self, pr_util):
576 commits = [
576 commits = [
577 {'message': 'a'},
577 {'message': 'a'},
578 {'message': 'b',
578 {'message': 'b',
579 'added': [FileNode('file_b', 'test_content b\n')]},
579 'added': [FileNode('file_b', 'test_content b\n')]},
580 {'message': 'c',
580 {'message': 'c',
581 'added': [FileNode('file_c', 'test_content c\n')]},
581 'added': [FileNode('file_c', 'test_content c\n')]},
582 ]
582 ]
583 # open a PR from a to b, adding file_b
583 # open a PR from a to b, adding file_b
584 pull_request = pr_util.create_pull_request(
584 pull_request = pr_util.create_pull_request(
585 commits=commits, target_head='a', source_head='b', revisions=['b'],
585 commits=commits, target_head='a', source_head='b', revisions=['b'],
586 name_suffix='per-file-review')
586 name_suffix='per-file-review')
587
587
588 # modify PR adding new file file_c
588 # modify PR adding new file file_c
589 pr_util.add_one_commit(head='c')
589 pr_util.add_one_commit(head='c')
590
590
591 assert_pr_file_changes(
591 assert_pr_file_changes(
592 pull_request,
592 pull_request,
593 added=['file_c'],
593 added=['file_c'],
594 modified=[],
594 modified=[],
595 removed=[])
595 removed=[])
596
596
597 def test_modify_and_undo_modification_diff(self, pr_util):
597 def test_modify_and_undo_modification_diff(self, pr_util):
598 commits = [
598 commits = [
599 {'message': 'a'},
599 {'message': 'a'},
600 {'message': 'b',
600 {'message': 'b',
601 'added': [FileNode('file_b', 'test_content b\n')]},
601 'added': [FileNode('file_b', 'test_content b\n')]},
602 {'message': 'c',
602 {'message': 'c',
603 'changed': [FileNode('file_b', 'test_content b modified\n')]},
603 'changed': [FileNode('file_b', 'test_content b modified\n')]},
604 {'message': 'd',
604 {'message': 'd',
605 'changed': [FileNode('file_b', 'test_content b\n')]},
605 'changed': [FileNode('file_b', 'test_content b\n')]},
606 ]
606 ]
607 # open a PR from a to b, adding file_b
607 # open a PR from a to b, adding file_b
608 pull_request = pr_util.create_pull_request(
608 pull_request = pr_util.create_pull_request(
609 commits=commits, target_head='a', source_head='b', revisions=['b'],
609 commits=commits, target_head='a', source_head='b', revisions=['b'],
610 name_suffix='per-file-review')
610 name_suffix='per-file-review')
611
611
612 # modify PR modifying file file_b
612 # modify PR modifying file file_b
613 pr_util.add_one_commit(head='c')
613 pr_util.add_one_commit(head='c')
614
614
615 assert_pr_file_changes(
615 assert_pr_file_changes(
616 pull_request,
616 pull_request,
617 added=[],
617 added=[],
618 modified=['file_b'],
618 modified=['file_b'],
619 removed=[])
619 removed=[])
620
620
621 # move the head again to d, which rollbacks change,
621 # move the head again to d, which rollbacks change,
622 # meaning we should indicate no changes
622 # meaning we should indicate no changes
623 pr_util.add_one_commit(head='d')
623 pr_util.add_one_commit(head='d')
624
624
625 assert_pr_file_changes(
625 assert_pr_file_changes(
626 pull_request,
626 pull_request,
627 added=[],
627 added=[],
628 modified=[],
628 modified=[],
629 removed=[])
629 removed=[])
630
630
631 def test_updated_all_files_in_pr(self, pr_util):
631 def test_updated_all_files_in_pr(self, pr_util):
632 commits = [
632 commits = [
633 {'message': 'a'},
633 {'message': 'a'},
634 {'message': 'b', 'added': [
634 {'message': 'b', 'added': [
635 FileNode('file_a', 'test_content a\n'),
635 FileNode('file_a', 'test_content a\n'),
636 FileNode('file_b', 'test_content b\n'),
636 FileNode('file_b', 'test_content b\n'),
637 FileNode('file_c', 'test_content c\n')]},
637 FileNode('file_c', 'test_content c\n')]},
638 {'message': 'c', 'changed': [
638 {'message': 'c', 'changed': [
639 FileNode('file_a', 'test_content a changed\n'),
639 FileNode('file_a', 'test_content a changed\n'),
640 FileNode('file_b', 'test_content b changed\n'),
640 FileNode('file_b', 'test_content b changed\n'),
641 FileNode('file_c', 'test_content c changed\n')]},
641 FileNode('file_c', 'test_content c changed\n')]},
642 ]
642 ]
643 # open a PR from a to b, changing 3 files
643 # open a PR from a to b, changing 3 files
644 pull_request = pr_util.create_pull_request(
644 pull_request = pr_util.create_pull_request(
645 commits=commits, target_head='a', source_head='b', revisions=['b'],
645 commits=commits, target_head='a', source_head='b', revisions=['b'],
646 name_suffix='per-file-review')
646 name_suffix='per-file-review')
647
647
648 pr_util.add_one_commit(head='c')
648 pr_util.add_one_commit(head='c')
649
649
650 assert_pr_file_changes(
650 assert_pr_file_changes(
651 pull_request,
651 pull_request,
652 added=[],
652 added=[],
653 modified=['file_a', 'file_b', 'file_c'],
653 modified=['file_a', 'file_b', 'file_c'],
654 removed=[])
654 removed=[])
655
655
656 def test_updated_and_removed_all_files_in_pr(self, pr_util):
656 def test_updated_and_removed_all_files_in_pr(self, pr_util):
657 commits = [
657 commits = [
658 {'message': 'a'},
658 {'message': 'a'},
659 {'message': 'b', 'added': [
659 {'message': 'b', 'added': [
660 FileNode('file_a', 'test_content a\n'),
660 FileNode('file_a', 'test_content a\n'),
661 FileNode('file_b', 'test_content b\n'),
661 FileNode('file_b', 'test_content b\n'),
662 FileNode('file_c', 'test_content c\n')]},
662 FileNode('file_c', 'test_content c\n')]},
663 {'message': 'c', 'removed': [
663 {'message': 'c', 'removed': [
664 FileNode('file_a', 'test_content a changed\n'),
664 FileNode('file_a', 'test_content a changed\n'),
665 FileNode('file_b', 'test_content b changed\n'),
665 FileNode('file_b', 'test_content b changed\n'),
666 FileNode('file_c', 'test_content c changed\n')]},
666 FileNode('file_c', 'test_content c changed\n')]},
667 ]
667 ]
668 # open a PR from a to b, removing 3 files
668 # open a PR from a to b, removing 3 files
669 pull_request = pr_util.create_pull_request(
669 pull_request = pr_util.create_pull_request(
670 commits=commits, target_head='a', source_head='b', revisions=['b'],
670 commits=commits, target_head='a', source_head='b', revisions=['b'],
671 name_suffix='per-file-review')
671 name_suffix='per-file-review')
672
672
673 pr_util.add_one_commit(head='c')
673 pr_util.add_one_commit(head='c')
674
674
675 assert_pr_file_changes(
675 assert_pr_file_changes(
676 pull_request,
676 pull_request,
677 added=[],
677 added=[],
678 modified=[],
678 modified=[],
679 removed=['file_a', 'file_b', 'file_c'])
679 removed=['file_a', 'file_b', 'file_c'])
680
680
681
681
682 def test_update_writes_snapshot_into_pull_request_version(pr_util):
682 def test_update_writes_snapshot_into_pull_request_version(pr_util):
683 model = PullRequestModel()
683 model = PullRequestModel()
684 pull_request = pr_util.create_pull_request()
684 pull_request = pr_util.create_pull_request()
685 pr_util.update_source_repository()
685 pr_util.update_source_repository()
686
686
687 model.update_commits(pull_request)
687 model.update_commits(pull_request)
688
688
689 # Expect that it has a version entry now
689 # Expect that it has a version entry now
690 assert len(model.get_versions(pull_request)) == 1
690 assert len(model.get_versions(pull_request)) == 1
691
691
692
692
693 def test_update_skips_new_version_if_unchanged(pr_util):
693 def test_update_skips_new_version_if_unchanged(pr_util):
694 pull_request = pr_util.create_pull_request()
694 pull_request = pr_util.create_pull_request()
695 model = PullRequestModel()
695 model = PullRequestModel()
696 model.update_commits(pull_request)
696 model.update_commits(pull_request)
697
697
698 # Expect that it still has no versions
698 # Expect that it still has no versions
699 assert len(model.get_versions(pull_request)) == 0
699 assert len(model.get_versions(pull_request)) == 0
700
700
701
701
702 def test_update_assigns_comments_to_the_new_version(pr_util):
702 def test_update_assigns_comments_to_the_new_version(pr_util):
703 model = PullRequestModel()
703 model = PullRequestModel()
704 pull_request = pr_util.create_pull_request()
704 pull_request = pr_util.create_pull_request()
705 comment = pr_util.create_comment()
705 comment = pr_util.create_comment()
706 pr_util.update_source_repository()
706 pr_util.update_source_repository()
707
707
708 model.update_commits(pull_request)
708 model.update_commits(pull_request)
709
709
710 # Expect that the comment is linked to the pr version now
710 # Expect that the comment is linked to the pr version now
711 assert comment.pull_request_version == model.get_versions(pull_request)[0]
711 assert comment.pull_request_version == model.get_versions(pull_request)[0]
712
712
713
713
714 def test_update_adds_a_comment_to_the_pull_request_about_the_change(pr_util):
714 def test_update_adds_a_comment_to_the_pull_request_about_the_change(pr_util):
715 model = PullRequestModel()
715 model = PullRequestModel()
716 pull_request = pr_util.create_pull_request()
716 pull_request = pr_util.create_pull_request()
717 pr_util.update_source_repository()
717 pr_util.update_source_repository()
718 pr_util.update_source_repository()
718 pr_util.update_source_repository()
719
719
720 model.update_commits(pull_request)
720 model.update_commits(pull_request)
721
721
722 # Expect to find a new comment about the change
722 # Expect to find a new comment about the change
723 expected_message = textwrap.dedent(
723 expected_message = textwrap.dedent(
724 """\
724 """\
725 Auto status change to |under_review|
725 Pull request updated. Auto status change to |under_review|
726
726
727 .. role:: added
727 .. role:: added
728 .. role:: removed
728 .. role:: removed
729 .. parsed-literal::
729 .. parsed-literal::
730
730
731 Changed commits:
731 Changed commits:
732 * :added:`1 added`
732 * :added:`1 added`
733 * :removed:`0 removed`
733 * :removed:`0 removed`
734
734
735 Changed files:
735 Changed files:
736 * `A file_2 <#a_c--92ed3b5f07b4>`_
736 * `A file_2 <#a_c--92ed3b5f07b4>`_
737
737
738 .. |under_review| replace:: *"Under Review"*"""
738 .. |under_review| replace:: *"Under Review"*"""
739 )
739 )
740 pull_request_comments = sorted(
740 pull_request_comments = sorted(
741 pull_request.comments, key=lambda c: c.modified_at)
741 pull_request.comments, key=lambda c: c.modified_at)
742 update_comment = pull_request_comments[-1]
742 update_comment = pull_request_comments[-1]
743 assert update_comment.text == expected_message
743 assert update_comment.text == expected_message
744
744
745
745
746 def test_create_version_from_snapshot_updates_attributes(pr_util):
746 def test_create_version_from_snapshot_updates_attributes(pr_util):
747 pull_request = pr_util.create_pull_request()
747 pull_request = pr_util.create_pull_request()
748
748
749 # Avoiding default values
749 # Avoiding default values
750 pull_request.status = PullRequest.STATUS_CLOSED
750 pull_request.status = PullRequest.STATUS_CLOSED
751 pull_request._last_merge_source_rev = "0" * 40
751 pull_request._last_merge_source_rev = "0" * 40
752 pull_request._last_merge_target_rev = "1" * 40
752 pull_request._last_merge_target_rev = "1" * 40
753 pull_request._last_merge_status = 1
753 pull_request._last_merge_status = 1
754 pull_request.merge_rev = "2" * 40
754 pull_request.merge_rev = "2" * 40
755
755
756 # Remember automatic values
756 # Remember automatic values
757 created_on = pull_request.created_on
757 created_on = pull_request.created_on
758 updated_on = pull_request.updated_on
758 updated_on = pull_request.updated_on
759
759
760 # Create a new version of the pull request
760 # Create a new version of the pull request
761 version = PullRequestModel()._create_version_from_snapshot(pull_request)
761 version = PullRequestModel()._create_version_from_snapshot(pull_request)
762
762
763 # Check attributes
763 # Check attributes
764 assert version.title == pr_util.create_parameters['title']
764 assert version.title == pr_util.create_parameters['title']
765 assert version.description == pr_util.create_parameters['description']
765 assert version.description == pr_util.create_parameters['description']
766 assert version.status == PullRequest.STATUS_CLOSED
766 assert version.status == PullRequest.STATUS_CLOSED
767
767
768 # versions get updated created_on
768 # versions get updated created_on
769 assert version.created_on != created_on
769 assert version.created_on != created_on
770
770
771 assert version.updated_on == updated_on
771 assert version.updated_on == updated_on
772 assert version.user_id == pull_request.user_id
772 assert version.user_id == pull_request.user_id
773 assert version.revisions == pr_util.create_parameters['revisions']
773 assert version.revisions == pr_util.create_parameters['revisions']
774 assert version.source_repo == pr_util.source_repository
774 assert version.source_repo == pr_util.source_repository
775 assert version.source_ref == pr_util.create_parameters['source_ref']
775 assert version.source_ref == pr_util.create_parameters['source_ref']
776 assert version.target_repo == pr_util.target_repository
776 assert version.target_repo == pr_util.target_repository
777 assert version.target_ref == pr_util.create_parameters['target_ref']
777 assert version.target_ref == pr_util.create_parameters['target_ref']
778 assert version._last_merge_source_rev == pull_request._last_merge_source_rev
778 assert version._last_merge_source_rev == pull_request._last_merge_source_rev
779 assert version._last_merge_target_rev == pull_request._last_merge_target_rev
779 assert version._last_merge_target_rev == pull_request._last_merge_target_rev
780 assert version._last_merge_status == pull_request._last_merge_status
780 assert version._last_merge_status == pull_request._last_merge_status
781 assert version.merge_rev == pull_request.merge_rev
781 assert version.merge_rev == pull_request.merge_rev
782 assert version.pull_request == pull_request
782 assert version.pull_request == pull_request
783
783
784
784
785 def test_link_comments_to_version_only_updates_unlinked_comments(pr_util):
785 def test_link_comments_to_version_only_updates_unlinked_comments(pr_util):
786 version1 = pr_util.create_version_of_pull_request()
786 version1 = pr_util.create_version_of_pull_request()
787 comment_linked = pr_util.create_comment(linked_to=version1)
787 comment_linked = pr_util.create_comment(linked_to=version1)
788 comment_unlinked = pr_util.create_comment()
788 comment_unlinked = pr_util.create_comment()
789 version2 = pr_util.create_version_of_pull_request()
789 version2 = pr_util.create_version_of_pull_request()
790
790
791 PullRequestModel()._link_comments_to_version(version2)
791 PullRequestModel()._link_comments_to_version(version2)
792
792
793 # Expect that only the new comment is linked to version2
793 # Expect that only the new comment is linked to version2
794 assert (
794 assert (
795 comment_unlinked.pull_request_version_id ==
795 comment_unlinked.pull_request_version_id ==
796 version2.pull_request_version_id)
796 version2.pull_request_version_id)
797 assert (
797 assert (
798 comment_linked.pull_request_version_id ==
798 comment_linked.pull_request_version_id ==
799 version1.pull_request_version_id)
799 version1.pull_request_version_id)
800 assert (
800 assert (
801 comment_unlinked.pull_request_version_id !=
801 comment_unlinked.pull_request_version_id !=
802 comment_linked.pull_request_version_id)
802 comment_linked.pull_request_version_id)
803
803
804
804
805 def test_calculate_commits():
805 def test_calculate_commits():
806 change = PullRequestModel()._calculate_commit_id_changes(
806 change = PullRequestModel()._calculate_commit_id_changes(
807 set([1, 2, 3]), set([1, 3, 4, 5]))
807 set([1, 2, 3]), set([1, 3, 4, 5]))
808 assert (set([4, 5]), set([1, 3]), set([2])) == (
808 assert (set([4, 5]), set([1, 3]), set([2])) == (
809 change.added, change.common, change.removed)
809 change.added, change.common, change.removed)
810
810
811
811
812 def assert_inline_comments(pull_request, visible=None, outdated=None):
812 def assert_inline_comments(pull_request, visible=None, outdated=None):
813 if visible is not None:
813 if visible is not None:
814 inline_comments = ChangesetCommentsModel().get_inline_comments(
814 inline_comments = ChangesetCommentsModel().get_inline_comments(
815 pull_request.target_repo.repo_id, pull_request=pull_request)
815 pull_request.target_repo.repo_id, pull_request=pull_request)
816 inline_cnt = ChangesetCommentsModel().get_inline_comments_count(
816 inline_cnt = ChangesetCommentsModel().get_inline_comments_count(
817 inline_comments)
817 inline_comments)
818 assert inline_cnt == visible
818 assert inline_cnt == visible
819 if outdated is not None:
819 if outdated is not None:
820 outdated_comments = ChangesetCommentsModel().get_outdated_comments(
820 outdated_comments = ChangesetCommentsModel().get_outdated_comments(
821 pull_request.target_repo.repo_id, pull_request)
821 pull_request.target_repo.repo_id, pull_request)
822 assert len(outdated_comments) == outdated
822 assert len(outdated_comments) == outdated
823
823
824
824
825 def assert_pr_file_changes(
825 def assert_pr_file_changes(
826 pull_request, added=None, modified=None, removed=None):
826 pull_request, added=None, modified=None, removed=None):
827 pr_versions = PullRequestModel().get_versions(pull_request)
827 pr_versions = PullRequestModel().get_versions(pull_request)
828 # always use first version, ie original PR to calculate changes
828 # always use first version, ie original PR to calculate changes
829 pull_request_version = pr_versions[0]
829 pull_request_version = pr_versions[0]
830 old_diff_data, new_diff_data = PullRequestModel()._generate_update_diffs(
830 old_diff_data, new_diff_data = PullRequestModel()._generate_update_diffs(
831 pull_request, pull_request_version)
831 pull_request, pull_request_version)
832 file_changes = PullRequestModel()._calculate_file_changes(
832 file_changes = PullRequestModel()._calculate_file_changes(
833 old_diff_data, new_diff_data)
833 old_diff_data, new_diff_data)
834
834
835 assert added == file_changes.added, \
835 assert added == file_changes.added, \
836 'expected added:%s vs value:%s' % (added, file_changes.added)
836 'expected added:%s vs value:%s' % (added, file_changes.added)
837 assert modified == file_changes.modified, \
837 assert modified == file_changes.modified, \
838 'expected modified:%s vs value:%s' % (modified, file_changes.modified)
838 'expected modified:%s vs value:%s' % (modified, file_changes.modified)
839 assert removed == file_changes.removed, \
839 assert removed == file_changes.removed, \
840 'expected removed:%s vs value:%s' % (removed, file_changes.removed)
840 'expected removed:%s vs value:%s' % (removed, file_changes.removed)
841
841
842
842
843 def outdated_comments_patcher(use_outdated=True):
843 def outdated_comments_patcher(use_outdated=True):
844 return mock.patch.object(
844 return mock.patch.object(
845 ChangesetCommentsModel, 'use_outdated_comments',
845 ChangesetCommentsModel, 'use_outdated_comments',
846 return_value=use_outdated)
846 return_value=use_outdated)
General Comments 0
You need to be logged in to leave comments. Login now