##// END OF EJS Templates
white space cleanup
marcink -
r3149:68f9c216 beta
parent child Browse files
Show More
@@ -1,1173 +1,1172 b''
1 1 """Helper functions
2 2
3 3 Consists of functions to typically be used within templates, but also
4 4 available to Controllers. This module is available to both as 'h'.
5 5 """
6 6 import random
7 7 import hashlib
8 8 import StringIO
9 9 import urllib
10 10 import math
11 11 import logging
12 12 import re
13 13 import urlparse
14 14 import textwrap
15 15
16 16 from datetime import datetime
17 17 from pygments.formatters.html import HtmlFormatter
18 18 from pygments import highlight as code_highlight
19 19 from pylons import url, request, config
20 20 from pylons.i18n.translation import _, ungettext
21 21 from hashlib import md5
22 22
23 23 from webhelpers.html import literal, HTML, escape
24 24 from webhelpers.html.tools import *
25 25 from webhelpers.html.builder import make_tag
26 26 from webhelpers.html.tags import auto_discovery_link, checkbox, css_classes, \
27 27 end_form, file, form, hidden, image, javascript_link, link_to, \
28 28 link_to_if, link_to_unless, ol, required_legend, select, stylesheet_link, \
29 29 submit, text, password, textarea, title, ul, xml_declaration, radio
30 30 from webhelpers.html.tools import auto_link, button_to, highlight, \
31 31 js_obfuscate, mail_to, strip_links, strip_tags, tag_re
32 32 from webhelpers.number import format_byte_size, format_bit_size
33 33 from webhelpers.pylonslib import Flash as _Flash
34 34 from webhelpers.pylonslib.secure_form import secure_form
35 35 from webhelpers.text import chop_at, collapse, convert_accented_entities, \
36 36 convert_misc_entities, lchop, plural, rchop, remove_formatting, \
37 37 replace_whitespace, urlify, truncate, wrap_paragraphs
38 38 from webhelpers.date import time_ago_in_words
39 39 from webhelpers.paginate import Page
40 40 from webhelpers.html.tags import _set_input_attrs, _set_id_attr, \
41 41 convert_boolean_attrs, NotGiven, _make_safe_id_component
42 42
43 43 from rhodecode.lib.annotate import annotate_highlight
44 44 from rhodecode.lib.utils import repo_name_slug
45 45 from rhodecode.lib.utils2 import str2bool, safe_unicode, safe_str, \
46 46 get_changeset_safe, datetime_to_time, time_to_datetime, AttributeDict
47 47 from rhodecode.lib.markup_renderer import MarkupRenderer
48 48 from rhodecode.lib.vcs.exceptions import ChangesetDoesNotExistError
49 49 from rhodecode.lib.vcs.backends.base import BaseChangeset, EmptyChangeset
50 50 from rhodecode.config.conf import DATE_FORMAT, DATETIME_FORMAT
51 51 from rhodecode.model.changeset_status import ChangesetStatusModel
52 52 from rhodecode.model.db import URL_SEP, Permission
53 53
54 54 log = logging.getLogger(__name__)
55 55
56 56
57 57 html_escape_table = {
58 58 "&": "&",
59 59 '"': """,
60 60 "'": "'",
61 61 ">": ">",
62 62 "<": "&lt;",
63 63 }
64 64
65 65
66 66 def html_escape(text):
67 67 """Produce entities within text."""
68 68 return "".join(html_escape_table.get(c, c) for c in text)
69 69
70 70
71 71 def shorter(text, size=20):
72 72 postfix = '...'
73 73 if len(text) > size:
74 74 return text[:size - len(postfix)] + postfix
75 75 return text
76 76
77 77
78 78 def _reset(name, value=None, id=NotGiven, type="reset", **attrs):
79 79 """
80 80 Reset button
81 81 """
82 82 _set_input_attrs(attrs, type, name, value)
83 83 _set_id_attr(attrs, id, name)
84 84 convert_boolean_attrs(attrs, ["disabled"])
85 85 return HTML.input(**attrs)
86 86
87 87 reset = _reset
88 88 safeid = _make_safe_id_component
89 89
90 90
91 91 def FID(raw_id, path):
92 92 """
93 93 Creates a uniqe ID for filenode based on it's hash of path and revision
94 94 it's safe to use in urls
95 95
96 96 :param raw_id:
97 97 :param path:
98 98 """
99 99
100 100 return 'C-%s-%s' % (short_id(raw_id), md5(safe_str(path)).hexdigest()[:12])
101 101
102 102
103 103 def get_token():
104 104 """Return the current authentication token, creating one if one doesn't
105 105 already exist.
106 106 """
107 107 token_key = "_authentication_token"
108 108 from pylons import session
109 109 if not token_key in session:
110 110 try:
111 111 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
112 112 except AttributeError: # Python < 2.4
113 113 token = hashlib.sha1(str(random.randrange(2 ** 128))).hexdigest()
114 114 session[token_key] = token
115 115 if hasattr(session, 'save'):
116 116 session.save()
117 117 return session[token_key]
118 118
119 119
120 120 class _GetError(object):
121 121 """Get error from form_errors, and represent it as span wrapped error
122 122 message
123 123
124 124 :param field_name: field to fetch errors for
125 125 :param form_errors: form errors dict
126 126 """
127 127
128 128 def __call__(self, field_name, form_errors):
129 129 tmpl = """<span class="error_msg">%s</span>"""
130 130 if form_errors and field_name in form_errors:
131 131 return literal(tmpl % form_errors.get(field_name))
132 132
133 133 get_error = _GetError()
134 134
135 135
136 136 class _ToolTip(object):
137 137
138 138 def __call__(self, tooltip_title, trim_at=50):
139 139 """
140 140 Special function just to wrap our text into nice formatted
141 141 autowrapped text
142 142
143 143 :param tooltip_title:
144 144 """
145 145 tooltip_title = escape(tooltip_title)
146 146 tooltip_title = tooltip_title.replace('<', '&lt;').replace('>', '&gt;')
147 147 return tooltip_title
148 148 tooltip = _ToolTip()
149 149
150 150
151 151 class _FilesBreadCrumbs(object):
152 152
153 153 def __call__(self, repo_name, rev, paths):
154 154 if isinstance(paths, str):
155 155 paths = safe_unicode(paths)
156 156 url_l = [link_to(repo_name, url('files_home',
157 157 repo_name=repo_name,
158 158 revision=rev, f_path=''),
159 159 class_='ypjax-link')]
160 160 paths_l = paths.split('/')
161 161 for cnt, p in enumerate(paths_l):
162 162 if p != '':
163 163 url_l.append(link_to(p,
164 164 url('files_home',
165 165 repo_name=repo_name,
166 166 revision=rev,
167 167 f_path='/'.join(paths_l[:cnt + 1])
168 168 ),
169 169 class_='ypjax-link'
170 170 )
171 171 )
172 172
173 173 return literal('/'.join(url_l))
174 174
175 175 files_breadcrumbs = _FilesBreadCrumbs()
176 176
177 177
178 178 class CodeHtmlFormatter(HtmlFormatter):
179 179 """
180 180 My code Html Formatter for source codes
181 181 """
182 182
183 183 def wrap(self, source, outfile):
184 184 return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
185 185
186 186 def _wrap_code(self, source):
187 187 for cnt, it in enumerate(source):
188 188 i, t = it
189 189 t = '<div id="L%s">%s</div>' % (cnt + 1, t)
190 190 yield i, t
191 191
192 192 def _wrap_tablelinenos(self, inner):
193 193 dummyoutfile = StringIO.StringIO()
194 194 lncount = 0
195 195 for t, line in inner:
196 196 if t:
197 197 lncount += 1
198 198 dummyoutfile.write(line)
199 199
200 200 fl = self.linenostart
201 201 mw = len(str(lncount + fl - 1))
202 202 sp = self.linenospecial
203 203 st = self.linenostep
204 204 la = self.lineanchors
205 205 aln = self.anchorlinenos
206 206 nocls = self.noclasses
207 207 if sp:
208 208 lines = []
209 209
210 210 for i in range(fl, fl + lncount):
211 211 if i % st == 0:
212 212 if i % sp == 0:
213 213 if aln:
214 214 lines.append('<a href="#%s%d" class="special">%*d</a>' %
215 215 (la, i, mw, i))
216 216 else:
217 217 lines.append('<span class="special">%*d</span>' % (mw, i))
218 218 else:
219 219 if aln:
220 220 lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i))
221 221 else:
222 222 lines.append('%*d' % (mw, i))
223 223 else:
224 224 lines.append('')
225 225 ls = '\n'.join(lines)
226 226 else:
227 227 lines = []
228 228 for i in range(fl, fl + lncount):
229 229 if i % st == 0:
230 230 if aln:
231 231 lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i))
232 232 else:
233 233 lines.append('%*d' % (mw, i))
234 234 else:
235 235 lines.append('')
236 236 ls = '\n'.join(lines)
237 237
238 238 # in case you wonder about the seemingly redundant <div> here: since the
239 239 # content in the other cell also is wrapped in a div, some browsers in
240 240 # some configurations seem to mess up the formatting...
241 241 if nocls:
242 242 yield 0, ('<table class="%stable">' % self.cssclass +
243 243 '<tr><td><div class="linenodiv" '
244 244 'style="background-color: #f0f0f0; padding-right: 10px">'
245 245 '<pre style="line-height: 125%">' +
246 246 ls + '</pre></div></td><td id="hlcode" class="code">')
247 247 else:
248 248 yield 0, ('<table class="%stable">' % self.cssclass +
249 249 '<tr><td class="linenos"><div class="linenodiv"><pre>' +
250 250 ls + '</pre></div></td><td id="hlcode" class="code">')
251 251 yield 0, dummyoutfile.getvalue()
252 252 yield 0, '</td></tr></table>'
253 253
254 254
255 255 def pygmentize(filenode, **kwargs):
256 256 """pygmentize function using pygments
257 257
258 258 :param filenode:
259 259 """
260 260
261 261 return literal(code_highlight(filenode.content,
262 262 filenode.lexer, CodeHtmlFormatter(**kwargs)))
263 263
264 264
265 265 def pygmentize_annotation(repo_name, filenode, **kwargs):
266 266 """
267 267 pygmentize function for annotation
268 268
269 269 :param filenode:
270 270 """
271 271
272 272 color_dict = {}
273 273
274 274 def gen_color(n=10000):
275 275 """generator for getting n of evenly distributed colors using
276 276 hsv color and golden ratio. It always return same order of colors
277 277
278 278 :returns: RGB tuple
279 279 """
280 280
281 281 def hsv_to_rgb(h, s, v):
282 282 if s == 0.0:
283 283 return v, v, v
284 284 i = int(h * 6.0) # XXX assume int() truncates!
285 285 f = (h * 6.0) - i
286 286 p = v * (1.0 - s)
287 287 q = v * (1.0 - s * f)
288 288 t = v * (1.0 - s * (1.0 - f))
289 289 i = i % 6
290 290 if i == 0:
291 291 return v, t, p
292 292 if i == 1:
293 293 return q, v, p
294 294 if i == 2:
295 295 return p, v, t
296 296 if i == 3:
297 297 return p, q, v
298 298 if i == 4:
299 299 return t, p, v
300 300 if i == 5:
301 301 return v, p, q
302 302
303 303 golden_ratio = 0.618033988749895
304 304 h = 0.22717784590367374
305 305
306 306 for _ in xrange(n):
307 307 h += golden_ratio
308 308 h %= 1
309 309 HSV_tuple = [h, 0.95, 0.95]
310 310 RGB_tuple = hsv_to_rgb(*HSV_tuple)
311 311 yield map(lambda x: str(int(x * 256)), RGB_tuple)
312 312
313 313 cgenerator = gen_color()
314 314
315 315 def get_color_string(cs):
316 316 if cs in color_dict:
317 317 col = color_dict[cs]
318 318 else:
319 319 col = color_dict[cs] = cgenerator.next()
320 320 return "color: rgb(%s)! important;" % (', '.join(col))
321 321
322 322 def url_func(repo_name):
323 323
324 324 def _url_func(changeset):
325 325 author = changeset.author
326 326 date = changeset.date
327 327 message = tooltip(changeset.message)
328 328
329 329 tooltip_html = ("<div style='font-size:0.8em'><b>Author:</b>"
330 330 " %s<br/><b>Date:</b> %s</b><br/><b>Message:"
331 331 "</b> %s<br/></div>")
332 332
333 333 tooltip_html = tooltip_html % (author, date, message)
334 334 lnk_format = '%5s:%s' % ('r%s' % changeset.revision,
335 335 short_id(changeset.raw_id))
336 336 uri = link_to(
337 337 lnk_format,
338 338 url('changeset_home', repo_name=repo_name,
339 339 revision=changeset.raw_id),
340 340 style=get_color_string(changeset.raw_id),
341 341 class_='tooltip',
342 342 title=tooltip_html
343 343 )
344 344
345 345 uri += '\n'
346 346 return uri
347 347 return _url_func
348 348
349 349 return literal(annotate_highlight(filenode, url_func(repo_name), **kwargs))
350 350
351 351
352 352 def is_following_repo(repo_name, user_id):
353 353 from rhodecode.model.scm import ScmModel
354 354 return ScmModel().is_following_repo(repo_name, user_id)
355 355
356 356 flash = _Flash()
357 357
358 358 #==============================================================================
359 359 # SCM FILTERS available via h.
360 360 #==============================================================================
361 361 from rhodecode.lib.vcs.utils import author_name, author_email
362 362 from rhodecode.lib.utils2 import credentials_filter, age as _age
363 363 from rhodecode.model.db import User, ChangesetStatus
364 364
365 365 age = lambda x: _age(x)
366 366 capitalize = lambda x: x.capitalize()
367 367 email = author_email
368 368 short_id = lambda x: x[:12]
369 369 hide_credentials = lambda x: ''.join(credentials_filter(x))
370 370
371 371
372 372 def fmt_date(date):
373 373 if date:
374 374 _fmt = _(u"%a, %d %b %Y %H:%M:%S").encode('utf8')
375 375 return date.strftime(_fmt).decode('utf8')
376 376
377 377 return ""
378 378
379 379
380 380 def is_git(repository):
381 381 if hasattr(repository, 'alias'):
382 382 _type = repository.alias
383 383 elif hasattr(repository, 'repo_type'):
384 384 _type = repository.repo_type
385 385 else:
386 386 _type = repository
387 387 return _type == 'git'
388 388
389 389
390 390 def is_hg(repository):
391 391 if hasattr(repository, 'alias'):
392 392 _type = repository.alias
393 393 elif hasattr(repository, 'repo_type'):
394 394 _type = repository.repo_type
395 395 else:
396 396 _type = repository
397 397 return _type == 'hg'
398 398
399 399
400 400 def email_or_none(author):
401 401 # extract email from the commit string
402 402 _email = email(author)
403 403 if _email != '':
404 404 # check it against RhodeCode database, and use the MAIN email for this
405 405 # user
406 406 user = User.get_by_email(_email, case_insensitive=True, cache=True)
407 407 if user is not None:
408 408 return user.email
409 409 return _email
410 410
411 411 # See if it contains a username we can get an email from
412 412 user = User.get_by_username(author_name(author), case_insensitive=True,
413 413 cache=True)
414 414 if user is not None:
415 415 return user.email
416 416
417 417 # No valid email, not a valid user in the system, none!
418 418 return None
419 419
420 420
421 421 def person(author, show_attr="username_and_name"):
422 422 # attr to return from fetched user
423 423 person_getter = lambda usr: getattr(usr, show_attr)
424 424
425 425 # Valid email in the attribute passed, see if they're in the system
426 426 _email = email(author)
427 427 if _email != '':
428 428 user = User.get_by_email(_email, case_insensitive=True, cache=True)
429 429 if user is not None:
430 430 return person_getter(user)
431 431 return _email
432 432
433 433 # Maybe it's a username?
434 434 _author = author_name(author)
435 435 user = User.get_by_username(_author, case_insensitive=True,
436 436 cache=True)
437 437 if user is not None:
438 438 return person_getter(user)
439 439
440 440 # Still nothing? Just pass back the author name then
441 441 return _author
442 442
443 443
444 444 def person_by_id(id_, show_attr="username_and_name"):
445 445 # attr to return from fetched user
446 446 person_getter = lambda usr: getattr(usr, show_attr)
447 447
448 448 #maybe it's an ID ?
449 449 if str(id_).isdigit() or isinstance(id_, int):
450 450 id_ = int(id_)
451 451 user = User.get(id_)
452 452 if user is not None:
453 453 return person_getter(user)
454 454 return id_
455 455
456 456
457 457 def desc_stylize(value):
458 458 """
459 459 converts tags from value into html equivalent
460 460
461 461 :param value:
462 462 """
463 463 value = re.sub(r'\[see\ \=\>\ *([a-zA-Z0-9\/\=\?\&\ \:\/\.\-]*)\]',
464 464 '<div class="metatag" tag="see">see =&gt; \\1 </div>', value)
465 465 value = re.sub(r'\[license\ \=\>\ *([a-zA-Z0-9\/\=\?\&\ \:\/\.\-]*)\]',
466 466 '<div class="metatag" tag="license"><a href="http:\/\/www.opensource.org/licenses/\\1">\\1</a></div>', value)
467 467 value = re.sub(r'\[(requires|recommends|conflicts|base)\ \=\>\ *([a-zA-Z\-\/]*)\]',
468 468 '<div class="metatag" tag="\\1">\\1 =&gt; <a href="/\\2">\\2</a></div>', value)
469 469 value = re.sub(r'\[(lang|language)\ \=\>\ *([a-zA-Z\-\/\#\+]*)\]',
470 470 '<div class="metatag" tag="lang">\\2</div>', value)
471 471 value = re.sub(r'\[([a-z]+)\]',
472 472 '<div class="metatag" tag="\\1">\\1</div>', value)
473 473
474 474 return value
475 475
476 476
477 477 def bool2icon(value):
478 478 """Returns True/False values represented as small html image of true/false
479 479 icons
480 480
481 481 :param value: bool value
482 482 """
483 483
484 484 if value is True:
485 485 return HTML.tag('img', src=url("/images/icons/accept.png"),
486 486 alt=_('True'))
487 487
488 488 if value is False:
489 489 return HTML.tag('img', src=url("/images/icons/cancel.png"),
490 490 alt=_('False'))
491 491
492 492 return value
493 493
494 494
495 495 def action_parser(user_log, feed=False, parse_cs=False):
496 496 """
497 497 This helper will action_map the specified string action into translated
498 498 fancy names with icons and links
499 499
500 500 :param user_log: user log instance
501 501 :param feed: use output for feeds (no html and fancy icons)
502 502 :param parse_cs: parse Changesets into VCS instances
503 503 """
504 504
505 505 action = user_log.action
506 506 action_params = ' '
507 507
508 508 x = action.split(':')
509 509
510 510 if len(x) > 1:
511 511 action, action_params = x
512 512
513 513 def get_cs_links():
514 514 revs_limit = 3 # display this amount always
515 515 revs_top_limit = 50 # show upto this amount of changesets hidden
516 516 revs_ids = action_params.split(',')
517 517 deleted = user_log.repository is None
518 518 if deleted:
519 519 return ','.join(revs_ids)
520 520
521 521 repo_name = user_log.repository.repo_name
522 522
523 523 def lnk(rev, repo_name):
524 524 if isinstance(rev, BaseChangeset) or isinstance(rev, AttributeDict):
525 525 lazy_cs = True
526 526 if getattr(rev, 'op', None) and getattr(rev, 'ref_name', None):
527 527 lazy_cs = False
528 528 lbl = '?'
529 529 if rev.op == 'delete_branch':
530 530 lbl = '%s' % _('Deleted branch: %s') % rev.ref_name
531 531 title = ''
532 532 elif rev.op == 'tag':
533 533 lbl = '%s' % _('Created tag: %s') % rev.ref_name
534 534 title = ''
535 535 _url = '#'
536 536
537 537 else:
538 538 lbl = '%s' % (rev.short_id[:8])
539 539 _url = url('changeset_home', repo_name=repo_name,
540 540 revision=rev.raw_id)
541 541 title = tooltip(rev.message)
542 542 else:
543 543 ## changeset cannot be found/striped/removed etc.
544 544 lbl = ('%s' % rev)[:12]
545 545 _url = '#'
546 546 title = _('Changeset not found')
547 547 if parse_cs:
548 548 return link_to(lbl, _url, title=title, class_='tooltip')
549 549 return link_to(lbl, _url, raw_id=rev.raw_id, repo_name=repo_name,
550 550 class_='lazy-cs' if lazy_cs else '')
551 551
552 552 revs = []
553 553 if len(filter(lambda v: v != '', revs_ids)) > 0:
554 554 repo = None
555 555 for rev in revs_ids[:revs_top_limit]:
556 556 _op = _name = None
557 557 if len(rev.split('=>')) == 2:
558 558 _op, _name = rev.split('=>')
559 559
560 560 # we want parsed changesets, or new log store format is bad
561 561 if parse_cs:
562 562 try:
563 563 if repo is None:
564 564 repo = user_log.repository.scm_instance
565 565 _rev = repo.get_changeset(rev)
566 566 revs.append(_rev)
567 567 except ChangesetDoesNotExistError:
568 568 log.error('cannot find revision %s in this repo' % rev)
569 569 revs.append(rev)
570 570 continue
571 571 else:
572 572 _rev = AttributeDict({
573 573 'short_id': rev[:12],
574 574 'raw_id': rev,
575 575 'message': '',
576 576 'op': _op,
577 577 'ref_name': _name
578 578 })
579 579 revs.append(_rev)
580 580 cs_links = []
581 581 cs_links.append(" " + ', '.join(
582 582 [lnk(rev, repo_name) for rev in revs[:revs_limit]]
583 583 )
584 584 )
585 585
586 586 compare_view = (
587 587 ' <div class="compare_view tooltip" title="%s">'
588 588 '<a href="%s">%s</a> </div>' % (
589 589 _('Show all combined changesets %s->%s') % (
590 590 revs_ids[0][:12], revs_ids[-1][:12]
591 591 ),
592 592 url('changeset_home', repo_name=repo_name,
593 593 revision='%s...%s' % (revs_ids[0], revs_ids[-1])
594 594 ),
595 595 _('compare view')
596 596 )
597 597 )
598 598
599 599 # if we have exactly one more than normally displayed
600 600 # just display it, takes less space than displaying
601 601 # "and 1 more revisions"
602 602 if len(revs_ids) == revs_limit + 1:
603 603 rev = revs[revs_limit]
604 604 cs_links.append(", " + lnk(rev, repo_name))
605 605
606 606 # hidden-by-default ones
607 607 if len(revs_ids) > revs_limit + 1:
608 608 uniq_id = revs_ids[0]
609 609 html_tmpl = (
610 610 '<span> %s <a class="show_more" id="_%s" '
611 611 'href="#more">%s</a> %s</span>'
612 612 )
613 613 if not feed:
614 614 cs_links.append(html_tmpl % (
615 615 _('and'),
616 616 uniq_id, _('%s more') % (len(revs_ids) - revs_limit),
617 617 _('revisions')
618 618 )
619 619 )
620 620
621 621 if not feed:
622 622 html_tmpl = '<span id="%s" style="display:none">, %s </span>'
623 623 else:
624 624 html_tmpl = '<span id="%s"> %s </span>'
625 625
626 626 morelinks = ', '.join(
627 627 [lnk(rev, repo_name) for rev in revs[revs_limit:]]
628 628 )
629 629
630 630 if len(revs_ids) > revs_top_limit:
631 631 morelinks += ', ...'
632 632
633 633 cs_links.append(html_tmpl % (uniq_id, morelinks))
634 634 if len(revs) > 1:
635 635 cs_links.append(compare_view)
636 636 return ''.join(cs_links)
637 637
638 638 def get_fork_name():
639 639 repo_name = action_params
640 640 _url = url('summary_home', repo_name=repo_name)
641 641 return _('fork name %s') % link_to(action_params, _url)
642 642
643 643 def get_user_name():
644 644 user_name = action_params
645 645 return user_name
646 646
647 647 def get_users_group():
648 648 group_name = action_params
649 649 return group_name
650 650
651 651 def get_pull_request():
652 652 pull_request_id = action_params
653 653 deleted = user_log.repository is None
654 654 if deleted:
655 655 repo_name = user_log.repository_name
656 656 else:
657 657 repo_name = user_log.repository.repo_name
658 658 return link_to(_('Pull request #%s') % pull_request_id,
659 659 url('pullrequest_show', repo_name=repo_name,
660 660 pull_request_id=pull_request_id))
661 661
662 662 # action : translated str, callback(extractor), icon
663 663 action_map = {
664 664 'user_deleted_repo': (_('[deleted] repository'),
665 665 None, 'database_delete.png'),
666 666 'user_created_repo': (_('[created] repository'),
667 667 None, 'database_add.png'),
668 668 'user_created_fork': (_('[created] repository as fork'),
669 669 None, 'arrow_divide.png'),
670 670 'user_forked_repo': (_('[forked] repository'),
671 671 get_fork_name, 'arrow_divide.png'),
672 672 'user_updated_repo': (_('[updated] repository'),
673 673 None, 'database_edit.png'),
674 674 'admin_deleted_repo': (_('[delete] repository'),
675 675 None, 'database_delete.png'),
676 676 'admin_created_repo': (_('[created] repository'),
677 677 None, 'database_add.png'),
678 678 'admin_forked_repo': (_('[forked] repository'),
679 679 None, 'arrow_divide.png'),
680 680 'admin_updated_repo': (_('[updated] repository'),
681 681 None, 'database_edit.png'),
682 682 'admin_created_user': (_('[created] user'),
683 683 get_user_name, 'user_add.png'),
684 684 'admin_updated_user': (_('[updated] user'),
685 685 get_user_name, 'user_edit.png'),
686 686 'admin_created_users_group': (_('[created] users group'),
687 687 get_users_group, 'group_add.png'),
688 688 'admin_updated_users_group': (_('[updated] users group'),
689 689 get_users_group, 'group_edit.png'),
690 690 'user_commented_revision': (_('[commented] on revision in repository'),
691 691 get_cs_links, 'comment_add.png'),
692 692 'user_commented_pull_request': (_('[commented] on pull request for'),
693 693 get_pull_request, 'comment_add.png'),
694 694 'user_closed_pull_request': (_('[closed] pull request for'),
695 695 get_pull_request, 'tick.png'),
696 696 'push': (_('[pushed] into'),
697 697 get_cs_links, 'script_add.png'),
698 698 'push_local': (_('[committed via RhodeCode] into repository'),
699 699 get_cs_links, 'script_edit.png'),
700 700 'push_remote': (_('[pulled from remote] into repository'),
701 701 get_cs_links, 'connect.png'),
702 702 'pull': (_('[pulled] from'),
703 703 None, 'down_16.png'),
704 704 'started_following_repo': (_('[started following] repository'),
705 705 None, 'heart_add.png'),
706 706 'stopped_following_repo': (_('[stopped following] repository'),
707 707 None, 'heart_delete.png'),
708 708 }
709 709
710 710 action_str = action_map.get(action, action)
711 711 if feed:
712 712 action = action_str[0].replace('[', '').replace(']', '')
713 713 else:
714 714 action = action_str[0]\
715 715 .replace('[', '<span class="journal_highlight">')\
716 716 .replace(']', '</span>')
717 717
718 718 action_params_func = lambda: ""
719 719
720 720 if callable(action_str[1]):
721 721 action_params_func = action_str[1]
722 722
723 723 def action_parser_icon():
724 724 action = user_log.action
725 725 action_params = None
726 726 x = action.split(':')
727 727
728 728 if len(x) > 1:
729 729 action, action_params = x
730 730
731 731 tmpl = """<img src="%s%s" alt="%s"/>"""
732 732 ico = action_map.get(action, ['', '', ''])[2]
733 733 return literal(tmpl % ((url('/images/icons/')), ico, action))
734 734
735 735 # returned callbacks we need to call to get
736 736 return [lambda: literal(action), action_params_func, action_parser_icon]
737 737
738 738
739 739
740 740 #==============================================================================
741 741 # PERMS
742 742 #==============================================================================
743 743 from rhodecode.lib.auth import HasPermissionAny, HasPermissionAll, \
744 744 HasRepoPermissionAny, HasRepoPermissionAll
745 745
746 746
747 747 #==============================================================================
748 748 # GRAVATAR URL
749 749 #==============================================================================
750 750
751 751 def gravatar_url(email_address, size=30):
752 752 from pylons import url # doh, we need to re-import url to mock it later
753 753
754 754 if (not str2bool(config['app_conf'].get('use_gravatar')) or
755 755 not email_address or email_address == 'anonymous@rhodecode.org'):
756 756 f = lambda a, l: min(l, key=lambda x: abs(x - a))
757 757 return url("/images/user%s.png" % f(size, [14, 16, 20, 24, 30]))
758 758
759 759 if(str2bool(config['app_conf'].get('use_gravatar')) and
760 760 config['app_conf'].get('alternative_gravatar_url')):
761 761 tmpl = config['app_conf'].get('alternative_gravatar_url', '')
762 762 parsed_url = urlparse.urlparse(url.current(qualified=True))
763 763 tmpl = tmpl.replace('{email}', email_address)\
764 764 .replace('{md5email}', hashlib.md5(email_address.lower()).hexdigest()) \
765 765 .replace('{netloc}', parsed_url.netloc)\
766 766 .replace('{scheme}', parsed_url.scheme)\
767 767 .replace('{size}', str(size))
768 768 return tmpl
769 769
770 770 ssl_enabled = 'https' == request.environ.get('wsgi.url_scheme')
771 771 default = 'identicon'
772 772 baseurl_nossl = "http://www.gravatar.com/avatar/"
773 773 baseurl_ssl = "https://secure.gravatar.com/avatar/"
774 774 baseurl = baseurl_ssl if ssl_enabled else baseurl_nossl
775 775
776 776 if isinstance(email_address, unicode):
777 777 #hashlib crashes on unicode items
778 778 email_address = safe_str(email_address)
779 779 # construct the url
780 780 gravatar_url = baseurl + hashlib.md5(email_address.lower()).hexdigest() + "?"
781 781 gravatar_url += urllib.urlencode({'d': default, 's': str(size)})
782 782
783 783 return gravatar_url
784 784
785 785
786 786 #==============================================================================
787 787 # REPO PAGER, PAGER FOR REPOSITORY
788 788 #==============================================================================
789 789 class RepoPage(Page):
790 790
791 791 def __init__(self, collection, page=1, items_per_page=20,
792 792 item_count=None, url=None, **kwargs):
793 793
794 794 """Create a "RepoPage" instance. special pager for paging
795 795 repository
796 796 """
797 797 self._url_generator = url
798 798
799 799 # Safe the kwargs class-wide so they can be used in the pager() method
800 800 self.kwargs = kwargs
801 801
802 802 # Save a reference to the collection
803 803 self.original_collection = collection
804 804
805 805 self.collection = collection
806 806
807 807 # The self.page is the number of the current page.
808 808 # The first page has the number 1!
809 809 try:
810 810 self.page = int(page) # make it int() if we get it as a string
811 811 except (ValueError, TypeError):
812 812 self.page = 1
813 813
814 814 self.items_per_page = items_per_page
815 815
816 816 # Unless the user tells us how many items the collections has
817 817 # we calculate that ourselves.
818 818 if item_count is not None:
819 819 self.item_count = item_count
820 820 else:
821 821 self.item_count = len(self.collection)
822 822
823 823 # Compute the number of the first and last available page
824 824 if self.item_count > 0:
825 825 self.first_page = 1
826 826 self.page_count = int(math.ceil(float(self.item_count) /
827 827 self.items_per_page))
828 828 self.last_page = self.first_page + self.page_count - 1
829 829
830 830 # Make sure that the requested page number is the range of
831 831 # valid pages
832 832 if self.page > self.last_page:
833 833 self.page = self.last_page
834 834 elif self.page < self.first_page:
835 835 self.page = self.first_page
836 836
837 837 # Note: the number of items on this page can be less than
838 838 # items_per_page if the last page is not full
839 839 self.first_item = max(0, (self.item_count) - (self.page *
840 840 items_per_page))
841 841 self.last_item = ((self.item_count - 1) - items_per_page *
842 842 (self.page - 1))
843 843
844 844 self.items = list(self.collection[self.first_item:self.last_item + 1])
845 845
846 846 # Links to previous and next page
847 847 if self.page > self.first_page:
848 848 self.previous_page = self.page - 1
849 849 else:
850 850 self.previous_page = None
851 851
852 852 if self.page < self.last_page:
853 853 self.next_page = self.page + 1
854 854 else:
855 855 self.next_page = None
856 856
857 857 # No items available
858 858 else:
859 859 self.first_page = None
860 860 self.page_count = 0
861 861 self.last_page = None
862 862 self.first_item = None
863 863 self.last_item = None
864 864 self.previous_page = None
865 865 self.next_page = None
866 866 self.items = []
867 867
868 868 # This is a subclass of the 'list' type. Initialise the list now.
869 869 list.__init__(self, reversed(self.items))
870 870
871 871
872 872 def changed_tooltip(nodes):
873 873 """
874 874 Generates a html string for changed nodes in changeset page.
875 875 It limits the output to 30 entries
876 876
877 877 :param nodes: LazyNodesGenerator
878 878 """
879 879 if nodes:
880 880 pref = ': <br/> '
881 881 suf = ''
882 882 if len(nodes) > 30:
883 883 suf = '<br/>' + _(' and %s more') % (len(nodes) - 30)
884 884 return literal(pref + '<br/> '.join([safe_unicode(x.path)
885 885 for x in nodes[:30]]) + suf)
886 886 else:
887 887 return ': ' + _('No Files')
888 888
889 889
890 890 def repo_link(groups_and_repos, last_url=None):
891 891 """
892 892 Makes a breadcrumbs link to repo within a group
893 893 joins &raquo; on each group to create a fancy link
894 894
895 895 ex::
896 896 group >> subgroup >> repo
897 897
898 898 :param groups_and_repos:
899 899 :param last_url:
900 900 """
901 901 groups, repo_name = groups_and_repos
902 902 last_link = link_to(repo_name, last_url) if last_url else repo_name
903 903
904 904 if not groups:
905 905 if last_url:
906 906 return last_link
907 907 return repo_name
908 908 else:
909 909 def make_link(group):
910 910 return link_to(group.name,
911 911 url('repos_group_home', group_name=group.group_name))
912 912 return literal(' &raquo; '.join(map(make_link, groups) + [last_link]))
913 913
914 914
915 915 def fancy_file_stats(stats):
916 916 """
917 917 Displays a fancy two colored bar for number of added/deleted
918 918 lines of code on file
919 919
920 920 :param stats: two element list of added/deleted lines of code
921 921 """
922 922 def cgen(l_type, a_v, d_v):
923 923 mapping = {'tr': 'top-right-rounded-corner-mid',
924 924 'tl': 'top-left-rounded-corner-mid',
925 925 'br': 'bottom-right-rounded-corner-mid',
926 926 'bl': 'bottom-left-rounded-corner-mid'}
927 927 map_getter = lambda x: mapping[x]
928 928
929 929 if l_type == 'a' and d_v:
930 930 #case when added and deleted are present
931 931 return ' '.join(map(map_getter, ['tl', 'bl']))
932 932
933 933 if l_type == 'a' and not d_v:
934 934 return ' '.join(map(map_getter, ['tr', 'br', 'tl', 'bl']))
935 935
936 936 if l_type == 'd' and a_v:
937 937 return ' '.join(map(map_getter, ['tr', 'br']))
938 938
939 939 if l_type == 'd' and not a_v:
940 940 return ' '.join(map(map_getter, ['tr', 'br', 'tl', 'bl']))
941 941
942 942 a, d = stats[0], stats[1]
943 943 width = 100
944 944
945 945 if a == 'b':
946 946 #binary mode
947 947 b_d = '<div class="bin%s %s" style="width:100%%">%s</div>' % (d, cgen('a', a_v='', d_v=0), 'bin')
948 948 b_a = '<div class="bin1" style="width:0%%">%s</div>' % ('bin')
949 949 return literal('<div style="width:%spx">%s%s</div>' % (width, b_a, b_d))
950 950
951 951 t = stats[0] + stats[1]
952 952 unit = float(width) / (t or 1)
953 953
954 954 # needs > 9% of width to be visible or 0 to be hidden
955 955 a_p = max(9, unit * a) if a > 0 else 0
956 956 d_p = max(9, unit * d) if d > 0 else 0
957 957 p_sum = a_p + d_p
958 958
959 959 if p_sum > width:
960 960 #adjust the percentage to be == 100% since we adjusted to 9
961 961 if a_p > d_p:
962 962 a_p = a_p - (p_sum - width)
963 963 else:
964 964 d_p = d_p - (p_sum - width)
965 965
966 966 a_v = a if a > 0 else ''
967 967 d_v = d if d > 0 else ''
968 968
969 969 d_a = '<div class="added %s" style="width:%s%%">%s</div>' % (
970 970 cgen('a', a_v, d_v), a_p, a_v
971 971 )
972 972 d_d = '<div class="deleted %s" style="width:%s%%">%s</div>' % (
973 973 cgen('d', a_v, d_v), d_p, d_v
974 974 )
975 975 return literal('<div style="width:%spx">%s%s</div>' % (width, d_a, d_d))
976 976
977 977
978 978 def urlify_text(text_):
979 979
980 980 url_pat = re.compile(r'''(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]'''
981 981 '''|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)''')
982 982
983 983 def url_func(match_obj):
984 984 url_full = match_obj.groups()[0]
985 985 return '<a href="%(url)s">%(url)s</a>' % ({'url': url_full})
986 986
987 987 return literal(url_pat.sub(url_func, text_))
988 988
989 989
990 990 def urlify_changesets(text_, repository):
991 991 """
992 992 Extract revision ids from changeset and make link from them
993 993
994 994 :param text_:
995 995 :param repository:
996 996 """
997 997
998 998 URL_PAT = re.compile(r'([0-9a-fA-F]{12,})')
999 999
1000 1000 def url_func(match_obj):
1001 1001 rev = match_obj.groups()[0]
1002 1002 pref = ''
1003 1003 if match_obj.group().startswith(' '):
1004 1004 pref = ' '
1005 1005 tmpl = (
1006 1006 '%(pref)s<a class="%(cls)s" href="%(url)s">'
1007 1007 '%(rev)s'
1008 1008 '</a>'
1009 1009 )
1010 1010 return tmpl % {
1011 1011 'pref': pref,
1012 1012 'cls': 'revision-link',
1013 1013 'url': url('changeset_home', repo_name=repository, revision=rev),
1014 1014 'rev': rev,
1015 1015 }
1016 1016
1017 1017 newtext = URL_PAT.sub(url_func, text_)
1018 1018
1019 1019 return newtext
1020 1020
1021 1021
1022 1022 def urlify_commit(text_, repository=None, link_=None):
1023 1023 """
1024 1024 Parses given text message and makes proper links.
1025 1025 issues are linked to given issue-server, and rest is a changeset link
1026 1026 if link_ is given, in other case it's a plain text
1027 1027
1028 1028 :param text_:
1029 1029 :param repository:
1030 1030 :param link_: changeset link
1031 1031 """
1032 1032 import traceback
1033 1033
1034 1034 def escaper(string):
1035 1035 return string.replace('<', '&lt;').replace('>', '&gt;')
1036 1036
1037 1037 def linkify_others(t, l):
1038 1038 urls = re.compile(r'(\<a.*?\<\/a\>)',)
1039 1039 links = []
1040 1040 for e in urls.split(t):
1041 1041 if not urls.match(e):
1042 1042 links.append('<a class="message-link" href="%s">%s</a>' % (l, e))
1043 1043 else:
1044 1044 links.append(e)
1045 1045
1046 1046 return ''.join(links)
1047 1047
1048 1048 # urlify changesets - extrac revisions and make link out of them
1049 1049 newtext = urlify_changesets(escaper(text_), repository)
1050 1050
1051 1051 try:
1052 1052 conf = config['app_conf']
1053 1053
1054 1054 # allow multiple issue servers to be used
1055 1055 valid_indices = [
1056 1056 x.group(1)
1057 1057 for x in map(lambda x: re.match(r'issue_pat(.*)', x), conf.keys())
1058 1058 if x and 'issue_server_link%s' % x.group(1) in conf
1059 1059 and 'issue_prefix%s' % x.group(1) in conf
1060 1060 ]
1061 1061
1062 1062 log.debug('found issue server suffixes `%s` during valuation of: %s'
1063 1063 % (','.join(valid_indices), newtext))
1064 1064
1065 1065 for pattern_index in valid_indices:
1066 1066 ISSUE_PATTERN = conf.get('issue_pat%s' % pattern_index)
1067 1067 ISSUE_SERVER_LNK = conf.get('issue_server_link%s' % pattern_index)
1068 1068 ISSUE_PREFIX = conf.get('issue_prefix%s' % pattern_index)
1069 1069
1070 1070 log.debug('pattern suffix `%s` PAT:%s SERVER_LINK:%s PREFIX:%s'
1071 1071 % (pattern_index, ISSUE_PATTERN, ISSUE_SERVER_LNK,
1072 1072 ISSUE_PREFIX))
1073 1073
1074 1074 URL_PAT = re.compile(r'%s' % ISSUE_PATTERN)
1075 1075
1076 1076 def url_func(match_obj):
1077 1077 pref = ''
1078 1078 if match_obj.group().startswith(' '):
1079 1079 pref = ' '
1080 1080
1081 1081 issue_id = ''.join(match_obj.groups())
1082 1082 tmpl = (
1083 1083 '%(pref)s<a class="%(cls)s" href="%(url)s">'
1084 1084 '%(issue-prefix)s%(id-repr)s'
1085 1085 '</a>'
1086 1086 )
1087 1087 url = ISSUE_SERVER_LNK.replace('{id}', issue_id)
1088 1088 if repository:
1089 1089 url = url.replace('{repo}', repository)
1090 1090 repo_name = repository.split(URL_SEP)[-1]
1091 1091 url = url.replace('{repo_name}', repo_name)
1092 1092
1093 1093 return tmpl % {
1094 1094 'pref': pref,
1095 1095 'cls': 'issue-tracker-link',
1096 1096 'url': url,
1097 1097 'id-repr': issue_id,
1098 1098 'issue-prefix': ISSUE_PREFIX,
1099 1099 'serv': ISSUE_SERVER_LNK,
1100 1100 }
1101 1101 newtext = URL_PAT.sub(url_func, newtext)
1102 1102 log.debug('processed prefix:`%s` => %s' % (pattern_index, newtext))
1103 1103
1104 1104 # if we actually did something above
1105 1105 if link_:
1106 1106 # wrap not links into final link => link_
1107 1107 newtext = linkify_others(newtext, link_)
1108 1108 except:
1109 1109 log.error(traceback.format_exc())
1110 1110 pass
1111 1111
1112 1112 return literal(newtext)
1113 1113
1114 1114
1115 1115 def rst(source):
1116 1116 return literal('<div class="rst-block">%s</div>' %
1117 1117 MarkupRenderer.rst(source))
1118 1118
1119 1119
1120 1120 def rst_w_mentions(source):
1121 1121 """
1122 1122 Wrapped rst renderer with @mention highlighting
1123 1123
1124 1124 :param source:
1125 1125 """
1126 1126 return literal('<div class="rst-block">%s</div>' %
1127 1127 MarkupRenderer.rst_with_mentions(source))
1128 1128
1129 1129
1130 1130 def changeset_status(repo, revision):
1131 1131 return ChangesetStatusModel().get_status(repo, revision)
1132 1132
1133 1133
1134 1134 def changeset_status_lbl(changeset_status):
1135 1135 return dict(ChangesetStatus.STATUSES).get(changeset_status)
1136 1136
1137 1137
1138 1138 def get_permission_name(key):
1139 1139 return dict(Permission.PERMS).get(key)
1140 1140
1141 1141
1142 1142 def journal_filter_help():
1143 1143 return _(textwrap.dedent('''
1144 1144 Example filter terms:
1145 1145 repository:vcs
1146 1146 username:marcin
1147 1147 action:*push*
1148 1148 ip:127.0.0.1
1149 1149 date:20120101
1150 1150 date:[20120101100000 TO 20120102]
1151 1151
1152 1152 Generate wildcards using '*' character:
1153 1153 "repositroy:vcs*" - search everything starting with 'vcs'
1154 1154 "repository:*vcs*" - search for repository containing 'vcs'
1155 1155
1156 1156 Optional AND / OR operators in queries
1157 1157 "repository:vcs OR repository:test"
1158 1158 "username:test AND repository:test*"
1159 1159 '''))
1160 1160
1161 1161
1162 1162 def not_mapped_error(repo_name):
1163 1163 flash(_('%s repository is not mapped to db perhaps'
1164 1164 ' it was created or renamed from the filesystem'
1165 1165 ' please run the application again'
1166 1166 ' in order to rescan repositories') % repo_name, category='error')
1167 1167
1168 1168
1169 1169 def ip_range(ip_addr):
1170 1170 from rhodecode.model.db import UserIpMap
1171 1171 s, e = UserIpMap._get_ip_range(ip_addr)
1172 1172 return '%s - %s' % (s, e)
1173
@@ -1,754 +1,754 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 rhodecode.lib.utils
4 4 ~~~~~~~~~~~~~~~~~~~
5 5
6 6 Utilities library for RhodeCode
7 7
8 8 :created_on: Apr 18, 2010
9 9 :author: marcink
10 10 :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
11 11 :license: GPLv3, see COPYING for more details.
12 12 """
13 13 # This program is free software: you can redistribute it and/or modify
14 14 # it under the terms of the GNU General Public License as published by
15 15 # the Free Software Foundation, either version 3 of the License, or
16 16 # (at your option) any later version.
17 17 #
18 18 # This program is distributed in the hope that it will be useful,
19 19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 21 # GNU General Public License for more details.
22 22 #
23 23 # You should have received a copy of the GNU General Public License
24 24 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25 25
26 26 import os
27 27 import re
28 28 import logging
29 29 import datetime
30 30 import traceback
31 31 import paste
32 32 import beaker
33 33 import tarfile
34 34 import shutil
35 35 import decorator
36 36 import warnings
37 37 from os.path import abspath
38 38 from os.path import dirname as dn, join as jn
39 39
40 40 from paste.script.command import Command, BadCommand
41 41
42 42 from mercurial import ui, config
43 43
44 44 from webhelpers.text import collapse, remove_formatting, strip_tags
45 45
46 46 from rhodecode.lib.vcs import get_backend
47 47 from rhodecode.lib.vcs.backends.base import BaseChangeset
48 48 from rhodecode.lib.vcs.utils.lazy import LazyProperty
49 49 from rhodecode.lib.vcs.utils.helpers import get_scm
50 50 from rhodecode.lib.vcs.exceptions import VCSError
51 51
52 52 from rhodecode.lib.caching_query import FromCache
53 53
54 54 from rhodecode.model import meta
55 55 from rhodecode.model.db import Repository, User, RhodeCodeUi, \
56 56 UserLog, RepoGroup, RhodeCodeSetting, CacheInvalidation
57 57 from rhodecode.model.meta import Session
58 58 from rhodecode.model.repos_group import ReposGroupModel
59 59 from rhodecode.lib.utils2 import safe_str, safe_unicode
60 60 from rhodecode.lib.vcs.utils.fakemod import create_module
61 61
62 62 log = logging.getLogger(__name__)
63 63
64 64 REMOVED_REPO_PAT = re.compile(r'rm__\d{8}_\d{6}_\d{6}__.*')
65 65
66 66
67 67 def recursive_replace(str_, replace=' '):
68 68 """
69 69 Recursive replace of given sign to just one instance
70 70
71 71 :param str_: given string
72 72 :param replace: char to find and replace multiple instances
73 73
74 74 Examples::
75 75 >>> recursive_replace("Mighty---Mighty-Bo--sstones",'-')
76 76 'Mighty-Mighty-Bo-sstones'
77 77 """
78 78
79 79 if str_.find(replace * 2) == -1:
80 80 return str_
81 81 else:
82 82 str_ = str_.replace(replace * 2, replace)
83 83 return recursive_replace(str_, replace)
84 84
85 85
86 86 def repo_name_slug(value):
87 87 """
88 88 Return slug of name of repository
89 89 This function is called on each creation/modification
90 90 of repository to prevent bad names in repo
91 91 """
92 92
93 93 slug = remove_formatting(value)
94 94 slug = strip_tags(slug)
95 95
96 96 for c in """`?=[]\;'"<>,/~!@#$%^&*()+{}|: """:
97 97 slug = slug.replace(c, '-')
98 98 slug = recursive_replace(slug, '-')
99 99 slug = collapse(slug, '-')
100 100 return slug
101 101
102 102
103 103 def get_repo_slug(request):
104 104 _repo = request.environ['pylons.routes_dict'].get('repo_name')
105 105 if _repo:
106 106 _repo = _repo.rstrip('/')
107 107 return _repo
108 108
109 109
110 110 def get_repos_group_slug(request):
111 111 _group = request.environ['pylons.routes_dict'].get('group_name')
112 112 if _group:
113 113 _group = _group.rstrip('/')
114 114 return _group
115 115
116 116
117 117 def action_logger(user, action, repo, ipaddr='', sa=None, commit=False):
118 118 """
119 119 Action logger for various actions made by users
120 120
121 121 :param user: user that made this action, can be a unique username string or
122 122 object containing user_id attribute
123 123 :param action: action to log, should be on of predefined unique actions for
124 124 easy translations
125 125 :param repo: string name of repository or object containing repo_id,
126 126 that action was made on
127 127 :param ipaddr: optional ip address from what the action was made
128 128 :param sa: optional sqlalchemy session
129 129
130 130 """
131 131
132 132 if not sa:
133 133 sa = meta.Session()
134 134
135 135 try:
136 136 if hasattr(user, 'user_id'):
137 137 user_obj = User.get(user.user_id)
138 138 elif isinstance(user, basestring):
139 139 user_obj = User.get_by_username(user)
140 140 else:
141 141 raise Exception('You have to provide a user object or a username')
142 142
143 143 if hasattr(repo, 'repo_id'):
144 144 repo_obj = Repository.get(repo.repo_id)
145 145 repo_name = repo_obj.repo_name
146 146 elif isinstance(repo, basestring):
147 147 repo_name = repo.lstrip('/')
148 148 repo_obj = Repository.get_by_repo_name(repo_name)
149 149 else:
150 150 repo_obj = None
151 151 repo_name = ''
152 152
153 153 user_log = UserLog()
154 154 user_log.user_id = user_obj.user_id
155 155 user_log.username = user_obj.username
156 156 user_log.action = safe_unicode(action)
157 157
158 158 user_log.repository = repo_obj
159 159 user_log.repository_name = repo_name
160 160
161 161 user_log.action_date = datetime.datetime.now()
162 162 user_log.user_ip = ipaddr
163 163 sa.add(user_log)
164 164
165 165 log.info('Logging action %s on %s by %s' %
166 166 (action, safe_unicode(repo), user_obj))
167 167 if commit:
168 168 sa.commit()
169 169 except:
170 170 log.error(traceback.format_exc())
171 171 raise
172 172
173 173
174 174 def get_repos(path, recursive=False):
175 175 """
176 176 Scans given path for repos and return (name,(type,path)) tuple
177 177
178 178 :param path: path to scan for repositories
179 179 :param recursive: recursive search and return names with subdirs in front
180 180 """
181 181
182 182 # remove ending slash for better results
183 183 path = path.rstrip(os.sep)
184 184
185 185 def _get_repos(p):
186 186 if not os.access(p, os.W_OK):
187 187 return
188 188 for dirpath in os.listdir(p):
189 189 if os.path.isfile(os.path.join(p, dirpath)):
190 190 continue
191 191 cur_path = os.path.join(p, dirpath)
192 192 try:
193 193 scm_info = get_scm(cur_path)
194 194 yield scm_info[1].split(path, 1)[-1].lstrip(os.sep), scm_info
195 195 except VCSError:
196 196 if not recursive:
197 197 continue
198 198 #check if this dir containts other repos for recursive scan
199 199 rec_path = os.path.join(p, dirpath)
200 200 if os.path.isdir(rec_path):
201 201 for inner_scm in _get_repos(rec_path):
202 202 yield inner_scm
203 203
204 204 return _get_repos(path)
205 205
206 206
207 207 def is_valid_repo(repo_name, base_path, scm=None):
208 208 """
209 209 Returns True if given path is a valid repository False otherwise.
210 210 If scm param is given also compare if given scm is the same as expected
211 211 from scm parameter
212 212
213 213 :param repo_name:
214 214 :param base_path:
215 215 :param scm:
216 216
217 217 :return True: if given path is a valid repository
218 218 """
219 219 full_path = os.path.join(safe_str(base_path), safe_str(repo_name))
220 220
221 221 try:
222 222 scm_ = get_scm(full_path)
223 223 if scm:
224 224 return scm_[0] == scm
225 225 return True
226 226 except VCSError:
227 227 return False
228 228
229 229
230 230 def is_valid_repos_group(repos_group_name, base_path):
231 231 """
232 232 Returns True if given path is a repos group False otherwise
233 233
234 234 :param repo_name:
235 235 :param base_path:
236 236 """
237 237 full_path = os.path.join(safe_str(base_path), safe_str(repos_group_name))
238 238
239 239 # check if it's not a repo
240 240 if is_valid_repo(repos_group_name, base_path):
241 241 return False
242 242
243 243 try:
244 244 # we need to check bare git repos at higher level
245 245 # since we might match branches/hooks/info/objects or possible
246 246 # other things inside bare git repo
247 247 get_scm(os.path.dirname(full_path))
248 248 return False
249 249 except VCSError:
250 250 pass
251 251
252 252 # check if it's a valid path
253 253 if os.path.isdir(full_path):
254 254 return True
255 255
256 256 return False
257 257
258 258
259 259 def ask_ok(prompt, retries=4, complaint='Yes or no please!'):
260 260 while True:
261 261 ok = raw_input(prompt)
262 262 if ok in ('y', 'ye', 'yes'):
263 263 return True
264 264 if ok in ('n', 'no', 'nop', 'nope'):
265 265 return False
266 266 retries = retries - 1
267 267 if retries < 0:
268 268 raise IOError
269 269 print complaint
270 270
271 271 #propagated from mercurial documentation
272 272 ui_sections = ['alias', 'auth',
273 273 'decode/encode', 'defaults',
274 274 'diff', 'email',
275 275 'extensions', 'format',
276 276 'merge-patterns', 'merge-tools',
277 277 'hooks', 'http_proxy',
278 278 'smtp', 'patch',
279 279 'paths', 'profiling',
280 280 'server', 'trusted',
281 281 'ui', 'web', ]
282 282
283 283
284 284 def make_ui(read_from='file', path=None, checkpaths=True, clear_session=True):
285 285 """
286 286 A function that will read python rc files or database
287 287 and make an mercurial ui object from read options
288 288
289 289 :param path: path to mercurial config file
290 290 :param checkpaths: check the path
291 291 :param read_from: read from 'file' or 'db'
292 292 """
293 293
294 294 baseui = ui.ui()
295 295
296 296 # clean the baseui object
297 297 baseui._ocfg = config.config()
298 298 baseui._ucfg = config.config()
299 299 baseui._tcfg = config.config()
300 300
301 301 if read_from == 'file':
302 302 if not os.path.isfile(path):
303 303 log.debug('hgrc file is not present at %s, skipping...' % path)
304 304 return False
305 305 log.debug('reading hgrc from %s' % path)
306 306 cfg = config.config()
307 307 cfg.read(path)
308 308 for section in ui_sections:
309 309 for k, v in cfg.items(section):
310 310 log.debug('settings ui from file: [%s] %s=%s' % (section, k, v))
311 311 baseui.setconfig(safe_str(section), safe_str(k), safe_str(v))
312 312
313 313 elif read_from == 'db':
314 314 sa = meta.Session()
315 315 ret = sa.query(RhodeCodeUi)\
316 316 .options(FromCache("sql_cache_short", "get_hg_ui_settings"))\
317 317 .all()
318 318
319 319 hg_ui = ret
320 320 for ui_ in hg_ui:
321 321 if ui_.ui_active:
322 322 log.debug('settings ui from db: [%s] %s=%s', ui_.ui_section,
323 323 ui_.ui_key, ui_.ui_value)
324 324 baseui.setconfig(safe_str(ui_.ui_section), safe_str(ui_.ui_key),
325 325 safe_str(ui_.ui_value))
326 326 if ui_.ui_key == 'push_ssl':
327 327 # force set push_ssl requirement to False, rhodecode
328 328 # handles that
329 329 baseui.setconfig(safe_str(ui_.ui_section), safe_str(ui_.ui_key),
330 330 False)
331 331 if clear_session:
332 332 meta.Session.remove()
333 333 return baseui
334 334
335 335
336 336 def set_rhodecode_config(config):
337 337 """
338 338 Updates pylons config with new settings from database
339 339
340 340 :param config:
341 341 """
342 342 hgsettings = RhodeCodeSetting.get_app_settings()
343 343
344 344 for k, v in hgsettings.items():
345 345 config[k] = v
346 346
347 347
348 348 def invalidate_cache(cache_key, *args):
349 349 """
350 350 Puts cache invalidation task into db for
351 351 further global cache invalidation
352 352 """
353 353
354 354 from rhodecode.model.scm import ScmModel
355 355
356 356 if cache_key.startswith('get_repo_cached_'):
357 357 name = cache_key.split('get_repo_cached_')[-1]
358 358 ScmModel().mark_for_invalidation(name)
359 359
360 360
361 361 def map_groups(path):
362 362 """
363 363 Given a full path to a repository, create all nested groups that this
364 364 repo is inside. This function creates parent-child relationships between
365 365 groups and creates default perms for all new groups.
366 366
367 367 :param paths: full path to repository
368 368 """
369 369 sa = meta.Session()
370 370 groups = path.split(Repository.url_sep())
371 371 parent = None
372 372 group = None
373 373
374 374 # last element is repo in nested groups structure
375 375 groups = groups[:-1]
376 376 rgm = ReposGroupModel(sa)
377 377 for lvl, group_name in enumerate(groups):
378 378 group_name = '/'.join(groups[:lvl] + [group_name])
379 379 group = RepoGroup.get_by_group_name(group_name)
380 380 desc = '%s group' % group_name
381 381
382 382 # skip folders that are now removed repos
383 383 if REMOVED_REPO_PAT.match(group_name):
384 384 break
385 385
386 386 if group is None:
387 387 log.debug('creating group level: %s group_name: %s' % (lvl,
388 388 group_name))
389 389 group = RepoGroup(group_name, parent)
390 390 group.group_description = desc
391 391 sa.add(group)
392 392 rgm._create_default_perms(group)
393 393 sa.flush()
394 394 parent = group
395 395 return group
396 396
397 397
398 398 def repo2db_mapper(initial_repo_list, remove_obsolete=False,
399 399 install_git_hook=False):
400 400 """
401 401 maps all repos given in initial_repo_list, non existing repositories
402 402 are created, if remove_obsolete is True it also check for db entries
403 403 that are not in initial_repo_list and removes them.
404 404
405 405 :param initial_repo_list: list of repositories found by scanning methods
406 406 :param remove_obsolete: check for obsolete entries in database
407 407 :param install_git_hook: if this is True, also check and install githook
408 408 for a repo if missing
409 409 """
410 410 from rhodecode.model.repo import RepoModel
411 411 from rhodecode.model.scm import ScmModel
412 412 sa = meta.Session()
413 413 rm = RepoModel()
414 414 user = sa.query(User).filter(User.admin == True).first()
415 415 if user is None:
416 416 raise Exception('Missing administrative account!')
417 417 added = []
418 418
419 419 # # clear cache keys
420 420 # log.debug("Clearing cache keys now...")
421 421 # CacheInvalidation.clear_cache()
422 422 # sa.commit()
423 423
424 424 ##creation defaults
425 425 defs = RhodeCodeSetting.get_default_repo_settings(strip_prefix=True)
426 426 enable_statistics = defs.get('repo_enable_statistics')
427 427 enable_locking = defs.get('repo_enable_locking')
428 428 enable_downloads = defs.get('repo_enable_downloads')
429 429 private = defs.get('repo_private')
430 430
431 431 for name, repo in initial_repo_list.items():
432 432 group = map_groups(name)
433 433 db_repo = rm.get_by_repo_name(name)
434 434 # found repo that is on filesystem not in RhodeCode database
435 435 if not db_repo:
436 436 log.info('repository %s not found, creating now' % name)
437 437 added.append(name)
438 438 desc = (repo.description
439 439 if repo.description != 'unknown'
440 440 else '%s repository' % name)
441 441
442 442 new_repo = rm.create_repo(
443 443 repo_name=name,
444 444 repo_type=repo.alias,
445 445 description=desc,
446 446 repos_group=getattr(group, 'group_id', None),
447 447 owner=user,
448 448 just_db=True,
449 449 enable_locking=enable_locking,
450 450 enable_downloads=enable_downloads,
451 451 enable_statistics=enable_statistics,
452 452 private=private
453 453 )
454 454 # we added that repo just now, and make sure it has githook
455 455 # installed
456 456 if new_repo.repo_type == 'git':
457 457 ScmModel().install_git_hook(new_repo.scm_instance)
458 458 new_repo.update_changeset_cache()
459 459 elif install_git_hook:
460 460 if db_repo.repo_type == 'git':
461 461 ScmModel().install_git_hook(db_repo.scm_instance)
462 462 # during starting install all cache keys for all repositories in the
463 463 # system, this will register all repos and multiple instances
464 464 key, _prefix, _org_key = CacheInvalidation._get_key(name)
465 465 CacheInvalidation.invalidate(name)
466 466 log.debug("Creating a cache key for %s, instance_id %s"
467 467 % (name, _prefix or 'unknown'))
468 468
469 469 sa.commit()
470 470 removed = []
471 471 if remove_obsolete:
472 472 # remove from database those repositories that are not in the filesystem
473 473 for repo in sa.query(Repository).all():
474 474 if repo.repo_name not in initial_repo_list.keys():
475 475 log.debug("Removing non-existing repository found in db `%s`" %
476 476 repo.repo_name)
477 477 try:
478 478 sa.delete(repo)
479 479 sa.commit()
480 480 removed.append(repo.repo_name)
481 481 except:
482 482 #don't hold further removals on error
483 483 log.error(traceback.format_exc())
484 484 sa.rollback()
485 485
486 486 return added, removed
487 487
488 488
489 489 # set cache regions for beaker so celery can utilise it
490 490 def add_cache(settings):
491 491 cache_settings = {'regions': None}
492 492 for key in settings.keys():
493 493 for prefix in ['beaker.cache.', 'cache.']:
494 494 if key.startswith(prefix):
495 495 name = key.split(prefix)[1].strip()
496 496 cache_settings[name] = settings[key].strip()
497 497 if cache_settings['regions']:
498 498 for region in cache_settings['regions'].split(','):
499 499 region = region.strip()
500 500 region_settings = {}
501 501 for key, value in cache_settings.items():
502 502 if key.startswith(region):
503 503 region_settings[key.split('.')[1]] = value
504 504 region_settings['expire'] = int(region_settings.get('expire',
505 505 60))
506 506 region_settings.setdefault('lock_dir',
507 507 cache_settings.get('lock_dir'))
508 508 region_settings.setdefault('data_dir',
509 509 cache_settings.get('data_dir'))
510 510
511 511 if 'type' not in region_settings:
512 512 region_settings['type'] = cache_settings.get('type',
513 513 'memory')
514 514 beaker.cache.cache_regions[region] = region_settings
515 515
516 516
517 517 def load_rcextensions(root_path):
518 518 import rhodecode
519 519 from rhodecode.config import conf
520 520
521 521 path = os.path.join(root_path, 'rcextensions', '__init__.py')
522 522 if os.path.isfile(path):
523 523 rcext = create_module('rc', path)
524 524 EXT = rhodecode.EXTENSIONS = rcext
525 525 log.debug('Found rcextensions now loading %s...' % rcext)
526 526
527 527 # Additional mappings that are not present in the pygments lexers
528 528 conf.LANGUAGES_EXTENSIONS_MAP.update(getattr(EXT, 'EXTRA_MAPPINGS', {}))
529 529
530 530 #OVERRIDE OUR EXTENSIONS FROM RC-EXTENSIONS (if present)
531 531
532 532 if getattr(EXT, 'INDEX_EXTENSIONS', []) != []:
533 533 log.debug('settings custom INDEX_EXTENSIONS')
534 534 conf.INDEX_EXTENSIONS = getattr(EXT, 'INDEX_EXTENSIONS', [])
535 535
536 536 #ADDITIONAL MAPPINGS
537 537 log.debug('adding extra into INDEX_EXTENSIONS')
538 538 conf.INDEX_EXTENSIONS.extend(getattr(EXT, 'EXTRA_INDEX_EXTENSIONS', []))
539 539
540 540
541 541 #==============================================================================
542 542 # TEST FUNCTIONS AND CREATORS
543 543 #==============================================================================
544 544 def create_test_index(repo_location, config, full_index):
545 545 """
546 546 Makes default test index
547 547
548 548 :param config: test config
549 549 :param full_index:
550 550 """
551 551
552 552 from rhodecode.lib.indexers.daemon import WhooshIndexingDaemon
553 553 from rhodecode.lib.pidlock import DaemonLock, LockHeld
554 554
555 555 repo_location = repo_location
556 556
557 557 index_location = os.path.join(config['app_conf']['index_dir'])
558 558 if not os.path.exists(index_location):
559 559 os.makedirs(index_location)
560 560
561 561 try:
562 562 l = DaemonLock(file_=jn(dn(index_location), 'make_index.lock'))
563 563 WhooshIndexingDaemon(index_location=index_location,
564 564 repo_location=repo_location)\
565 565 .run(full_index=full_index)
566 566 l.release()
567 567 except LockHeld:
568 568 pass
569 569
570 570
571 571 def create_test_env(repos_test_path, config):
572 572 """
573 573 Makes a fresh database and
574 574 install test repository into tmp dir
575 575 """
576 576 from rhodecode.lib.db_manage import DbManage
577 577 from rhodecode.tests import HG_REPO, GIT_REPO, TESTS_TMP_PATH
578 578
579 579 # PART ONE create db
580 580 dbconf = config['sqlalchemy.db1.url']
581 581 log.debug('making test db %s' % dbconf)
582 582
583 583 # create test dir if it doesn't exist
584 584 if not os.path.isdir(repos_test_path):
585 585 log.debug('Creating testdir %s' % repos_test_path)
586 586 os.makedirs(repos_test_path)
587 587
588 588 dbmanage = DbManage(log_sql=True, dbconf=dbconf, root=config['here'],
589 589 tests=True)
590 590 dbmanage.create_tables(override=True)
591 591 dbmanage.create_settings(dbmanage.config_prompt(repos_test_path))
592 592 dbmanage.create_default_user()
593 593 dbmanage.admin_prompt()
594 594 dbmanage.create_permissions()
595 595 dbmanage.populate_default_permissions()
596 596 Session().commit()
597 597 # PART TWO make test repo
598 598 log.debug('making test vcs repositories')
599 599
600 600 idx_path = config['app_conf']['index_dir']
601 601 data_path = config['app_conf']['cache_dir']
602 602
603 603 #clean index and data
604 604 if idx_path and os.path.exists(idx_path):
605 605 log.debug('remove %s' % idx_path)
606 606 shutil.rmtree(idx_path)
607 607
608 608 if data_path and os.path.exists(data_path):
609 609 log.debug('remove %s' % data_path)
610 610 shutil.rmtree(data_path)
611 611
612 612 #CREATE DEFAULT TEST REPOS
613 613 cur_dir = dn(dn(abspath(__file__)))
614 614 tar = tarfile.open(jn(cur_dir, 'tests', "vcs_test_hg.tar.gz"))
615 615 tar.extractall(jn(TESTS_TMP_PATH, HG_REPO))
616 616 tar.close()
617 617
618 618 cur_dir = dn(dn(abspath(__file__)))
619 619 tar = tarfile.open(jn(cur_dir, 'tests', "vcs_test_git.tar.gz"))
620 620 tar.extractall(jn(TESTS_TMP_PATH, GIT_REPO))
621 621 tar.close()
622 622
623 623 #LOAD VCS test stuff
624 624 from rhodecode.tests.vcs import setup_package
625 625 setup_package()
626 626
627 627
628 628 #==============================================================================
629 629 # PASTER COMMANDS
630 630 #==============================================================================
631 631 class BasePasterCommand(Command):
632 632 """
633 633 Abstract Base Class for paster commands.
634 634
635 635 The celery commands are somewhat aggressive about loading
636 636 celery.conf, and since our module sets the `CELERY_LOADER`
637 637 environment variable to our loader, we have to bootstrap a bit and
638 638 make sure we've had a chance to load the pylons config off of the
639 639 command line, otherwise everything fails.
640 640 """
641 641 min_args = 1
642 642 min_args_error = "Please provide a paster config file as an argument."
643 643 takes_config_file = 1
644 644 requires_config_file = True
645 645
646 646 def notify_msg(self, msg, log=False):
647 647 """Make a notification to user, additionally if logger is passed
648 648 it logs this action using given logger
649 649
650 650 :param msg: message that will be printed to user
651 651 :param log: logging instance, to use to additionally log this message
652 652
653 653 """
654 654 if log and isinstance(log, logging):
655 655 log(msg)
656 656
657 657 def run(self, args):
658 658 """
659 659 Overrides Command.run
660 660
661 661 Checks for a config file argument and loads it.
662 662 """
663 663 if len(args) < self.min_args:
664 664 raise BadCommand(
665 665 self.min_args_error % {'min_args': self.min_args,
666 666 'actual_args': len(args)})
667 667
668 668 # Decrement because we're going to lob off the first argument.
669 669 # @@ This is hacky
670 670 self.min_args -= 1
671 671 self.bootstrap_config(args[0])
672 672 self.update_parser()
673 673 return super(BasePasterCommand, self).run(args[1:])
674 674
675 675 def update_parser(self):
676 676 """
677 677 Abstract method. Allows for the class's parser to be updated
678 678 before the superclass's `run` method is called. Necessary to
679 679 allow options/arguments to be passed through to the underlying
680 680 celery command.
681 681 """
682 682 raise NotImplementedError("Abstract Method.")
683 683
684 684 def bootstrap_config(self, conf):
685 685 """
686 686 Loads the pylons configuration.
687 687 """
688 688 from pylons import config as pylonsconfig
689 689
690 690 self.path_to_ini_file = os.path.realpath(conf)
691 691 conf = paste.deploy.appconfig('config:' + self.path_to_ini_file)
692 692 pylonsconfig.init_app(conf.global_conf, conf.local_conf)
693 693
694 694
695 695 def check_git_version():
696 696 """
697 697 Checks what version of git is installed in system, and issues a warning
698 698 if it's too old for RhodeCode to properly work.
699 699 """
700 700 import subprocess
701 701 from distutils.version import StrictVersion
702 702 from rhodecode import BACKENDS
703 703
704 704 p = subprocess.Popen('git --version', shell=True,
705 705 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
706 706 stdout, stderr = p.communicate()
707 707 ver = (stdout.split(' ')[-1] or '').strip() or '0.0.0'
708 708 if len(ver.split('.')) > 3:
709 709 #StrictVersion needs to be only 3 element type
710 710 ver = '.'.join(ver.split('.')[:3])
711 711 try:
712 712 _ver = StrictVersion(ver)
713 713 except:
714 714 _ver = StrictVersion('0.0.0')
715 715 stderr = traceback.format_exc()
716 716
717 717 req_ver = '1.7.4'
718 718 to_old_git = False
719 719 if _ver < StrictVersion(req_ver):
720 720 to_old_git = True
721 721
722 722 if 'git' in BACKENDS:
723 723 log.debug('GIT version detected: %s' % stdout)
724 724 if stderr:
725 725 log.warning('Unable to detect git version org error was:%r' % stderr)
726 726 elif to_old_git:
727 727 log.warning('RhodeCode detected git version %s, which is too old '
728 728 'for the system to function properly. Make sure '
729 729 'its version is at least %s' % (ver, req_ver))
730 730 return _ver
731 731
732 732
733 733 @decorator.decorator
734 734 def jsonify(func, *args, **kwargs):
735 735 """Action decorator that formats output for JSON
736 736
737 737 Given a function that will return content, this decorator will turn
738 738 the result into JSON, with a content-type of 'application/json' and
739 739 output it.
740 740
741 741 """
742 742 from pylons.decorators.util import get_pylons
743 743 from rhodecode.lib.ext_json import json
744 744 pylons = get_pylons(args)
745 745 pylons.response.headers['Content-Type'] = 'application/json; charset=utf-8'
746 746 data = func(*args, **kwargs)
747 747 if isinstance(data, (list, tuple)):
748 748 msg = "JSON responses with Array envelopes are susceptible to " \
749 749 "cross-site data leak attacks, see " \
750 750 "http://wiki.pylonshq.com/display/pylonsfaq/Warnings"
751 751 warnings.warn(msg, Warning, 2)
752 752 log.warning(msg)
753 753 log.debug("Returning JSON wrapped action output")
754 return json.dumps(data, encoding='utf-8') No newline at end of file
754 return json.dumps(data, encoding='utf-8')
@@ -1,56 +1,55 b''
1 1 ## -*- coding: utf-8 -*-
2 2 <%inherit file="/base/base.html"/>
3 3
4 4 <%def name="title()">
5 5 ${_('Admin journal')} - ${c.rhodecode_name}
6 6 </%def>
7 7
8 8 <%def name="breadcrumbs_links()">
9 9 <form id="filter_form">
10 10 <input class="q_filter_box ${'' if c.search_term else 'initial'}" id="j_filter" size="15" type="text" name="filter" value="${c.search_term or _('journal filter...')}"/>
11 11 <span class="tooltip" title="${h.tooltip(h.journal_filter_help())}">?</span>
12 12 <input type='submit' value="${_('filter')}" class="ui-btn" style="padding:0px 2px 0px 2px;margin:0px"/>
13 13 ${_('Admin journal')} - ${ungettext('%s entry', '%s entries', c.users_log.item_count) % (c.users_log.item_count)}
14 14 </form>
15 15 ${h.end_form()}
16 16 </%def>
17 17
18 18 <%def name="page_nav()">
19 19 ${self.menu('admin')}
20 20 </%def>
21 21 <%def name="main()">
22 22 <div class="box">
23 23 <!-- box / title -->
24 24 <div class="title">
25 25 ${self.breadcrumbs()}
26 26 </div>
27 27 <!-- end box / title -->
28 28 <div class="table">
29 29 <div id="user_log">
30 30 ${c.log_data}
31 31 </div>
32 32 </div>
33 33 </div>
34 34
35 35 <script>
36 36 YUE.on('j_filter','click',function(){
37 37 var jfilter = YUD.get('j_filter');
38 38 if(YUD.hasClass(jfilter, 'initial')){
39 39 jfilter.value = '';
40 40 }
41 41 });
42 42 var fix_j_filter_width = function(len){
43 43 YUD.setStyle(YUD.get('j_filter'),'width',Math.max(80, len*6.50)+'px');
44 44 }
45 45 YUE.on('j_filter','keyup',function(){
46 46 fix_j_filter_width(YUD.get('j_filter').value.length);
47 47 });
48 48 YUE.on('filter_form','submit',function(e){
49 49 YUE.preventDefault(e)
50 50 var val = YUD.get('j_filter').value;
51 51 window.location = "${url.current(filter='__FILTER__')}".replace('__FILTER__',val);
52 52 });
53 53 fix_j_filter_width(YUD.get('j_filter').value.length);
54 54 </script>
55 55 </%def>
56
@@ -1,19 +1,17 b''
1 1 ## -*- coding: utf-8 -*-
2 2 <%inherit file="main.html"/>
3 3
4 4 ${_('User %s opened pull request for repository %s and wants you to review changes.') % (('<b>%s</b>' % pr_user_created),pr_repo_url) |n}
5 5 <div>${_('title')}: ${pr_title}</div>
6 6 <div>${_('description')}:</div>
7 7 <div>${_('View this pull request here')}: ${pr_url}</div>
8 8 <p>
9 9 ${body}
10 10 </p>
11 11
12 12 <div>${_('revisions for reviewing')}</div>
13 13 <ul>
14 14 %for r in pr_revisions:
15 15 <li>${r}</li>
16 16 %endfor
17 17 </ul>
18
19
@@ -1,1 +1,1 b''
1 #TODO; write tests when we activate algo for permissions. No newline at end of file
1 #TODO; write tests when we activate algo for permissions.
General Comments 0
You need to be logged in to leave comments. Login now