##// END OF EJS Templates
Merged in aras_p/rhodecode (pull request #28)
marcink -
r1980:3dbf0ff5 merge beta
parent child Browse files
Show More
@@ -1,870 +1,886 b''
1 """Helper functions
1 """Helper functions
2
2
3 Consists of functions to typically be used within templates, but also
3 Consists of functions to typically be used within templates, but also
4 available to Controllers. This module is available to both as 'h'.
4 available to Controllers. This module is available to both as 'h'.
5 """
5 """
6 import random
6 import random
7 import hashlib
7 import hashlib
8 import StringIO
8 import StringIO
9 import urllib
9 import urllib
10 import math
10 import math
11 import logging
11 import logging
12
12
13 from datetime import datetime
13 from datetime import datetime
14 from pygments.formatters.html import HtmlFormatter
14 from pygments.formatters.html import HtmlFormatter
15 from pygments import highlight as code_highlight
15 from pygments import highlight as code_highlight
16 from pylons import url, request, config
16 from pylons import url, request, config
17 from pylons.i18n.translation import _, ungettext
17 from pylons.i18n.translation import _, ungettext
18 from hashlib import md5
18 from hashlib import md5
19
19
20 from webhelpers.html import literal, HTML, escape
20 from webhelpers.html import literal, HTML, escape
21 from webhelpers.html.tools import *
21 from webhelpers.html.tools import *
22 from webhelpers.html.builder import make_tag
22 from webhelpers.html.builder import make_tag
23 from webhelpers.html.tags import auto_discovery_link, checkbox, css_classes, \
23 from webhelpers.html.tags import auto_discovery_link, checkbox, css_classes, \
24 end_form, file, form, hidden, image, javascript_link, link_to, \
24 end_form, file, form, hidden, image, javascript_link, link_to, \
25 link_to_if, link_to_unless, ol, required_legend, select, stylesheet_link, \
25 link_to_if, link_to_unless, ol, required_legend, select, stylesheet_link, \
26 submit, text, password, textarea, title, ul, xml_declaration, radio
26 submit, text, password, textarea, title, ul, xml_declaration, radio
27 from webhelpers.html.tools import auto_link, button_to, highlight, \
27 from webhelpers.html.tools import auto_link, button_to, highlight, \
28 js_obfuscate, mail_to, strip_links, strip_tags, tag_re
28 js_obfuscate, mail_to, strip_links, strip_tags, tag_re
29 from webhelpers.number import format_byte_size, format_bit_size
29 from webhelpers.number import format_byte_size, format_bit_size
30 from webhelpers.pylonslib import Flash as _Flash
30 from webhelpers.pylonslib import Flash as _Flash
31 from webhelpers.pylonslib.secure_form import secure_form
31 from webhelpers.pylonslib.secure_form import secure_form
32 from webhelpers.text import chop_at, collapse, convert_accented_entities, \
32 from webhelpers.text import chop_at, collapse, convert_accented_entities, \
33 convert_misc_entities, lchop, plural, rchop, remove_formatting, \
33 convert_misc_entities, lchop, plural, rchop, remove_formatting, \
34 replace_whitespace, urlify, truncate, wrap_paragraphs
34 replace_whitespace, urlify, truncate, wrap_paragraphs
35 from webhelpers.date import time_ago_in_words
35 from webhelpers.date import time_ago_in_words
36 from webhelpers.paginate import Page
36 from webhelpers.paginate import Page
37 from webhelpers.html.tags import _set_input_attrs, _set_id_attr, \
37 from webhelpers.html.tags import _set_input_attrs, _set_id_attr, \
38 convert_boolean_attrs, NotGiven, _make_safe_id_component
38 convert_boolean_attrs, NotGiven, _make_safe_id_component
39
39
40 from rhodecode.lib.annotate import annotate_highlight
40 from rhodecode.lib.annotate import annotate_highlight
41 from rhodecode.lib.utils import repo_name_slug
41 from rhodecode.lib.utils import repo_name_slug
42 from rhodecode.lib import str2bool, safe_unicode, safe_str, get_changeset_safe
42 from rhodecode.lib import str2bool, safe_unicode, safe_str, get_changeset_safe
43 from rhodecode.lib.markup_renderer import MarkupRenderer
43 from rhodecode.lib.markup_renderer import MarkupRenderer
44
44
45 log = logging.getLogger(__name__)
45 log = logging.getLogger(__name__)
46
46
47
47
48 def _reset(name, value=None, id=NotGiven, type="reset", **attrs):
48 def _reset(name, value=None, id=NotGiven, type="reset", **attrs):
49 """
49 """
50 Reset button
50 Reset button
51 """
51 """
52 _set_input_attrs(attrs, type, name, value)
52 _set_input_attrs(attrs, type, name, value)
53 _set_id_attr(attrs, id, name)
53 _set_id_attr(attrs, id, name)
54 convert_boolean_attrs(attrs, ["disabled"])
54 convert_boolean_attrs(attrs, ["disabled"])
55 return HTML.input(**attrs)
55 return HTML.input(**attrs)
56
56
57 reset = _reset
57 reset = _reset
58 safeid = _make_safe_id_component
58 safeid = _make_safe_id_component
59
59
60
60
61 def FID(raw_id, path):
61 def FID(raw_id, path):
62 """
62 """
63 Creates a uniqe ID for filenode based on it's hash of path and revision
63 Creates a uniqe ID for filenode based on it's hash of path and revision
64 it's safe to use in urls
64 it's safe to use in urls
65
65
66 :param raw_id:
66 :param raw_id:
67 :param path:
67 :param path:
68 """
68 """
69
69
70 return 'C-%s-%s' % (short_id(raw_id), md5(path).hexdigest()[:12])
70 return 'C-%s-%s' % (short_id(raw_id), md5(path).hexdigest()[:12])
71
71
72
72
73 def get_token():
73 def get_token():
74 """Return the current authentication token, creating one if one doesn't
74 """Return the current authentication token, creating one if one doesn't
75 already exist.
75 already exist.
76 """
76 """
77 token_key = "_authentication_token"
77 token_key = "_authentication_token"
78 from pylons import session
78 from pylons import session
79 if not token_key in session:
79 if not token_key in session:
80 try:
80 try:
81 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
81 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
82 except AttributeError: # Python < 2.4
82 except AttributeError: # Python < 2.4
83 token = hashlib.sha1(str(random.randrange(2 ** 128))).hexdigest()
83 token = hashlib.sha1(str(random.randrange(2 ** 128))).hexdigest()
84 session[token_key] = token
84 session[token_key] = token
85 if hasattr(session, 'save'):
85 if hasattr(session, 'save'):
86 session.save()
86 session.save()
87 return session[token_key]
87 return session[token_key]
88
88
89 class _GetError(object):
89 class _GetError(object):
90 """Get error from form_errors, and represent it as span wrapped error
90 """Get error from form_errors, and represent it as span wrapped error
91 message
91 message
92
92
93 :param field_name: field to fetch errors for
93 :param field_name: field to fetch errors for
94 :param form_errors: form errors dict
94 :param form_errors: form errors dict
95 """
95 """
96
96
97 def __call__(self, field_name, form_errors):
97 def __call__(self, field_name, form_errors):
98 tmpl = """<span class="error_msg">%s</span>"""
98 tmpl = """<span class="error_msg">%s</span>"""
99 if form_errors and form_errors.has_key(field_name):
99 if form_errors and form_errors.has_key(field_name):
100 return literal(tmpl % form_errors.get(field_name))
100 return literal(tmpl % form_errors.get(field_name))
101
101
102 get_error = _GetError()
102 get_error = _GetError()
103
103
104 class _ToolTip(object):
104 class _ToolTip(object):
105
105
106 def __call__(self, tooltip_title, trim_at=50):
106 def __call__(self, tooltip_title, trim_at=50):
107 """Special function just to wrap our text into nice formatted
107 """Special function just to wrap our text into nice formatted
108 autowrapped text
108 autowrapped text
109
109
110 :param tooltip_title:
110 :param tooltip_title:
111 """
111 """
112 return escape(tooltip_title)
112 return escape(tooltip_title)
113 tooltip = _ToolTip()
113 tooltip = _ToolTip()
114
114
115 class _FilesBreadCrumbs(object):
115 class _FilesBreadCrumbs(object):
116
116
117 def __call__(self, repo_name, rev, paths):
117 def __call__(self, repo_name, rev, paths):
118 if isinstance(paths, str):
118 if isinstance(paths, str):
119 paths = safe_unicode(paths)
119 paths = safe_unicode(paths)
120 url_l = [link_to(repo_name, url('files_home',
120 url_l = [link_to(repo_name, url('files_home',
121 repo_name=repo_name,
121 repo_name=repo_name,
122 revision=rev, f_path=''))]
122 revision=rev, f_path=''))]
123 paths_l = paths.split('/')
123 paths_l = paths.split('/')
124 for cnt, p in enumerate(paths_l):
124 for cnt, p in enumerate(paths_l):
125 if p != '':
125 if p != '':
126 url_l.append(link_to(p,
126 url_l.append(link_to(p,
127 url('files_home',
127 url('files_home',
128 repo_name=repo_name,
128 repo_name=repo_name,
129 revision=rev,
129 revision=rev,
130 f_path='/'.join(paths_l[:cnt + 1])
130 f_path='/'.join(paths_l[:cnt + 1])
131 )
131 )
132 )
132 )
133 )
133 )
134
134
135 return literal('/'.join(url_l))
135 return literal('/'.join(url_l))
136
136
137 files_breadcrumbs = _FilesBreadCrumbs()
137 files_breadcrumbs = _FilesBreadCrumbs()
138
138
139 class CodeHtmlFormatter(HtmlFormatter):
139 class CodeHtmlFormatter(HtmlFormatter):
140 """My code Html Formatter for source codes
140 """My code Html Formatter for source codes
141 """
141 """
142
142
143 def wrap(self, source, outfile):
143 def wrap(self, source, outfile):
144 return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
144 return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
145
145
146 def _wrap_code(self, source):
146 def _wrap_code(self, source):
147 for cnt, it in enumerate(source):
147 for cnt, it in enumerate(source):
148 i, t = it
148 i, t = it
149 t = '<div id="L%s">%s</div>' % (cnt + 1, t)
149 t = '<div id="L%s">%s</div>' % (cnt + 1, t)
150 yield i, t
150 yield i, t
151
151
152 def _wrap_tablelinenos(self, inner):
152 def _wrap_tablelinenos(self, inner):
153 dummyoutfile = StringIO.StringIO()
153 dummyoutfile = StringIO.StringIO()
154 lncount = 0
154 lncount = 0
155 for t, line in inner:
155 for t, line in inner:
156 if t:
156 if t:
157 lncount += 1
157 lncount += 1
158 dummyoutfile.write(line)
158 dummyoutfile.write(line)
159
159
160 fl = self.linenostart
160 fl = self.linenostart
161 mw = len(str(lncount + fl - 1))
161 mw = len(str(lncount + fl - 1))
162 sp = self.linenospecial
162 sp = self.linenospecial
163 st = self.linenostep
163 st = self.linenostep
164 la = self.lineanchors
164 la = self.lineanchors
165 aln = self.anchorlinenos
165 aln = self.anchorlinenos
166 nocls = self.noclasses
166 nocls = self.noclasses
167 if sp:
167 if sp:
168 lines = []
168 lines = []
169
169
170 for i in range(fl, fl + lncount):
170 for i in range(fl, fl + lncount):
171 if i % st == 0:
171 if i % st == 0:
172 if i % sp == 0:
172 if i % sp == 0:
173 if aln:
173 if aln:
174 lines.append('<a href="#%s%d" class="special">%*d</a>' %
174 lines.append('<a href="#%s%d" class="special">%*d</a>' %
175 (la, i, mw, i))
175 (la, i, mw, i))
176 else:
176 else:
177 lines.append('<span class="special">%*d</span>' % (mw, i))
177 lines.append('<span class="special">%*d</span>' % (mw, i))
178 else:
178 else:
179 if aln:
179 if aln:
180 lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i))
180 lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i))
181 else:
181 else:
182 lines.append('%*d' % (mw, i))
182 lines.append('%*d' % (mw, i))
183 else:
183 else:
184 lines.append('')
184 lines.append('')
185 ls = '\n'.join(lines)
185 ls = '\n'.join(lines)
186 else:
186 else:
187 lines = []
187 lines = []
188 for i in range(fl, fl + lncount):
188 for i in range(fl, fl + lncount):
189 if i % st == 0:
189 if i % st == 0:
190 if aln:
190 if aln:
191 lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i))
191 lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i))
192 else:
192 else:
193 lines.append('%*d' % (mw, i))
193 lines.append('%*d' % (mw, i))
194 else:
194 else:
195 lines.append('')
195 lines.append('')
196 ls = '\n'.join(lines)
196 ls = '\n'.join(lines)
197
197
198 # in case you wonder about the seemingly redundant <div> here: since the
198 # in case you wonder about the seemingly redundant <div> here: since the
199 # content in the other cell also is wrapped in a div, some browsers in
199 # content in the other cell also is wrapped in a div, some browsers in
200 # some configurations seem to mess up the formatting...
200 # some configurations seem to mess up the formatting...
201 if nocls:
201 if nocls:
202 yield 0, ('<table class="%stable">' % self.cssclass +
202 yield 0, ('<table class="%stable">' % self.cssclass +
203 '<tr><td><div class="linenodiv" '
203 '<tr><td><div class="linenodiv" '
204 'style="background-color: #f0f0f0; padding-right: 10px">'
204 'style="background-color: #f0f0f0; padding-right: 10px">'
205 '<pre style="line-height: 125%">' +
205 '<pre style="line-height: 125%">' +
206 ls + '</pre></div></td><td id="hlcode" class="code">')
206 ls + '</pre></div></td><td id="hlcode" class="code">')
207 else:
207 else:
208 yield 0, ('<table class="%stable">' % self.cssclass +
208 yield 0, ('<table class="%stable">' % self.cssclass +
209 '<tr><td class="linenos"><div class="linenodiv"><pre>' +
209 '<tr><td class="linenos"><div class="linenodiv"><pre>' +
210 ls + '</pre></div></td><td id="hlcode" class="code">')
210 ls + '</pre></div></td><td id="hlcode" class="code">')
211 yield 0, dummyoutfile.getvalue()
211 yield 0, dummyoutfile.getvalue()
212 yield 0, '</td></tr></table>'
212 yield 0, '</td></tr></table>'
213
213
214
214
215 def pygmentize(filenode, **kwargs):
215 def pygmentize(filenode, **kwargs):
216 """pygmentize function using pygments
216 """pygmentize function using pygments
217
217
218 :param filenode:
218 :param filenode:
219 """
219 """
220
220
221 return literal(code_highlight(filenode.content,
221 return literal(code_highlight(filenode.content,
222 filenode.lexer, CodeHtmlFormatter(**kwargs)))
222 filenode.lexer, CodeHtmlFormatter(**kwargs)))
223
223
224
224
225 def pygmentize_annotation(repo_name, filenode, **kwargs):
225 def pygmentize_annotation(repo_name, filenode, **kwargs):
226 """
226 """
227 pygmentize function for annotation
227 pygmentize function for annotation
228
228
229 :param filenode:
229 :param filenode:
230 """
230 """
231
231
232 color_dict = {}
232 color_dict = {}
233
233
234 def gen_color(n=10000):
234 def gen_color(n=10000):
235 """generator for getting n of evenly distributed colors using
235 """generator for getting n of evenly distributed colors using
236 hsv color and golden ratio. It always return same order of colors
236 hsv color and golden ratio. It always return same order of colors
237
237
238 :returns: RGB tuple
238 :returns: RGB tuple
239 """
239 """
240
240
241 def hsv_to_rgb(h, s, v):
241 def hsv_to_rgb(h, s, v):
242 if s == 0.0:
242 if s == 0.0:
243 return v, v, v
243 return v, v, v
244 i = int(h * 6.0) # XXX assume int() truncates!
244 i = int(h * 6.0) # XXX assume int() truncates!
245 f = (h * 6.0) - i
245 f = (h * 6.0) - i
246 p = v * (1.0 - s)
246 p = v * (1.0 - s)
247 q = v * (1.0 - s * f)
247 q = v * (1.0 - s * f)
248 t = v * (1.0 - s * (1.0 - f))
248 t = v * (1.0 - s * (1.0 - f))
249 i = i % 6
249 i = i % 6
250 if i == 0:
250 if i == 0:
251 return v, t, p
251 return v, t, p
252 if i == 1:
252 if i == 1:
253 return q, v, p
253 return q, v, p
254 if i == 2:
254 if i == 2:
255 return p, v, t
255 return p, v, t
256 if i == 3:
256 if i == 3:
257 return p, q, v
257 return p, q, v
258 if i == 4:
258 if i == 4:
259 return t, p, v
259 return t, p, v
260 if i == 5:
260 if i == 5:
261 return v, p, q
261 return v, p, q
262
262
263 golden_ratio = 0.618033988749895
263 golden_ratio = 0.618033988749895
264 h = 0.22717784590367374
264 h = 0.22717784590367374
265
265
266 for _ in xrange(n):
266 for _ in xrange(n):
267 h += golden_ratio
267 h += golden_ratio
268 h %= 1
268 h %= 1
269 HSV_tuple = [h, 0.95, 0.95]
269 HSV_tuple = [h, 0.95, 0.95]
270 RGB_tuple = hsv_to_rgb(*HSV_tuple)
270 RGB_tuple = hsv_to_rgb(*HSV_tuple)
271 yield map(lambda x: str(int(x * 256)), RGB_tuple)
271 yield map(lambda x: str(int(x * 256)), RGB_tuple)
272
272
273 cgenerator = gen_color()
273 cgenerator = gen_color()
274
274
275 def get_color_string(cs):
275 def get_color_string(cs):
276 if cs in color_dict:
276 if cs in color_dict:
277 col = color_dict[cs]
277 col = color_dict[cs]
278 else:
278 else:
279 col = color_dict[cs] = cgenerator.next()
279 col = color_dict[cs] = cgenerator.next()
280 return "color: rgb(%s)! important;" % (', '.join(col))
280 return "color: rgb(%s)! important;" % (', '.join(col))
281
281
282 def url_func(repo_name):
282 def url_func(repo_name):
283
283
284 def _url_func(changeset):
284 def _url_func(changeset):
285 author = changeset.author
285 author = changeset.author
286 date = changeset.date
286 date = changeset.date
287 message = tooltip(changeset.message)
287 message = tooltip(changeset.message)
288
288
289 tooltip_html = ("<div style='font-size:0.8em'><b>Author:</b>"
289 tooltip_html = ("<div style='font-size:0.8em'><b>Author:</b>"
290 " %s<br/><b>Date:</b> %s</b><br/><b>Message:"
290 " %s<br/><b>Date:</b> %s</b><br/><b>Message:"
291 "</b> %s<br/></div>")
291 "</b> %s<br/></div>")
292
292
293 tooltip_html = tooltip_html % (author, date, message)
293 tooltip_html = tooltip_html % (author, date, message)
294 lnk_format = '%5s:%s' % ('r%s' % changeset.revision,
294 lnk_format = '%5s:%s' % ('r%s' % changeset.revision,
295 short_id(changeset.raw_id))
295 short_id(changeset.raw_id))
296 uri = link_to(
296 uri = link_to(
297 lnk_format,
297 lnk_format,
298 url('changeset_home', repo_name=repo_name,
298 url('changeset_home', repo_name=repo_name,
299 revision=changeset.raw_id),
299 revision=changeset.raw_id),
300 style=get_color_string(changeset.raw_id),
300 style=get_color_string(changeset.raw_id),
301 class_='tooltip',
301 class_='tooltip',
302 title=tooltip_html
302 title=tooltip_html
303 )
303 )
304
304
305 uri += '\n'
305 uri += '\n'
306 return uri
306 return uri
307 return _url_func
307 return _url_func
308
308
309 return literal(annotate_highlight(filenode, url_func(repo_name), **kwargs))
309 return literal(annotate_highlight(filenode, url_func(repo_name), **kwargs))
310
310
311
311
312 def is_following_repo(repo_name, user_id):
312 def is_following_repo(repo_name, user_id):
313 from rhodecode.model.scm import ScmModel
313 from rhodecode.model.scm import ScmModel
314 return ScmModel().is_following_repo(repo_name, user_id)
314 return ScmModel().is_following_repo(repo_name, user_id)
315
315
316 flash = _Flash()
316 flash = _Flash()
317
317
318 #==============================================================================
318 #==============================================================================
319 # SCM FILTERS available via h.
319 # SCM FILTERS available via h.
320 #==============================================================================
320 #==============================================================================
321 from vcs.utils import author_name, author_email
321 from vcs.utils import author_name, author_email
322 from rhodecode.lib import credentials_filter, age as _age
322 from rhodecode.lib import credentials_filter, age as _age
323 from rhodecode.model.db import User
323 from rhodecode.model.db import User
324
324
325 age = lambda x: _age(x)
325 age = lambda x: _age(x)
326 capitalize = lambda x: x.capitalize()
326 capitalize = lambda x: x.capitalize()
327 email = author_email
327 email = author_email
328 short_id = lambda x: x[:12]
328 short_id = lambda x: x[:12]
329 hide_credentials = lambda x: ''.join(credentials_filter(x))
329 hide_credentials = lambda x: ''.join(credentials_filter(x))
330
330
331
331
332 def is_git(repository):
332 def is_git(repository):
333 if hasattr(repository, 'alias'):
333 if hasattr(repository, 'alias'):
334 _type = repository.alias
334 _type = repository.alias
335 elif hasattr(repository, 'repo_type'):
335 elif hasattr(repository, 'repo_type'):
336 _type = repository.repo_type
336 _type = repository.repo_type
337 else:
337 else:
338 _type = repository
338 _type = repository
339 return _type == 'git'
339 return _type == 'git'
340
340
341
341
342 def is_hg(repository):
342 def is_hg(repository):
343 if hasattr(repository, 'alias'):
343 if hasattr(repository, 'alias'):
344 _type = repository.alias
344 _type = repository.alias
345 elif hasattr(repository, 'repo_type'):
345 elif hasattr(repository, 'repo_type'):
346 _type = repository.repo_type
346 _type = repository.repo_type
347 else:
347 else:
348 _type = repository
348 _type = repository
349 return _type == 'hg'
349 return _type == 'hg'
350
350
351
351
352 def email_or_none(author):
352 def email_or_none(author):
353 _email = email(author)
353 _email = email(author)
354 if _email != '':
354 if _email != '':
355 return _email
355 return _email
356
356
357 # See if it contains a username we can get an email from
357 # See if it contains a username we can get an email from
358 user = User.get_by_username(author_name(author), case_insensitive=True,
358 user = User.get_by_username(author_name(author), case_insensitive=True,
359 cache=True)
359 cache=True)
360 if user is not None:
360 if user is not None:
361 return user.email
361 return user.email
362
362
363 # No valid email, not a valid user in the system, none!
363 # No valid email, not a valid user in the system, none!
364 return None
364 return None
365
365
366
366
367 def person(author):
367 def person(author):
368 # attr to return from fetched user
368 # attr to return from fetched user
369 person_getter = lambda usr: usr.username
369 person_getter = lambda usr: usr.username
370
370
371 # Valid email in the attribute passed, see if they're in the system
371 # Valid email in the attribute passed, see if they're in the system
372 _email = email(author)
372 _email = email(author)
373 if _email != '':
373 if _email != '':
374 user = User.get_by_email(_email, case_insensitive=True, cache=True)
374 user = User.get_by_email(_email, case_insensitive=True, cache=True)
375 if user is not None:
375 if user is not None:
376 return person_getter(user)
376 return person_getter(user)
377 return _email
377 return _email
378
378
379 # Maybe it's a username?
379 # Maybe it's a username?
380 _author = author_name(author)
380 _author = author_name(author)
381 user = User.get_by_username(_author, case_insensitive=True,
381 user = User.get_by_username(_author, case_insensitive=True,
382 cache=True)
382 cache=True)
383 if user is not None:
383 if user is not None:
384 return person_getter(user)
384 return person_getter(user)
385
385
386 # Still nothing? Just pass back the author name then
386 # Still nothing? Just pass back the author name then
387 return _author
387 return _author
388
388
389
389
390 def bool2icon(value):
390 def bool2icon(value):
391 """Returns True/False values represented as small html image of true/false
391 """Returns True/False values represented as small html image of true/false
392 icons
392 icons
393
393
394 :param value: bool value
394 :param value: bool value
395 """
395 """
396
396
397 if value is True:
397 if value is True:
398 return HTML.tag('img', src=url("/images/icons/accept.png"),
398 return HTML.tag('img', src=url("/images/icons/accept.png"),
399 alt=_('True'))
399 alt=_('True'))
400
400
401 if value is False:
401 if value is False:
402 return HTML.tag('img', src=url("/images/icons/cancel.png"),
402 return HTML.tag('img', src=url("/images/icons/cancel.png"),
403 alt=_('False'))
403 alt=_('False'))
404
404
405 return value
405 return value
406
406
407
407
408 def action_parser(user_log, feed=False):
408 def action_parser(user_log, feed=False):
409 """This helper will action_map the specified string action into translated
409 """This helper will action_map the specified string action into translated
410 fancy names with icons and links
410 fancy names with icons and links
411
411
412 :param user_log: user log instance
412 :param user_log: user log instance
413 :param feed: use output for feeds (no html and fancy icons)
413 :param feed: use output for feeds (no html and fancy icons)
414 """
414 """
415
415
416 action = user_log.action
416 action = user_log.action
417 action_params = ' '
417 action_params = ' '
418
418
419 x = action.split(':')
419 x = action.split(':')
420
420
421 if len(x) > 1:
421 if len(x) > 1:
422 action, action_params = x
422 action, action_params = x
423
423
424 def get_cs_links():
424 def get_cs_links():
425 revs_limit = 3 #display this amount always
425 revs_limit = 3 #display this amount always
426 revs_top_limit = 50 #show upto this amount of changesets hidden
426 revs_top_limit = 50 #show upto this amount of changesets hidden
427 revs = action_params.split(',')
427 revs = action_params.split(',')
428 repo_name = user_log.repository.repo_name
428 repo_name = user_log.repository.repo_name
429
429
430 from rhodecode.model.scm import ScmModel
430 from rhodecode.model.scm import ScmModel
431 repo = user_log.repository.scm_instance
431 repo = user_log.repository.scm_instance
432
432
433 message = lambda rev: get_changeset_safe(repo, rev).message
433 message = lambda rev: get_changeset_safe(repo, rev).message
434 cs_links = []
434 cs_links = []
435 cs_links.append(" " + ', '.join ([link_to(rev,
435 cs_links.append(" " + ', '.join ([link_to(rev,
436 url('changeset_home',
436 url('changeset_home',
437 repo_name=repo_name,
437 repo_name=repo_name,
438 revision=rev), title=tooltip(message(rev)),
438 revision=rev), title=tooltip(message(rev)),
439 class_='tooltip') for rev in revs[:revs_limit] ]))
439 class_='tooltip') for rev in revs[:revs_limit] ]))
440
440
441 compare_view = (' <div class="compare_view tooltip" title="%s">'
441 compare_view = (' <div class="compare_view tooltip" title="%s">'
442 '<a href="%s">%s</a> '
442 '<a href="%s">%s</a> '
443 '</div>' % (_('Show all combined changesets %s->%s' \
443 '</div>' % (_('Show all combined changesets %s->%s' \
444 % (revs[0], revs[-1])),
444 % (revs[0], revs[-1])),
445 url('changeset_home', repo_name=repo_name,
445 url('changeset_home', repo_name=repo_name,
446 revision='%s...%s' % (revs[0], revs[-1])
446 revision='%s...%s' % (revs[0], revs[-1])
447 ),
447 ),
448 _('compare view'))
448 _('compare view'))
449 )
449 )
450
450
451 if len(revs) > revs_limit:
451 # if we have exactly one more than normally displayed:
452 # just display it, takes less space than displaying "and 1 more revisions"
453 if len(revs) == revs_limit + 1:
454 rev = revs[revs_limit]
455 cs_links.append(", " + link_to(rev,
456 url('changeset_home',
457 repo_name=repo_name,
458 revision=rev), title=tooltip(message(rev)),
459 class_='tooltip') )
460
461 # hidden-by-default ones
462 if len(revs) > revs_limit + 1:
452 uniq_id = revs[0]
463 uniq_id = revs[0]
453 html_tmpl = ('<span> %s '
464 html_tmpl = ('<span> %s '
454 '<a class="show_more" id="_%s" href="#more">%s</a> '
465 '<a class="show_more" id="_%s" href="#more">%s</a> '
455 '%s</span>')
466 '%s</span>')
456 if not feed:
467 if not feed:
457 cs_links.append(html_tmpl % (_('and'), uniq_id, _('%s more') \
468 cs_links.append(html_tmpl % (_('and'), uniq_id, _('%s more') \
458 % (len(revs) - revs_limit),
469 % (len(revs) - revs_limit),
459 _('revisions')))
470 _('revisions')))
460
471
461 if not feed:
472 if not feed:
462 html_tmpl = '<span id="%s" style="display:none"> %s </span>'
473 html_tmpl = '<span id="%s" style="display:none">, %s </span>'
463 else:
474 else:
464 html_tmpl = '<span id="%s"> %s </span>'
475 html_tmpl = '<span id="%s"> %s </span>'
465
476
466 cs_links.append(html_tmpl % (uniq_id, ', '.join([link_to(rev,
477 morelinks = ', '.join([link_to(rev,
467 url('changeset_home',
478 url('changeset_home',
468 repo_name=repo_name, revision=rev),
479 repo_name=repo_name, revision=rev),
469 title=message(rev), class_='tooltip')
480 title=message(rev), class_='tooltip')
470 for rev in revs[revs_limit:revs_top_limit]])))
481 for rev in revs[revs_limit:revs_top_limit]])
482
483 if len(revs) > revs_top_limit:
484 morelinks += ', ...'
485
486 cs_links.append(html_tmpl % (uniq_id, morelinks))
471 if len(revs) > 1:
487 if len(revs) > 1:
472 cs_links.append(compare_view)
488 cs_links.append(compare_view)
473 return ''.join(cs_links)
489 return ''.join(cs_links)
474
490
475 def get_fork_name():
491 def get_fork_name():
476 repo_name = action_params
492 repo_name = action_params
477 return _('fork name ') + str(link_to(action_params, url('summary_home',
493 return _('fork name ') + str(link_to(action_params, url('summary_home',
478 repo_name=repo_name,)))
494 repo_name=repo_name,)))
479
495
480 action_map = {'user_deleted_repo':(_('[deleted] repository'), None),
496 action_map = {'user_deleted_repo':(_('[deleted] repository'), None),
481 'user_created_repo':(_('[created] repository'), None),
497 'user_created_repo':(_('[created] repository'), None),
482 'user_created_fork':(_('[created] repository as fork'), None),
498 'user_created_fork':(_('[created] repository as fork'), None),
483 'user_forked_repo':(_('[forked] repository'), get_fork_name),
499 'user_forked_repo':(_('[forked] repository'), get_fork_name),
484 'user_updated_repo':(_('[updated] repository'), None),
500 'user_updated_repo':(_('[updated] repository'), None),
485 'admin_deleted_repo':(_('[delete] repository'), None),
501 'admin_deleted_repo':(_('[delete] repository'), None),
486 'admin_created_repo':(_('[created] repository'), None),
502 'admin_created_repo':(_('[created] repository'), None),
487 'admin_forked_repo':(_('[forked] repository'), None),
503 'admin_forked_repo':(_('[forked] repository'), None),
488 'admin_updated_repo':(_('[updated] repository'), None),
504 'admin_updated_repo':(_('[updated] repository'), None),
489 'push':(_('[pushed] into'), get_cs_links),
505 'push':(_('[pushed] into'), get_cs_links),
490 'push_local':(_('[committed via RhodeCode] into'), get_cs_links),
506 'push_local':(_('[committed via RhodeCode] into'), get_cs_links),
491 'push_remote':(_('[pulled from remote] into'), get_cs_links),
507 'push_remote':(_('[pulled from remote] into'), get_cs_links),
492 'pull':(_('[pulled] from'), None),
508 'pull':(_('[pulled] from'), None),
493 'started_following_repo':(_('[started following] repository'), None),
509 'started_following_repo':(_('[started following] repository'), None),
494 'stopped_following_repo':(_('[stopped following] repository'), None),
510 'stopped_following_repo':(_('[stopped following] repository'), None),
495 }
511 }
496
512
497 action_str = action_map.get(action, action)
513 action_str = action_map.get(action, action)
498 if feed:
514 if feed:
499 action = action_str[0].replace('[', '').replace(']', '')
515 action = action_str[0].replace('[', '').replace(']', '')
500 else:
516 else:
501 action = action_str[0].replace('[', '<span class="journal_highlight">')\
517 action = action_str[0].replace('[', '<span class="journal_highlight">')\
502 .replace(']', '</span>')
518 .replace(']', '</span>')
503
519
504 action_params_func = lambda :""
520 action_params_func = lambda :""
505
521
506 if callable(action_str[1]):
522 if callable(action_str[1]):
507 action_params_func = action_str[1]
523 action_params_func = action_str[1]
508
524
509 return [literal(action), action_params_func]
525 return [literal(action), action_params_func]
510
526
511
527
512 def action_parser_icon(user_log):
528 def action_parser_icon(user_log):
513 action = user_log.action
529 action = user_log.action
514 action_params = None
530 action_params = None
515 x = action.split(':')
531 x = action.split(':')
516
532
517 if len(x) > 1:
533 if len(x) > 1:
518 action, action_params = x
534 action, action_params = x
519
535
520 tmpl = """<img src="%s%s" alt="%s"/>"""
536 tmpl = """<img src="%s%s" alt="%s"/>"""
521 map = {'user_deleted_repo':'database_delete.png',
537 map = {'user_deleted_repo':'database_delete.png',
522 'user_created_repo':'database_add.png',
538 'user_created_repo':'database_add.png',
523 'user_created_fork':'arrow_divide.png',
539 'user_created_fork':'arrow_divide.png',
524 'user_forked_repo':'arrow_divide.png',
540 'user_forked_repo':'arrow_divide.png',
525 'user_updated_repo':'database_edit.png',
541 'user_updated_repo':'database_edit.png',
526 'admin_deleted_repo':'database_delete.png',
542 'admin_deleted_repo':'database_delete.png',
527 'admin_created_repo':'database_add.png',
543 'admin_created_repo':'database_add.png',
528 'admin_forked_repo':'arrow_divide.png',
544 'admin_forked_repo':'arrow_divide.png',
529 'admin_updated_repo':'database_edit.png',
545 'admin_updated_repo':'database_edit.png',
530 'push':'script_add.png',
546 'push':'script_add.png',
531 'push_local':'script_edit.png',
547 'push_local':'script_edit.png',
532 'push_remote':'connect.png',
548 'push_remote':'connect.png',
533 'pull':'down_16.png',
549 'pull':'down_16.png',
534 'started_following_repo':'heart_add.png',
550 'started_following_repo':'heart_add.png',
535 'stopped_following_repo':'heart_delete.png',
551 'stopped_following_repo':'heart_delete.png',
536 }
552 }
537 return literal(tmpl % ((url('/images/icons/')),
553 return literal(tmpl % ((url('/images/icons/')),
538 map.get(action, action), action))
554 map.get(action, action), action))
539
555
540
556
541 #==============================================================================
557 #==============================================================================
542 # PERMS
558 # PERMS
543 #==============================================================================
559 #==============================================================================
544 from rhodecode.lib.auth import HasPermissionAny, HasPermissionAll, \
560 from rhodecode.lib.auth import HasPermissionAny, HasPermissionAll, \
545 HasRepoPermissionAny, HasRepoPermissionAll
561 HasRepoPermissionAny, HasRepoPermissionAll
546
562
547
563
548 #==============================================================================
564 #==============================================================================
549 # GRAVATAR URL
565 # GRAVATAR URL
550 #==============================================================================
566 #==============================================================================
551
567
552 def gravatar_url(email_address, size=30):
568 def gravatar_url(email_address, size=30):
553 if (not str2bool(config['app_conf'].get('use_gravatar')) or
569 if (not str2bool(config['app_conf'].get('use_gravatar')) or
554 not email_address or email_address == 'anonymous@rhodecode.org'):
570 not email_address or email_address == 'anonymous@rhodecode.org'):
555 f=lambda a,l:min(l,key=lambda x:abs(x-a))
571 f=lambda a,l:min(l,key=lambda x:abs(x-a))
556 return url("/images/user%s.png" % f(size, [14, 16, 20, 24, 30]))
572 return url("/images/user%s.png" % f(size, [14, 16, 20, 24, 30]))
557
573
558 ssl_enabled = 'https' == request.environ.get('wsgi.url_scheme')
574 ssl_enabled = 'https' == request.environ.get('wsgi.url_scheme')
559 default = 'identicon'
575 default = 'identicon'
560 baseurl_nossl = "http://www.gravatar.com/avatar/"
576 baseurl_nossl = "http://www.gravatar.com/avatar/"
561 baseurl_ssl = "https://secure.gravatar.com/avatar/"
577 baseurl_ssl = "https://secure.gravatar.com/avatar/"
562 baseurl = baseurl_ssl if ssl_enabled else baseurl_nossl
578 baseurl = baseurl_ssl if ssl_enabled else baseurl_nossl
563
579
564 if isinstance(email_address, unicode):
580 if isinstance(email_address, unicode):
565 #hashlib crashes on unicode items
581 #hashlib crashes on unicode items
566 email_address = safe_str(email_address)
582 email_address = safe_str(email_address)
567 # construct the url
583 # construct the url
568 gravatar_url = baseurl + hashlib.md5(email_address.lower()).hexdigest() + "?"
584 gravatar_url = baseurl + hashlib.md5(email_address.lower()).hexdigest() + "?"
569 gravatar_url += urllib.urlencode({'d':default, 's':str(size)})
585 gravatar_url += urllib.urlencode({'d':default, 's':str(size)})
570
586
571 return gravatar_url
587 return gravatar_url
572
588
573
589
574 #==============================================================================
590 #==============================================================================
575 # REPO PAGER, PAGER FOR REPOSITORY
591 # REPO PAGER, PAGER FOR REPOSITORY
576 #==============================================================================
592 #==============================================================================
577 class RepoPage(Page):
593 class RepoPage(Page):
578
594
579 def __init__(self, collection, page=1, items_per_page=20,
595 def __init__(self, collection, page=1, items_per_page=20,
580 item_count=None, url=None, **kwargs):
596 item_count=None, url=None, **kwargs):
581
597
582 """Create a "RepoPage" instance. special pager for paging
598 """Create a "RepoPage" instance. special pager for paging
583 repository
599 repository
584 """
600 """
585 self._url_generator = url
601 self._url_generator = url
586
602
587 # Safe the kwargs class-wide so they can be used in the pager() method
603 # Safe the kwargs class-wide so they can be used in the pager() method
588 self.kwargs = kwargs
604 self.kwargs = kwargs
589
605
590 # Save a reference to the collection
606 # Save a reference to the collection
591 self.original_collection = collection
607 self.original_collection = collection
592
608
593 self.collection = collection
609 self.collection = collection
594
610
595 # The self.page is the number of the current page.
611 # The self.page is the number of the current page.
596 # The first page has the number 1!
612 # The first page has the number 1!
597 try:
613 try:
598 self.page = int(page) # make it int() if we get it as a string
614 self.page = int(page) # make it int() if we get it as a string
599 except (ValueError, TypeError):
615 except (ValueError, TypeError):
600 self.page = 1
616 self.page = 1
601
617
602 self.items_per_page = items_per_page
618 self.items_per_page = items_per_page
603
619
604 # Unless the user tells us how many items the collections has
620 # Unless the user tells us how many items the collections has
605 # we calculate that ourselves.
621 # we calculate that ourselves.
606 if item_count is not None:
622 if item_count is not None:
607 self.item_count = item_count
623 self.item_count = item_count
608 else:
624 else:
609 self.item_count = len(self.collection)
625 self.item_count = len(self.collection)
610
626
611 # Compute the number of the first and last available page
627 # Compute the number of the first and last available page
612 if self.item_count > 0:
628 if self.item_count > 0:
613 self.first_page = 1
629 self.first_page = 1
614 self.page_count = int(math.ceil(float(self.item_count) /
630 self.page_count = int(math.ceil(float(self.item_count) /
615 self.items_per_page))
631 self.items_per_page))
616 self.last_page = self.first_page + self.page_count - 1
632 self.last_page = self.first_page + self.page_count - 1
617
633
618 # Make sure that the requested page number is the range of
634 # Make sure that the requested page number is the range of
619 # valid pages
635 # valid pages
620 if self.page > self.last_page:
636 if self.page > self.last_page:
621 self.page = self.last_page
637 self.page = self.last_page
622 elif self.page < self.first_page:
638 elif self.page < self.first_page:
623 self.page = self.first_page
639 self.page = self.first_page
624
640
625 # Note: the number of items on this page can be less than
641 # Note: the number of items on this page can be less than
626 # items_per_page if the last page is not full
642 # items_per_page if the last page is not full
627 self.first_item = max(0, (self.item_count) - (self.page *
643 self.first_item = max(0, (self.item_count) - (self.page *
628 items_per_page))
644 items_per_page))
629 self.last_item = ((self.item_count - 1) - items_per_page *
645 self.last_item = ((self.item_count - 1) - items_per_page *
630 (self.page - 1))
646 (self.page - 1))
631
647
632 self.items = list(self.collection[self.first_item:self.last_item + 1])
648 self.items = list(self.collection[self.first_item:self.last_item + 1])
633
649
634 # Links to previous and next page
650 # Links to previous and next page
635 if self.page > self.first_page:
651 if self.page > self.first_page:
636 self.previous_page = self.page - 1
652 self.previous_page = self.page - 1
637 else:
653 else:
638 self.previous_page = None
654 self.previous_page = None
639
655
640 if self.page < self.last_page:
656 if self.page < self.last_page:
641 self.next_page = self.page + 1
657 self.next_page = self.page + 1
642 else:
658 else:
643 self.next_page = None
659 self.next_page = None
644
660
645 # No items available
661 # No items available
646 else:
662 else:
647 self.first_page = None
663 self.first_page = None
648 self.page_count = 0
664 self.page_count = 0
649 self.last_page = None
665 self.last_page = None
650 self.first_item = None
666 self.first_item = None
651 self.last_item = None
667 self.last_item = None
652 self.previous_page = None
668 self.previous_page = None
653 self.next_page = None
669 self.next_page = None
654 self.items = []
670 self.items = []
655
671
656 # This is a subclass of the 'list' type. Initialise the list now.
672 # This is a subclass of the 'list' type. Initialise the list now.
657 list.__init__(self, reversed(self.items))
673 list.__init__(self, reversed(self.items))
658
674
659
675
660 def changed_tooltip(nodes):
676 def changed_tooltip(nodes):
661 """
677 """
662 Generates a html string for changed nodes in changeset page.
678 Generates a html string for changed nodes in changeset page.
663 It limits the output to 30 entries
679 It limits the output to 30 entries
664
680
665 :param nodes: LazyNodesGenerator
681 :param nodes: LazyNodesGenerator
666 """
682 """
667 if nodes:
683 if nodes:
668 pref = ': <br/> '
684 pref = ': <br/> '
669 suf = ''
685 suf = ''
670 if len(nodes) > 30:
686 if len(nodes) > 30:
671 suf = '<br/>' + _(' and %s more') % (len(nodes) - 30)
687 suf = '<br/>' + _(' and %s more') % (len(nodes) - 30)
672 return literal(pref + '<br/> '.join([safe_unicode(x.path)
688 return literal(pref + '<br/> '.join([safe_unicode(x.path)
673 for x in nodes[:30]]) + suf)
689 for x in nodes[:30]]) + suf)
674 else:
690 else:
675 return ': ' + _('No Files')
691 return ': ' + _('No Files')
676
692
677
693
678 def repo_link(groups_and_repos):
694 def repo_link(groups_and_repos):
679 """
695 """
680 Makes a breadcrumbs link to repo within a group
696 Makes a breadcrumbs link to repo within a group
681 joins &raquo; on each group to create a fancy link
697 joins &raquo; on each group to create a fancy link
682
698
683 ex::
699 ex::
684 group >> subgroup >> repo
700 group >> subgroup >> repo
685
701
686 :param groups_and_repos:
702 :param groups_and_repos:
687 """
703 """
688 groups, repo_name = groups_and_repos
704 groups, repo_name = groups_and_repos
689
705
690 if not groups:
706 if not groups:
691 return repo_name
707 return repo_name
692 else:
708 else:
693 def make_link(group):
709 def make_link(group):
694 return link_to(group.name, url('repos_group_home',
710 return link_to(group.name, url('repos_group_home',
695 group_name=group.group_name))
711 group_name=group.group_name))
696 return literal(' &raquo; '.join(map(make_link, groups)) + \
712 return literal(' &raquo; '.join(map(make_link, groups)) + \
697 " &raquo; " + repo_name)
713 " &raquo; " + repo_name)
698
714
699
715
700 def fancy_file_stats(stats):
716 def fancy_file_stats(stats):
701 """
717 """
702 Displays a fancy two colored bar for number of added/deleted
718 Displays a fancy two colored bar for number of added/deleted
703 lines of code on file
719 lines of code on file
704
720
705 :param stats: two element list of added/deleted lines of code
721 :param stats: two element list of added/deleted lines of code
706 """
722 """
707
723
708 a, d, t = stats[0], stats[1], stats[0] + stats[1]
724 a, d, t = stats[0], stats[1], stats[0] + stats[1]
709 width = 100
725 width = 100
710 unit = float(width) / (t or 1)
726 unit = float(width) / (t or 1)
711
727
712 # needs > 9% of width to be visible or 0 to be hidden
728 # needs > 9% of width to be visible or 0 to be hidden
713 a_p = max(9, unit * a) if a > 0 else 0
729 a_p = max(9, unit * a) if a > 0 else 0
714 d_p = max(9, unit * d) if d > 0 else 0
730 d_p = max(9, unit * d) if d > 0 else 0
715 p_sum = a_p + d_p
731 p_sum = a_p + d_p
716
732
717 if p_sum > width:
733 if p_sum > width:
718 #adjust the percentage to be == 100% since we adjusted to 9
734 #adjust the percentage to be == 100% since we adjusted to 9
719 if a_p > d_p:
735 if a_p > d_p:
720 a_p = a_p - (p_sum - width)
736 a_p = a_p - (p_sum - width)
721 else:
737 else:
722 d_p = d_p - (p_sum - width)
738 d_p = d_p - (p_sum - width)
723
739
724 a_v = a if a > 0 else ''
740 a_v = a if a > 0 else ''
725 d_v = d if d > 0 else ''
741 d_v = d if d > 0 else ''
726
742
727 def cgen(l_type):
743 def cgen(l_type):
728 mapping = {'tr': 'top-right-rounded-corner',
744 mapping = {'tr': 'top-right-rounded-corner',
729 'tl': 'top-left-rounded-corner',
745 'tl': 'top-left-rounded-corner',
730 'br': 'bottom-right-rounded-corner',
746 'br': 'bottom-right-rounded-corner',
731 'bl': 'bottom-left-rounded-corner'}
747 'bl': 'bottom-left-rounded-corner'}
732 map_getter = lambda x: mapping[x]
748 map_getter = lambda x: mapping[x]
733
749
734 if l_type == 'a' and d_v:
750 if l_type == 'a' and d_v:
735 #case when added and deleted are present
751 #case when added and deleted are present
736 return ' '.join(map(map_getter, ['tl', 'bl']))
752 return ' '.join(map(map_getter, ['tl', 'bl']))
737
753
738 if l_type == 'a' and not d_v:
754 if l_type == 'a' and not d_v:
739 return ' '.join(map(map_getter, ['tr', 'br', 'tl', 'bl']))
755 return ' '.join(map(map_getter, ['tr', 'br', 'tl', 'bl']))
740
756
741 if l_type == 'd' and a_v:
757 if l_type == 'd' and a_v:
742 return ' '.join(map(map_getter, ['tr', 'br']))
758 return ' '.join(map(map_getter, ['tr', 'br']))
743
759
744 if l_type == 'd' and not a_v:
760 if l_type == 'd' and not a_v:
745 return ' '.join(map(map_getter, ['tr', 'br', 'tl', 'bl']))
761 return ' '.join(map(map_getter, ['tr', 'br', 'tl', 'bl']))
746
762
747 d_a = '<div class="added %s" style="width:%s%%">%s</div>' % (
763 d_a = '<div class="added %s" style="width:%s%%">%s</div>' % (
748 cgen('a'),a_p, a_v
764 cgen('a'),a_p, a_v
749 )
765 )
750 d_d = '<div class="deleted %s" style="width:%s%%">%s</div>' % (
766 d_d = '<div class="deleted %s" style="width:%s%%">%s</div>' % (
751 cgen('d'),d_p, d_v
767 cgen('d'),d_p, d_v
752 )
768 )
753 return literal('<div style="width:%spx">%s%s</div>' % (width, d_a, d_d))
769 return literal('<div style="width:%spx">%s%s</div>' % (width, d_a, d_d))
754
770
755
771
756 def urlify_text(text_):
772 def urlify_text(text_):
757 import re
773 import re
758
774
759 url_pat = re.compile(r'''(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]'''
775 url_pat = re.compile(r'''(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]'''
760 '''|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)''')
776 '''|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)''')
761
777
762 def url_func(match_obj):
778 def url_func(match_obj):
763 url_full = match_obj.groups()[0]
779 url_full = match_obj.groups()[0]
764 return '<a href="%(url)s">%(url)s</a>' % ({'url': url_full})
780 return '<a href="%(url)s">%(url)s</a>' % ({'url': url_full})
765
781
766 return literal(url_pat.sub(url_func, text_))
782 return literal(url_pat.sub(url_func, text_))
767
783
768
784
769 def urlify_changesets(text_, repository):
785 def urlify_changesets(text_, repository):
770 import re
786 import re
771 URL_PAT = re.compile(r'([0-9a-fA-F]{12,})')
787 URL_PAT = re.compile(r'([0-9a-fA-F]{12,})')
772
788
773 def url_func(match_obj):
789 def url_func(match_obj):
774 rev = match_obj.groups()[0]
790 rev = match_obj.groups()[0]
775 pref = ''
791 pref = ''
776 if match_obj.group().startswith(' '):
792 if match_obj.group().startswith(' '):
777 pref = ' '
793 pref = ' '
778 tmpl = (
794 tmpl = (
779 '%(pref)s<a class="%(cls)s" href="%(url)s">'
795 '%(pref)s<a class="%(cls)s" href="%(url)s">'
780 '%(rev)s'
796 '%(rev)s'
781 '</a>'
797 '</a>'
782 )
798 )
783 return tmpl % {
799 return tmpl % {
784 'pref': pref,
800 'pref': pref,
785 'cls': 'revision-link',
801 'cls': 'revision-link',
786 'url': url('changeset_home', repo_name=repository, revision=rev),
802 'url': url('changeset_home', repo_name=repository, revision=rev),
787 'rev': rev,
803 'rev': rev,
788 }
804 }
789
805
790 newtext = URL_PAT.sub(url_func, text_)
806 newtext = URL_PAT.sub(url_func, text_)
791
807
792 return newtext
808 return newtext
793
809
794
810
795 def urlify_commit(text_, repository=None, link_=None):
811 def urlify_commit(text_, repository=None, link_=None):
796 import re
812 import re
797 import traceback
813 import traceback
798
814
799 # urlify changesets
815 # urlify changesets
800 text_ = urlify_changesets(text_, repository)
816 text_ = urlify_changesets(text_, repository)
801
817
802 def linkify_others(t,l):
818 def linkify_others(t,l):
803 urls = re.compile(r'(\<a.*?\<\/a\>)',)
819 urls = re.compile(r'(\<a.*?\<\/a\>)',)
804 links = []
820 links = []
805 for e in urls.split(t):
821 for e in urls.split(t):
806 if not urls.match(e):
822 if not urls.match(e):
807 links.append('<a class="message-link" href="%s">%s</a>' % (l,e))
823 links.append('<a class="message-link" href="%s">%s</a>' % (l,e))
808 else:
824 else:
809 links.append(e)
825 links.append(e)
810
826
811 return ''.join(links)
827 return ''.join(links)
812 try:
828 try:
813 conf = config['app_conf']
829 conf = config['app_conf']
814
830
815 URL_PAT = re.compile(r'%s' % conf.get('issue_pat'))
831 URL_PAT = re.compile(r'%s' % conf.get('issue_pat'))
816
832
817 if URL_PAT:
833 if URL_PAT:
818 ISSUE_SERVER_LNK = conf.get('issue_server_link')
834 ISSUE_SERVER_LNK = conf.get('issue_server_link')
819 ISSUE_PREFIX = conf.get('issue_prefix')
835 ISSUE_PREFIX = conf.get('issue_prefix')
820
836
821 def url_func(match_obj):
837 def url_func(match_obj):
822 pref = ''
838 pref = ''
823 if match_obj.group().startswith(' '):
839 if match_obj.group().startswith(' '):
824 pref = ' '
840 pref = ' '
825
841
826 issue_id = ''.join(match_obj.groups())
842 issue_id = ''.join(match_obj.groups())
827 tmpl = (
843 tmpl = (
828 '%(pref)s<a class="%(cls)s" href="%(url)s">'
844 '%(pref)s<a class="%(cls)s" href="%(url)s">'
829 '%(issue-prefix)s%(id-repr)s'
845 '%(issue-prefix)s%(id-repr)s'
830 '</a>'
846 '</a>'
831 )
847 )
832 url = ISSUE_SERVER_LNK.replace('{id}', issue_id)
848 url = ISSUE_SERVER_LNK.replace('{id}', issue_id)
833 if repository:
849 if repository:
834 url = url.replace('{repo}', repository)
850 url = url.replace('{repo}', repository)
835
851
836 return tmpl % {
852 return tmpl % {
837 'pref': pref,
853 'pref': pref,
838 'cls': 'issue-tracker-link',
854 'cls': 'issue-tracker-link',
839 'url': url,
855 'url': url,
840 'id-repr': issue_id,
856 'id-repr': issue_id,
841 'issue-prefix': ISSUE_PREFIX,
857 'issue-prefix': ISSUE_PREFIX,
842 'serv': ISSUE_SERVER_LNK,
858 'serv': ISSUE_SERVER_LNK,
843 }
859 }
844
860
845 newtext = URL_PAT.sub(url_func, text_)
861 newtext = URL_PAT.sub(url_func, text_)
846
862
847 # wrap not links into final link => link_
863 # wrap not links into final link => link_
848 newtext = linkify_others(newtext, link_)
864 newtext = linkify_others(newtext, link_)
849
865
850 return literal(newtext)
866 return literal(newtext)
851 except:
867 except:
852 log.error(traceback.format_exc())
868 log.error(traceback.format_exc())
853 pass
869 pass
854
870
855 return text_
871 return text_
856
872
857
873
858 def rst(source):
874 def rst(source):
859 return literal('<div class="rst-block">%s</div>' %
875 return literal('<div class="rst-block">%s</div>' %
860 MarkupRenderer.rst(source))
876 MarkupRenderer.rst(source))
861
877
862
878
863 def rst_w_mentions(source):
879 def rst_w_mentions(source):
864 """
880 """
865 Wrapped rst renderer with @mention highlighting
881 Wrapped rst renderer with @mention highlighting
866
882
867 :param source:
883 :param source:
868 """
884 """
869 return literal('<div class="rst-block">%s</div>' %
885 return literal('<div class="rst-block">%s</div>' %
870 MarkupRenderer.rst_with_mentions(source))
886 MarkupRenderer.rst_with_mentions(source))
General Comments 0
You need to be logged in to leave comments. Login now