##// END OF EJS Templates
pull-requests: expose version browsing of pull requests....
marcink -
r1255:952cdf08 default
parent child Browse files
Show More

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

@@ -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 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -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:
115 <div class="field">
116 <div class="field">
116 <div class="label-summary">
117 <div class="label-summary">
117 <label>${_('Merge')}:</label>
118 <label>Merge:</label>
118 </div>
119 <div class="input">
120 % if not c.pull_request.is_closed() and c.pull_request.shadow_merge_ref:
121 <div class="pr-mergeinfo">
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">
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">
126 %endif
119 </div>
127 </div>
120 <div class="input">
128 % else:
121 <div class="pr-mergeinfo">
129 <div class="">
122 %if h.is_hg(c.pull_request.target_repo):
130 ${_('Shadow repository data not available')}.
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):
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
127 </div>
128 </div>
131 </div>
132 % endif
129 </div>
133 </div>
130 %endif
134 </div>
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