##// END OF EJS Templates
helpers: python3 port
super-admin -
r5084:536057f6 default
parent child Browse files
Show More
@@ -1,2164 +1,2161 b''
1 1
2 2 # Copyright (C) 2010-2020 RhodeCode GmbH
3 3 #
4 4 # This program is free software: you can redistribute it and/or modify
5 5 # it under the terms of the GNU Affero General Public License, version 3
6 6 # (only), as published by the Free Software Foundation.
7 7 #
8 8 # This program is distributed in the hope that it will be useful,
9 9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 11 # GNU General Public License for more details.
12 12 #
13 13 # You should have received a copy of the GNU Affero General Public License
14 14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 15 #
16 16 # This program is dual-licensed. If you wish to learn more about the
17 17 # RhodeCode Enterprise Edition, including its added features, Support services,
18 18 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 19
20 20 """
21 21 Helper functions
22 22
23 23 Consists of functions to typically be used within templates, but also
24 24 available to Controllers. This module is available to both as 'h'.
25 25 """
26 26 import base64
27 27 import collections
28 28
29 29 import os
30 30 import random
31 31 import hashlib
32 from io import StringIO
32 import io
33 33 import textwrap
34 import urllib.request, urllib.parse, urllib.error
34 import urllib.request
35 import urllib.parse
36 import urllib.error
35 37 import math
36 38 import logging
37 39 import re
38 40 import time
39 41 import string
40 import hashlib
41 42 import regex
42 43 from collections import OrderedDict
43 44
44 45 import pygments
45 46 import itertools
46 47 import fnmatch
47 48 import bleach
48 49
49 50 from datetime import datetime
50 51 from functools import partial
51 52 from pygments.formatters.html import HtmlFormatter
52 53 from pygments.lexers import (
53 54 get_lexer_by_name, get_lexer_for_filename, get_lexer_for_mimetype)
54 55
55 56 from pyramid.threadlocal import get_current_request
56 57 from tempita import looper
57 58 from webhelpers2.html import literal, HTML, escape
58 59 from webhelpers2.html._autolink import _auto_link_urls
59 60 from webhelpers2.html.tools import (
60 61 button_to, highlight, js_obfuscate, strip_links, strip_tags)
61 62
62 63 from webhelpers2.text import (
63 64 chop_at, collapse, convert_accented_entities,
64 65 convert_misc_entities, lchop, plural, rchop, remove_formatting,
65 66 replace_whitespace, urlify, truncate, wrap_paragraphs)
66 67 from webhelpers2.date import time_ago_in_words
67 68
68 69 from webhelpers2.html.tags import (
69 70 _input, NotGiven, _make_safe_id_component as safeid,
70 71 form as insecure_form,
71 72 auto_discovery_link, checkbox, end_form, file,
72 73 hidden, image, javascript_link, link_to, link_to_if, link_to_unless, ol,
73 select as raw_select, stylesheet_link, submit, text, password, textarea,
74 stylesheet_link, submit, text, password, textarea,
74 75 ul, radio, Options)
75 76
76 77 from webhelpers2.number import format_byte_size
78 # python3.11 backport fixes for webhelpers2
79 from rhodecode.lib._vendor.webhelpers_backports import raw_select
77 80
78 81 from rhodecode.lib.action_parser import action_parser
79 82 from rhodecode.lib.pagination import Page, RepoPage, SqlPage
80 83 from rhodecode.lib import ext_json
81 84 from rhodecode.lib.ext_json import json
82 from rhodecode.lib.str_utils import safe_bytes
85 from rhodecode.lib.str_utils import safe_bytes, convert_special_chars
83 86 from rhodecode.lib.utils import repo_name_slug, get_custom_lexer
87 from rhodecode.lib.str_utils import safe_str
84 88 from rhodecode.lib.utils2 import (
85 str2bool, safe_unicode, safe_str,
89 str2bool,
86 90 get_commit_safe, datetime_to_time, time_to_datetime, time_to_utcdatetime,
87 91 AttributeDict, safe_int, md5, md5_safe, get_host_info)
88 92 from rhodecode.lib.markup_renderer import MarkupRenderer, relative_links
89 93 from rhodecode.lib.vcs.exceptions import CommitDoesNotExistError
90 94 from rhodecode.lib.vcs.backends.base import BaseChangeset, EmptyCommit
91 95 from rhodecode.lib.vcs.conf.settings import ARCHIVE_SPECS
92 96 from rhodecode.lib.index.search_utils import get_matching_line_offsets
93 97 from rhodecode.config.conf import DATE_FORMAT, DATETIME_FORMAT
94 98 from rhodecode.model.changeset_status import ChangesetStatusModel
95 99 from rhodecode.model.db import Permission, User, Repository, UserApiKeys, FileStore
96 100 from rhodecode.model.repo_group import RepoGroupModel
97 101 from rhodecode.model.settings import IssueTrackerSettingsModel
98 102
99 103
100 104 log = logging.getLogger(__name__)
101 105
102 106
103 107 DEFAULT_USER = User.DEFAULT_USER
104 108 DEFAULT_USER_EMAIL = User.DEFAULT_USER_EMAIL
105 109
106 110
107 111 def asset(path, ver=None, **kwargs):
108 112 """
109 113 Helper to generate a static asset file path for rhodecode assets
110 114
111 115 eg. h.asset('images/image.png', ver='3923')
112 116
113 117 :param path: path of asset
114 118 :param ver: optional version query param to append as ?ver=
115 119 """
116 120 request = get_current_request()
117 121 query = {}
118 122 query.update(kwargs)
119 123 if ver:
120 124 query = {'ver': ver}
121 125 return request.static_path(
122 126 'rhodecode:public/{}'.format(path), _query=query)
123 127
124 128
125 129 default_html_escape_table = {
126 ord('&'): u'&amp;',
127 ord('<'): u'&lt;',
128 ord('>'): u'&gt;',
129 ord('"'): u'&quot;',
130 ord("'"): u'&#39;',
130 ord('&'): '&amp;',
131 ord('<'): '&lt;',
132 ord('>'): '&gt;',
133 ord('"'): '&quot;',
134 ord("'"): '&#39;',
131 135 }
132 136
133 137
134 138 def html_escape(text, html_escape_table=default_html_escape_table):
135 139 """Produce entities within text."""
136 140 return text.translate(html_escape_table)
137 141
138 142
139 143 def str_json(*args, **kwargs):
140 144 return ext_json.str_json(*args, **kwargs)
141 145
142 146
143 147 def formatted_str_json(*args, **kwargs):
144 148 return ext_json.formatted_str_json(*args, **kwargs)
145 149
146 150
147 151 def chop_at_smart(s, sub, inclusive=False, suffix_if_chopped=None):
148 152 """
149 153 Truncate string ``s`` at the first occurrence of ``sub``.
150 154
151 155 If ``inclusive`` is true, truncate just after ``sub`` rather than at it.
152 156 """
153 157 suffix_if_chopped = suffix_if_chopped or ''
154 158 pos = s.find(sub)
155 159 if pos == -1:
156 160 return s
157 161
158 162 if inclusive:
159 163 pos += len(sub)
160 164
161 165 chopped = s[:pos]
162 166 left = s[pos:].strip()
163 167
164 168 if left and suffix_if_chopped:
165 169 chopped += suffix_if_chopped
166 170
167 171 return chopped
168 172
169 173
170 174 def shorter(text, size=20, prefix=False):
171 175 postfix = '...'
172 176 if len(text) > size:
173 177 if prefix:
174 178 # shorten in front
175 179 return postfix + text[-(size - len(postfix)):]
176 180 else:
177 181 return text[:size - len(postfix)] + postfix
178 182 return text
179 183
180 184
181 185 def reset(name, value=None, id=NotGiven, type="reset", **attrs):
182 186 """
183 187 Reset button
184 188 """
185 189 return _input(type, name, value, id, attrs)
186 190
187 191
188 192 def select(name, selected_values, options, id=NotGiven, **attrs):
189 193
190 194 if isinstance(options, (list, tuple)):
191 195 options_iter = options
192 196 # Handle old value,label lists ... where value also can be value,label lists
193 197 options = Options()
194 198 for opt in options_iter:
195 199 if isinstance(opt, tuple) and len(opt) == 2:
196 200 value, label = opt
197 201 elif isinstance(opt, str):
198 202 value = label = opt
199 203 else:
200 204 raise ValueError('invalid select option type %r' % type(opt))
201 205
202 206 if isinstance(value, (list, tuple)):
203 207 option_group = options.add_optgroup(label)
204 208 for opt2 in value:
205 209 if isinstance(opt2, tuple) and len(opt2) == 2:
206 210 group_value, group_label = opt2
207 211 elif isinstance(opt2, str):
208 212 group_value = group_label = opt2
209 213 else:
210 214 raise ValueError('invalid select option type %r' % type(opt2))
211 215
212 216 option_group.add_option(group_label, group_value)
213 217 else:
214 218 options.add_option(label, value)
215 219
216 220 return raw_select(name, selected_values, options, id=id, **attrs)
217 221
218 222
219 223 def branding(name, length=40):
220 224 return truncate(name, length, indicator="")
221 225
222 226
223 227 def FID(raw_id, path):
224 228 """
225 229 Creates a unique ID for filenode based on it's hash of path and commit
226 230 it's safe to use in urls
227 231
228 232 :param raw_id:
229 233 :param path:
230 234 """
231 235
232 236 return 'c-%s-%s' % (short_id(raw_id), md5_safe(path)[:12])
233 237
234 238
235 239 class _GetError(object):
236 240 """Get error from form_errors, and represent it as span wrapped error
237 241 message
238 242
239 243 :param field_name: field to fetch errors for
240 244 :param form_errors: form errors dict
241 245 """
242 246
243 247 def __call__(self, field_name, form_errors):
244 248 tmpl = """<span class="error_msg">%s</span>"""
245 249 if form_errors and field_name in form_errors:
246 250 return literal(tmpl % form_errors.get(field_name))
247 251
248 252
249 253 get_error = _GetError()
250 254
251 255
252 256 class _ToolTip(object):
253 257
254 258 def __call__(self, tooltip_title, trim_at=50):
255 259 """
256 260 Special function just to wrap our text into nice formatted
257 261 autowrapped text
258 262
259 263 :param tooltip_title:
260 264 """
261 265 tooltip_title = escape(tooltip_title)
262 266 tooltip_title = tooltip_title.replace('<', '&lt;').replace('>', '&gt;')
263 267 return tooltip_title
264 268
265 269
266 270 tooltip = _ToolTip()
267 271
268 files_icon = u'<i class="file-breadcrumb-copy tooltip icon-clipboard clipboard-action" data-clipboard-text="{}" title="Copy file path"></i>'
272 files_icon = '<i class="file-breadcrumb-copy tooltip icon-clipboard clipboard-action" data-clipboard-text="{}" title="Copy file path"></i>'
269 273
270 274
271 275 def files_breadcrumbs(repo_name, repo_type, commit_id, file_path, landing_ref_name=None, at_ref=None,
272 276 limit_items=False, linkify_last_item=False, hide_last_item=False,
273 277 copy_path_icon=True):
274 if isinstance(file_path, str):
275 file_path = safe_unicode(file_path)
276 278
277 279 if at_ref:
278 280 route_qry = {'at': at_ref}
279 281 default_landing_ref = at_ref or landing_ref_name or commit_id
280 282 else:
281 283 route_qry = None
282 284 default_landing_ref = commit_id
283 285
284 286 # first segment is a `HOME` link to repo files root location
285 root_name = literal(u'<i class="icon-home"></i>')
287 root_name = literal('<i class="icon-home"></i>')
286 288
287 289 url_segments = [
288 290 link_to(
289 291 root_name,
290 292 repo_files_by_ref_url(
291 293 repo_name,
292 294 repo_type,
293 295 f_path=None, # None here is a special case for SVN repos,
294 296 # that won't prefix with a ref
295 297 ref_name=default_landing_ref,
296 298 commit_id=commit_id,
297 299 query=route_qry
298 300 )
299 301 )]
300 302
301 303 path_segments = file_path.split('/')
302 304 last_cnt = len(path_segments) - 1
303 305 for cnt, segment in enumerate(path_segments):
304 306 if not segment:
305 307 continue
306 308 segment_html = escape(segment)
307 309
308 310 last_item = cnt == last_cnt
309 311
310 312 if last_item and hide_last_item:
311 313 # iterate over and hide last element
312 314 continue
313 315
314 316 if last_item and linkify_last_item is False:
315 317 # plain version
316 318 url_segments.append(segment_html)
317 319 else:
318 320 url_segments.append(
319 321 link_to(
320 322 segment_html,
321 323 repo_files_by_ref_url(
322 324 repo_name,
323 325 repo_type,
324 326 f_path='/'.join(path_segments[:cnt + 1]),
325 327 ref_name=default_landing_ref,
326 328 commit_id=commit_id,
327 329 query=route_qry
328 330 ),
329 331 ))
330 332
331 333 limited_url_segments = url_segments[:1] + ['...'] + url_segments[-5:]
332 334 if limit_items and len(limited_url_segments) < len(url_segments):
333 335 url_segments = limited_url_segments
334 336
335 337 full_path = file_path
336 338 if copy_path_icon:
337 339 icon = files_icon.format(escape(full_path))
338 340 else:
339 341 icon = ''
340 342
341 343 if file_path == '':
342 344 return root_name
343 345 else:
344 346 return literal(' / '.join(url_segments) + icon)
345 347
346 348
347 349 def files_url_data(request):
348 import urllib.request, urllib.parse, urllib.error
349 350 matchdict = request.matchdict
350 351
351 352 if 'f_path' not in matchdict:
352 353 matchdict['f_path'] = ''
353 354 else:
354 355 matchdict['f_path'] = urllib.parse.quote(safe_str(matchdict['f_path']))
355 356 if 'commit_id' not in matchdict:
356 357 matchdict['commit_id'] = 'tip'
357 358
358 359 return ext_json.str_json(matchdict)
359 360
360 361
361 362 def repo_files_by_ref_url(db_repo_name, db_repo_type, f_path, ref_name, commit_id, query=None, ):
362 363 _is_svn = is_svn(db_repo_type)
363 364 final_f_path = f_path
364 365
365 366 if _is_svn:
366 367 """
367 368 For SVN the ref_name cannot be used as a commit_id, it needs to be prefixed with
368 369 actually commit_id followed by the ref_name. This should be done only in case
369 370 This is a initial landing url, without additional paths.
370 371
371 372 like: /1000/tags/1.0.0/?at=tags/1.0.0
372 373 """
373 374
374 375 if ref_name and ref_name != 'tip':
375 376 # NOTE(marcink): for svn the ref_name is actually the stored path, so we prefix it
376 377 # for SVN we only do this magic prefix if it's root, .eg landing revision
377 378 # of files link. If we are in the tree we don't need this since we traverse the url
378 379 # that has everything stored
379 380 if f_path in ['', '/']:
380 381 final_f_path = '/'.join([ref_name, f_path])
381 382
382 383 # SVN always needs a commit_id explicitly, without a named REF
383 384 default_commit_id = commit_id
384 385 else:
385 386 """
386 387 For git and mercurial we construct a new URL using the names instead of commit_id
387 388 like: /master/some_path?at=master
388 389 """
389 390 # We currently do not support branches with slashes
390 391 if '/' in ref_name:
391 392 default_commit_id = commit_id
392 393 else:
393 394 default_commit_id = ref_name
394 395
395 396 # sometimes we pass f_path as None, to indicate explicit no prefix,
396 397 # we translate it to string to not have None
397 398 final_f_path = final_f_path or ''
398 399
399 400 files_url = route_path(
400 401 'repo_files',
401 402 repo_name=db_repo_name,
402 403 commit_id=default_commit_id,
403 404 f_path=final_f_path,
404 405 _query=query
405 406 )
406 407 return files_url
407 408
408 409
409 410 def code_highlight(code, lexer, formatter, use_hl_filter=False):
410 411 """
411 412 Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``.
412 413
413 414 If ``outfile`` is given and a valid file object (an object
414 415 with a ``write`` method), the result will be written to it, otherwise
415 416 it is returned as a string.
416 417 """
417 418 if use_hl_filter:
418 419 # add HL filter
419 420 from rhodecode.lib.index import search_utils
420 421 lexer.add_filter(search_utils.ElasticSearchHLFilter())
421 422 return pygments.format(pygments.lex(code, lexer), formatter)
422 423
423 424
424 425 class CodeHtmlFormatter(HtmlFormatter):
425 426 """
426 427 My code Html Formatter for source codes
427 428 """
428 429
429 def wrap(self, source, outfile):
430 def wrap(self, source):
430 431 return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
431 432
432 433 def _wrap_code(self, source):
433 434 for cnt, it in enumerate(source):
434 435 i, t = it
435 t = '<div id="L%s">%s</div>' % (cnt + 1, t)
436 t = f'<div id="L{cnt+1}">{t}</div>'
436 437 yield i, t
437 438
438 439 def _wrap_tablelinenos(self, inner):
439 dummyoutfile = StringIO.StringIO()
440 dummyoutfile = io.StringIO()
440 441 lncount = 0
441 442 for t, line in inner:
442 443 if t:
443 444 lncount += 1
444 445 dummyoutfile.write(line)
445 446
446 447 fl = self.linenostart
447 448 mw = len(str(lncount + fl - 1))
448 449 sp = self.linenospecial
449 450 st = self.linenostep
450 451 la = self.lineanchors
451 452 aln = self.anchorlinenos
452 453 nocls = self.noclasses
453 454 if sp:
454 455 lines = []
455 456
456 457 for i in range(fl, fl + lncount):
457 458 if i % st == 0:
458 459 if i % sp == 0:
459 460 if aln:
460 461 lines.append('<a href="#%s%d" class="special">%*d</a>' %
461 462 (la, i, mw, i))
462 463 else:
463 464 lines.append('<span class="special">%*d</span>' % (mw, i))
464 465 else:
465 466 if aln:
466 467 lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i))
467 468 else:
468 469 lines.append('%*d' % (mw, i))
469 470 else:
470 471 lines.append('')
471 472 ls = '\n'.join(lines)
472 473 else:
473 474 lines = []
474 475 for i in range(fl, fl + lncount):
475 476 if i % st == 0:
476 477 if aln:
477 478 lines.append('<a href="#%s%d">%*d</a>' % (la, i, mw, i))
478 479 else:
479 480 lines.append('%*d' % (mw, i))
480 481 else:
481 482 lines.append('')
482 483 ls = '\n'.join(lines)
483 484
484 485 # in case you wonder about the seemingly redundant <div> here: since the
485 486 # content in the other cell also is wrapped in a div, some browsers in
486 487 # some configurations seem to mess up the formatting...
487 488 if nocls:
488 489 yield 0, ('<table class="%stable">' % self.cssclass +
489 490 '<tr><td><div class="linenodiv" '
490 491 'style="background-color: #f0f0f0; padding-right: 10px">'
491 492 '<pre style="line-height: 125%">' +
492 493 ls + '</pre></div></td><td id="hlcode" class="code">')
493 494 else:
494 495 yield 0, ('<table class="%stable">' % self.cssclass +
495 496 '<tr><td class="linenos"><div class="linenodiv"><pre>' +
496 497 ls + '</pre></div></td><td id="hlcode" class="code">')
497 498 yield 0, dummyoutfile.getvalue()
498 499 yield 0, '</td></tr></table>'
499 500
500 501
501 502 class SearchContentCodeHtmlFormatter(CodeHtmlFormatter):
502 503 def __init__(self, **kw):
503 504 # only show these line numbers if set
504 505 self.only_lines = kw.pop('only_line_numbers', [])
505 506 self.query_terms = kw.pop('query_terms', [])
506 507 self.max_lines = kw.pop('max_lines', 5)
507 508 self.line_context = kw.pop('line_context', 3)
508 509 self.url = kw.pop('url', None)
509 510
510 511 super(CodeHtmlFormatter, self).__init__(**kw)
511 512
512 513 def _wrap_code(self, source):
513 514 for cnt, it in enumerate(source):
514 515 i, t = it
515 516 t = '<pre>%s</pre>' % t
516 517 yield i, t
517 518
518 519 def _wrap_tablelinenos(self, inner):
519 520 yield 0, '<table class="code-highlight %stable">' % self.cssclass
520 521
521 522 last_shown_line_number = 0
522 523 current_line_number = 1
523 524
524 525 for t, line in inner:
525 526 if not t:
526 527 yield t, line
527 528 continue
528 529
529 530 if current_line_number in self.only_lines:
530 531 if last_shown_line_number + 1 != current_line_number:
531 532 yield 0, '<tr>'
532 533 yield 0, '<td class="line">...</td>'
533 534 yield 0, '<td id="hlcode" class="code"></td>'
534 535 yield 0, '</tr>'
535 536
536 537 yield 0, '<tr>'
537 538 if self.url:
538 539 yield 0, '<td class="line"><a href="%s#L%i">%i</a></td>' % (
539 540 self.url, current_line_number, current_line_number)
540 541 else:
541 542 yield 0, '<td class="line"><a href="">%i</a></td>' % (
542 543 current_line_number)
543 544 yield 0, '<td id="hlcode" class="code">' + line + '</td>'
544 545 yield 0, '</tr>'
545 546
546 547 last_shown_line_number = current_line_number
547 548
548 549 current_line_number += 1
549 550
550 551 yield 0, '</table>'
551 552
552 553
553 554 def hsv_to_rgb(h, s, v):
554 555 """ Convert hsv color values to rgb """
555 556
556 557 if s == 0.0:
557 558 return v, v, v
558 559 i = int(h * 6.0) # XXX assume int() truncates!
559 560 f = (h * 6.0) - i
560 561 p = v * (1.0 - s)
561 562 q = v * (1.0 - s * f)
562 563 t = v * (1.0 - s * (1.0 - f))
563 564 i = i % 6
564 565 if i == 0:
565 566 return v, t, p
566 567 if i == 1:
567 568 return q, v, p
568 569 if i == 2:
569 570 return p, v, t
570 571 if i == 3:
571 572 return p, q, v
572 573 if i == 4:
573 574 return t, p, v
574 575 if i == 5:
575 576 return v, p, q
576 577
577 578
578 579 def unique_color_generator(n=10000, saturation=0.10, lightness=0.95):
579 580 """
580 581 Generator for getting n of evenly distributed colors using
581 582 hsv color and golden ratio. It always return same order of colors
582 583
583 584 :param n: number of colors to generate
584 585 :param saturation: saturation of returned colors
585 586 :param lightness: lightness of returned colors
586 587 :returns: RGB tuple
587 588 """
588 589
589 590 golden_ratio = 0.618033988749895
590 591 h = 0.22717784590367374
591 592
592 593 for _ in range(n):
593 594 h += golden_ratio
594 595 h %= 1
595 596 HSV_tuple = [h, saturation, lightness]
596 597 RGB_tuple = hsv_to_rgb(*HSV_tuple)
597 yield map(lambda x: str(int(x * 256)), RGB_tuple)
598 yield [str(int(x * 256)) for x in RGB_tuple]
598 599
599 600
600 601 def color_hasher(n=10000, saturation=0.10, lightness=0.95):
601 602 """
602 603 Returns a function which when called with an argument returns a unique
603 604 color for that argument, eg.
604 605
605 606 :param n: number of colors to generate
606 607 :param saturation: saturation of returned colors
607 608 :param lightness: lightness of returned colors
608 609 :returns: css RGB string
609 610
610 611 >>> color_hash = color_hasher()
611 612 >>> color_hash('hello')
612 613 'rgb(34, 12, 59)'
613 614 >>> color_hash('hello')
614 615 'rgb(34, 12, 59)'
615 616 >>> color_hash('other')
616 617 'rgb(90, 224, 159)'
617 618 """
618 619
619 620 color_dict = {}
620 621 cgenerator = unique_color_generator(
621 622 saturation=saturation, lightness=lightness)
622 623
623 624 def get_color_string(thing):
624 625 if thing in color_dict:
625 626 col = color_dict[thing]
626 627 else:
627 628 col = color_dict[thing] = next(cgenerator)
628 629 return "rgb(%s)" % (', '.join(col))
629 630
630 631 return get_color_string
631 632
632 633
633 634 def get_lexer_safe(mimetype=None, filepath=None):
634 635 """
635 636 Tries to return a relevant pygments lexer using mimetype/filepath name,
636 637 defaulting to plain text if none could be found
637 638 """
638 639 lexer = None
639 640 try:
640 641 if mimetype:
641 642 lexer = get_lexer_for_mimetype(mimetype)
642 643 if not lexer:
643 644 lexer = get_lexer_for_filename(filepath)
644 645 except pygments.util.ClassNotFound:
645 646 pass
646 647
647 648 if not lexer:
648 649 lexer = get_lexer_by_name('text')
649 650
650 651 return lexer
651 652
652 653
653 654 def get_lexer_for_filenode(filenode):
654 655 lexer = get_custom_lexer(filenode.extension) or filenode.lexer
655 656 return lexer
656 657
657 658
658 659 def pygmentize(filenode, **kwargs):
659 660 """
660 661 pygmentize function using pygments
661 662
662 663 :param filenode:
663 664 """
664 665 lexer = get_lexer_for_filenode(filenode)
665 666 return literal(code_highlight(filenode.content, lexer,
666 667 CodeHtmlFormatter(**kwargs)))
667 668
668 669
669 670 def is_following_repo(repo_name, user_id):
670 671 from rhodecode.model.scm import ScmModel
671 672 return ScmModel().is_following_repo(repo_name, user_id)
672 673
673 674
674 675 class _Message(object):
675 676 """A message returned by ``Flash.pop_messages()``.
676 677
677 678 Converting the message to a string returns the message text. Instances
678 679 also have the following attributes:
679 680
680 681 * ``message``: the message text.
681 682 * ``category``: the category specified when the message was created.
682 683 """
683 684
684 685 def __init__(self, category, message, sub_data=None):
685 686 self.category = category
686 687 self.message = message
687 688 self.sub_data = sub_data or {}
688 689
689 690 def __str__(self):
690 691 return self.message
691 692
692 693 __unicode__ = __str__
693 694
694 695 def __html__(self):
695 return escape(safe_unicode(self.message))
696 return escape(safe_str(self.message))
696 697
697 698
698 699 class Flash(object):
699 700 # List of allowed categories. If None, allow any category.
700 701 categories = ["warning", "notice", "error", "success"]
701 702
702 703 # Default category if none is specified.
703 704 default_category = "notice"
704 705
705 706 def __init__(self, session_key="flash", categories=None,
706 707 default_category=None):
707 708 """
708 709 Instantiate a ``Flash`` object.
709 710
710 711 ``session_key`` is the key to save the messages under in the user's
711 712 session.
712 713
713 714 ``categories`` is an optional list which overrides the default list
714 715 of categories.
715 716
716 717 ``default_category`` overrides the default category used for messages
717 718 when none is specified.
718 719 """
719 720 self.session_key = session_key
720 721 if categories is not None:
721 722 self.categories = categories
722 723 if default_category is not None:
723 724 self.default_category = default_category
724 725 if self.categories and self.default_category not in self.categories:
725 726 raise ValueError(
726 727 "unrecognized default category %r" % (self.default_category,))
727 728
728 729 def pop_messages(self, session=None, request=None):
729 730 """
730 731 Return all accumulated messages and delete them from the session.
731 732
732 733 The return value is a list of ``Message`` objects.
733 734 """
734 735 messages = []
735 736
736 737 if not session:
737 738 if not request:
738 739 request = get_current_request()
739 740 session = request.session
740 741
741 742 # Pop the 'old' pylons flash messages. They are tuples of the form
742 743 # (category, message)
743 744 for cat, msg in session.pop(self.session_key, []):
744 745 messages.append(_Message(cat, msg))
745 746
746 747 # Pop the 'new' pyramid flash messages for each category as list
747 748 # of strings.
748 749 for cat in self.categories:
749 750 for msg in session.pop_flash(queue=cat):
750 751 sub_data = {}
751 752 if hasattr(msg, 'rsplit'):
752 753 flash_data = msg.rsplit('|DELIM|', 1)
753 754 org_message = flash_data[0]
754 755 if len(flash_data) > 1:
755 756 sub_data = json.loads(flash_data[1])
756 757 else:
757 758 org_message = msg
758 759
759 760 messages.append(_Message(cat, org_message, sub_data=sub_data))
760 761
761 762 # Map messages from the default queue to the 'notice' category.
762 763 for msg in session.pop_flash():
763 764 messages.append(_Message('notice', msg))
764 765
765 766 session.save()
766 767 return messages
767 768
768 769 def json_alerts(self, session=None, request=None):
769 770 payloads = []
770 771 messages = flash.pop_messages(session=session, request=request) or []
771 772 for message in messages:
772 773 payloads.append({
773 774 'message': {
774 'message': u'{}'.format(message.message),
775 'message': '{}'.format(message.message),
775 776 'level': message.category,
776 777 'force': True,
777 778 'subdata': message.sub_data
778 779 }
779 780 })
780 781 return safe_str(json.dumps(payloads))
781 782
782 783 def __call__(self, message, category=None, ignore_duplicate=True,
783 784 session=None, request=None):
784 785
785 786 if not session:
786 787 if not request:
787 788 request = get_current_request()
788 789 session = request.session
789 790
790 791 session.flash(
791 792 message, queue=category, allow_duplicate=not ignore_duplicate)
792 793
793 794
794 795 flash = Flash()
795 796
796 797 #==============================================================================
797 798 # SCM FILTERS available via h.
798 799 #==============================================================================
799 800 from rhodecode.lib.vcs.utils import author_name, author_email
800 801 from rhodecode.lib.utils2 import age, age_from_seconds
801 802 from rhodecode.model.db import User, ChangesetStatus
802 803
803 804
804 805 email = author_email
805 806
806 807
807 808 def capitalize(raw_text):
808 809 return raw_text.capitalize()
809 810
810 811
811 812 def short_id(long_id):
812 813 return long_id[:12]
813 814
814 815
815 816 def hide_credentials(url):
816 817 from rhodecode.lib.utils2 import credentials_filter
817 818 return credentials_filter(url)
818 819
819
820 import pytz
820 import zoneinfo
821 821 import tzlocal
822 822 local_timezone = tzlocal.get_localzone()
823 823
824 824
825 825 def get_timezone(datetime_iso, time_is_local=False):
826 826 tzinfo = '+00:00'
827 827
828 828 # detect if we have a timezone info, otherwise, add it
829 829 if time_is_local and isinstance(datetime_iso, datetime) and not datetime_iso.tzinfo:
830 830 force_timezone = os.environ.get('RC_TIMEZONE', '')
831 831 if force_timezone:
832 force_timezone = pytz.timezone(force_timezone)
832 force_timezone = zoneinfo.ZoneInfo(force_timezone)
833 833 timezone = force_timezone or local_timezone
834 offset = timezone.localize(datetime_iso).strftime('%z')
834
835 offset = datetime_iso.replace(tzinfo=timezone).strftime('%z')
835 836 tzinfo = '{}:{}'.format(offset[:-2], offset[-2:])
836 837 return tzinfo
837 838
838 839
839 840 def age_component(datetime_iso, value=None, time_is_local=False, tooltip=True):
840 841 title = value or format_date(datetime_iso)
841 842 tzinfo = get_timezone(datetime_iso, time_is_local=time_is_local)
842 843
843 844 return literal(
844 845 '<time class="timeago {cls}" title="{tt_title}" datetime="{dt}{tzinfo}">{title}</time>'.format(
845 846 cls='tooltip' if tooltip else '',
846 847 tt_title=('{title}{tzinfo}'.format(title=title, tzinfo=tzinfo)) if tooltip else '',
847 848 title=title, dt=datetime_iso, tzinfo=tzinfo
848 849 ))
849 850
850 851
851 852 def _shorten_commit_id(commit_id, commit_len=None):
852 853 if commit_len is None:
853 854 request = get_current_request()
854 855 commit_len = request.call_context.visual.show_sha_length
855 856 return commit_id[:commit_len]
856 857
857 858
858 859 def show_id(commit, show_idx=None, commit_len=None):
859 860 """
860 861 Configurable function that shows ID
861 862 by default it's r123:fffeeefffeee
862 863
863 864 :param commit: commit instance
864 865 """
865 866 if show_idx is None:
866 867 request = get_current_request()
867 868 show_idx = request.call_context.visual.show_revision_number
868 869
869 870 raw_id = _shorten_commit_id(commit.raw_id, commit_len=commit_len)
870 871 if show_idx:
871 872 return 'r%s:%s' % (commit.idx, raw_id)
872 873 else:
873 874 return '%s' % (raw_id, )
874 875
875 876
876 877 def format_date(date):
877 878 """
878 879 use a standardized formatting for dates used in RhodeCode
879 880
880 881 :param date: date/datetime object
881 882 :return: formatted date
882 883 """
883 884
884 885 if date:
885 886 _fmt = "%a, %d %b %Y %H:%M:%S"
886 return safe_unicode(date.strftime(_fmt))
887
888 return u""
887 return safe_str(date.strftime(_fmt))
888
889 return ""
889 890
890 891
891 892 class _RepoChecker(object):
892 893
893 894 def __init__(self, backend_alias):
894 895 self._backend_alias = backend_alias
895 896
896 897 def __call__(self, repository):
897 898 if hasattr(repository, 'alias'):
898 899 _type = repository.alias
899 900 elif hasattr(repository, 'repo_type'):
900 901 _type = repository.repo_type
901 902 else:
902 903 _type = repository
903 904 return _type == self._backend_alias
904 905
905 906
906 907 is_git = _RepoChecker('git')
907 908 is_hg = _RepoChecker('hg')
908 909 is_svn = _RepoChecker('svn')
909 910
910 911
911 912 def get_repo_type_by_name(repo_name):
912 913 repo = Repository.get_by_repo_name(repo_name)
913 914 if repo:
914 915 return repo.repo_type
915 916
916 917
917 918 def is_svn_without_proxy(repository):
918 919 if is_svn(repository):
919 920 from rhodecode.model.settings import VcsSettingsModel
920 921 conf = VcsSettingsModel().get_ui_settings_as_config_obj()
921 922 return not str2bool(conf.get('vcs_svn_proxy', 'http_requests_enabled'))
922 923 return False
923 924
924 925
925 926 def discover_user(author):
926 927 """
927 928 Tries to discover RhodeCode User based on the author string. Author string
928 929 is typically `FirstName LastName <email@address.com>`
929 930 """
930 931
931 932 # if author is already an instance use it for extraction
932 933 if isinstance(author, User):
933 934 return author
934 935
935 936 # Valid email in the attribute passed, see if they're in the system
936 937 _email = author_email(author)
937 938 if _email != '':
938 939 user = User.get_by_email(_email, case_insensitive=True, cache=True)
939 940 if user is not None:
940 941 return user
941 942
942 943 # Maybe it's a username, we try to extract it and fetch by username ?
943 944 _author = author_name(author)
944 945 user = User.get_by_username(_author, case_insensitive=True, cache=True)
945 946 if user is not None:
946 947 return user
947 948
948 949 return None
949 950
950 951
951 952 def email_or_none(author):
952 953 # extract email from the commit string
953 954 _email = author_email(author)
954 955
955 956 # If we have an email, use it, otherwise
956 957 # see if it contains a username we can get an email from
957 958 if _email != '':
958 959 return _email
959 960 else:
960 961 user = User.get_by_username(
961 962 author_name(author), case_insensitive=True, cache=True)
962 963
963 964 if user is not None:
964 965 return user.email
965 966
966 967 # No valid email, not a valid user in the system, none!
967 968 return None
968 969
969 970
970 971 def link_to_user(author, length=0, **kwargs):
971 972 user = discover_user(author)
972 973 # user can be None, but if we have it already it means we can re-use it
973 974 # in the person() function, so we save 1 intensive-query
974 975 if user:
975 976 author = user
976 977
977 978 display_person = person(author, 'username_or_name_or_email')
978 979 if length:
979 980 display_person = shorter(display_person, length)
980 981
981 982 if user and user.username != user.DEFAULT_USER:
982 983 return link_to(
983 984 escape(display_person),
984 985 route_path('user_profile', username=user.username),
985 986 **kwargs)
986 987 else:
987 988 return escape(display_person)
988 989
989 990
990 991 def link_to_group(users_group_name, **kwargs):
991 992 return link_to(
992 993 escape(users_group_name),
993 994 route_path('user_group_profile', user_group_name=users_group_name),
994 995 **kwargs)
995 996
996 997
997 998 def person(author, show_attr="username_and_name"):
998 999 user = discover_user(author)
999 1000 if user:
1000 1001 return getattr(user, show_attr)
1001 1002 else:
1002 1003 _author = author_name(author)
1003 1004 _email = email(author)
1004 1005 return _author or _email
1005 1006
1006 1007
1007 1008 def author_string(email):
1008 1009 if email:
1009 1010 user = User.get_by_email(email, case_insensitive=True, cache=True)
1010 1011 if user:
1011 1012 if user.first_name or user.last_name:
1012 1013 return '%s %s &lt;%s&gt;' % (
1013 1014 user.first_name, user.last_name, email)
1014 1015 else:
1015 1016 return email
1016 1017 else:
1017 1018 return email
1018 1019 else:
1019 1020 return None
1020 1021
1021 1022
1022 1023 def person_by_id(id_, show_attr="username_and_name"):
1023 1024 # attr to return from fetched user
1024 person_getter = lambda usr: getattr(usr, show_attr)
1025 def person_getter(usr):
1026 return getattr(usr, show_attr)
1025 1027
1026 1028 #maybe it's an ID ?
1027 1029 if str(id_).isdigit() or isinstance(id_, int):
1028 1030 id_ = int(id_)
1029 1031 user = User.get(id_)
1030 1032 if user is not None:
1031 1033 return person_getter(user)
1032 1034 return id_
1033 1035
1034 1036
1035 1037 def gravatar_with_user(request, author, show_disabled=False, tooltip=False):
1036 1038 _render = request.get_partial_renderer('rhodecode:templates/base/base.mako')
1037 1039 return _render('gravatar_with_user', author, show_disabled=show_disabled, tooltip=tooltip)
1038 1040
1039 1041
1040 1042 tags_paterns = OrderedDict((
1041 1043 ('lang', (re.compile(r'\[(lang|language)\ \=\&gt;\ *([a-zA-Z\-\/\#\+\.]*)\]'),
1042 1044 '<div class="metatag" tag="lang">\\2</div>')),
1043 1045
1044 1046 ('see', (re.compile(r'\[see\ \=\&gt;\ *([a-zA-Z0-9\/\=\?\&amp;\ \:\/\.\-]*)\]'),
1045 1047 '<div class="metatag" tag="see">see: \\1 </div>')),
1046 1048
1047 1049 ('url', (re.compile(r'\[url\ \=\&gt;\ \[([a-zA-Z0-9\ \.\-\_]+)\]\((http://|https://|/)(.*?)\)\]'),
1048 1050 '<div class="metatag" tag="url"> <a href="\\2\\3">\\1</a> </div>')),
1049 1051
1050 1052 ('license', (re.compile(r'\[license\ \=\&gt;\ *([a-zA-Z0-9\/\=\?\&amp;\ \:\/\.\-]*)\]'),
1051 1053 '<div class="metatag" tag="license"><a href="http:\/\/www.opensource.org/licenses/\\1">\\1</a></div>')),
1052 1054
1053 1055 ('ref', (re.compile(r'\[(requires|recommends|conflicts|base)\ \=\&gt;\ *([a-zA-Z0-9\-\/]*)\]'),
1054 1056 '<div class="metatag" tag="ref \\1">\\1: <a href="/\\2">\\2</a></div>')),
1055 1057
1056 1058 ('state', (re.compile(r'\[(stable|featured|stale|dead|dev|deprecated)\]'),
1057 1059 '<div class="metatag" tag="state \\1">\\1</div>')),
1058 1060
1059 1061 # label in grey
1060 1062 ('label', (re.compile(r'\[([a-z]+)\]'),
1061 1063 '<div class="metatag" tag="label">\\1</div>')),
1062 1064
1063 1065 # generic catch all in grey
1064 1066 ('generic', (re.compile(r'\[([a-zA-Z0-9\.\-\_]+)\]'),
1065 1067 '<div class="metatag" tag="generic">\\1</div>')),
1066 1068 ))
1067 1069
1068 1070
1069 1071 def extract_metatags(value):
1070 1072 """
1071 1073 Extract supported meta-tags from given text value
1072 1074 """
1073 1075 tags = []
1074 1076 if not value:
1075 1077 return tags, ''
1076 1078
1077 for key, val in tags_paterns.items():
1079 for key, val in list(tags_paterns.items()):
1078 1080 pat, replace_html = val
1079 1081 tags.extend([(key, x.group()) for x in pat.finditer(value)])
1080 1082 value = pat.sub('', value)
1081 1083
1082 1084 return tags, value
1083 1085
1084 1086
1085 1087 def style_metatag(tag_type, value):
1086 1088 """
1087 1089 converts tags from value into html equivalent
1088 1090 """
1089 1091 if not value:
1090 1092 return ''
1091 1093
1092 1094 html_value = value
1093 1095 tag_data = tags_paterns.get(tag_type)
1094 1096 if tag_data:
1095 1097 pat, replace_html = tag_data
1096 # convert to plain `unicode` instead of a markup tag to be used in
1097 # regex expressions. safe_unicode doesn't work here
1098 # convert to plain `str` instead of a markup tag to be used in
1099 # regex expressions. safe_str doesn't work here
1098 1100 html_value = pat.sub(replace_html, value)
1099 1101
1100 1102 return html_value
1101 1103
1102 1104
1103 1105 def bool2icon(value, show_at_false=True):
1104 1106 """
1105 1107 Returns boolean value of a given value, represented as html element with
1106 1108 classes that will represent icons
1107 1109
1108 1110 :param value: given value to convert to html node
1109 1111 """
1110 1112
1111 1113 if value: # does bool conversion
1112 1114 return HTML.tag('i', class_="icon-true", title='True')
1113 1115 else: # not true as bool
1114 1116 if show_at_false:
1115 1117 return HTML.tag('i', class_="icon-false", title='False')
1116 1118 return HTML.tag('i')
1117 1119
1118 1120
1119 1121 def b64(inp):
1120 return base64.b64encode(inp)
1122 return base64.b64encode(safe_bytes(inp))
1121 1123
1122 1124 #==============================================================================
1123 1125 # PERMS
1124 1126 #==============================================================================
1125 1127 from rhodecode.lib.auth import (
1126 1128 HasPermissionAny, HasPermissionAll,
1127 1129 HasRepoPermissionAny, HasRepoPermissionAll, HasRepoGroupPermissionAll,
1128 1130 HasRepoGroupPermissionAny, HasRepoPermissionAnyApi, get_csrf_token,
1129 1131 csrf_token_key, AuthUser)
1130 1132
1131 1133
1132 1134 #==============================================================================
1133 1135 # GRAVATAR URL
1134 1136 #==============================================================================
1135 1137 class InitialsGravatar(object):
1136 1138 def __init__(self, email_address, first_name, last_name, size=30,
1137 1139 background=None, text_color='#fff'):
1138 1140 self.size = size
1139 1141 self.first_name = first_name
1140 1142 self.last_name = last_name
1141 1143 self.email_address = email_address
1142 1144 self.background = background or self.str2color(email_address)
1143 1145 self.text_color = text_color
1144 1146
1145 1147 def get_color_bank(self):
1146 1148 """
1147 1149 returns a predefined list of colors that gravatars can use.
1148 1150 Those are randomized distinct colors that guarantee readability and
1149 1151 uniqueness.
1150 1152
1151 1153 generated with: http://phrogz.net/css/distinct-colors.html
1152 1154 """
1153 1155 return [
1154 1156 '#bf3030', '#a67f53', '#00ff00', '#5989b3', '#392040', '#d90000',
1155 1157 '#402910', '#204020', '#79baf2', '#a700b3', '#bf6060', '#7f5320',
1156 1158 '#008000', '#003059', '#ee00ff', '#ff0000', '#8c4b00', '#007300',
1157 1159 '#005fb3', '#de73e6', '#ff4040', '#ffaa00', '#3df255', '#203140',
1158 1160 '#47004d', '#591616', '#664400', '#59b365', '#0d2133', '#83008c',
1159 1161 '#592d2d', '#bf9f60', '#73e682', '#1d3f73', '#73006b', '#402020',
1160 1162 '#b2862d', '#397341', '#597db3', '#e600d6', '#a60000', '#736039',
1161 1163 '#00b318', '#79aaf2', '#330d30', '#ff8080', '#403010', '#16591f',
1162 1164 '#002459', '#8c4688', '#e50000', '#ffbf40', '#00732e', '#102340',
1163 1165 '#bf60ac', '#8c4646', '#cc8800', '#00a642', '#1d3473', '#b32d98',
1164 1166 '#660e00', '#ffd580', '#80ffb2', '#7391e6', '#733967', '#d97b6c',
1165 1167 '#8c5e00', '#59b389', '#3967e6', '#590047', '#73281d', '#665200',
1166 1168 '#00e67a', '#2d50b3', '#8c2377', '#734139', '#b2982d', '#16593a',
1167 1169 '#001859', '#ff00aa', '#a65e53', '#ffcc00', '#0d3321', '#2d3959',
1168 1170 '#731d56', '#401610', '#4c3d00', '#468c6c', '#002ca6', '#d936a3',
1169 1171 '#d94c36', '#403920', '#36d9a3', '#0d1733', '#592d4a', '#993626',
1170 1172 '#cca300', '#00734d', '#46598c', '#8c005e', '#7f1100', '#8c7000',
1171 1173 '#00a66f', '#7382e6', '#b32d74', '#d9896c', '#ffe680', '#1d7362',
1172 1174 '#364cd9', '#73003d', '#d93a00', '#998a4d', '#59b3a1', '#5965b3',
1173 1175 '#e5007a', '#73341d', '#665f00', '#00b38f', '#0018b3', '#59163a',
1174 1176 '#b2502d', '#bfb960', '#00ffcc', '#23318c', '#a6537f', '#734939',
1175 1177 '#b2a700', '#104036', '#3d3df2', '#402031', '#e56739', '#736f39',
1176 1178 '#79f2ea', '#000059', '#401029', '#4c1400', '#ffee00', '#005953',
1177 1179 '#101040', '#990052', '#402820', '#403d10', '#00ffee', '#0000d9',
1178 1180 '#ff80c4', '#a66953', '#eeff00', '#00ccbe', '#8080ff', '#e673a1',
1179 1181 '#a62c00', '#474d00', '#1a3331', '#46468c', '#733950', '#662900',
1180 1182 '#858c23', '#238c85', '#0f0073', '#b20047', '#d9986c', '#becc00',
1181 1183 '#396f73', '#281d73', '#ff0066', '#ff6600', '#dee673', '#59adb3',
1182 1184 '#6559b3', '#590024', '#b2622d', '#98b32d', '#36ced9', '#332d59',
1183 1185 '#40001a', '#733f1d', '#526600', '#005359', '#242040', '#bf6079',
1184 1186 '#735039', '#cef23d', '#007780', '#5630bf', '#66001b', '#b24700',
1185 1187 '#acbf60', '#1d6273', '#25008c', '#731d34', '#a67453', '#50592d',
1186 1188 '#00ccff', '#6600ff', '#ff0044', '#4c1f00', '#8a994d', '#79daf2',
1187 1189 '#a173e6', '#d93662', '#402310', '#aaff00', '#2d98b3', '#8c40ff',
1188 1190 '#592d39', '#ff8c40', '#354020', '#103640', '#1a0040', '#331a20',
1189 1191 '#331400', '#334d00', '#1d5673', '#583973', '#7f0022', '#4c3626',
1190 1192 '#88cc00', '#36a3d9', '#3d0073', '#d9364c', '#33241a', '#698c23',
1191 1193 '#5995b3', '#300059', '#e57382', '#7f3300', '#366600', '#00aaff',
1192 1194 '#3a1659', '#733941', '#663600', '#74b32d', '#003c59', '#7f53a6',
1193 1195 '#73000f', '#ff8800', '#baf279', '#79caf2', '#291040', '#a6293a',
1194 1196 '#b2742d', '#587339', '#0077b3', '#632699', '#400009', '#d9a66c',
1195 1197 '#294010', '#2d4a59', '#aa00ff', '#4c131b', '#b25f00', '#5ce600',
1196 1198 '#267399', '#a336d9', '#990014', '#664e33', '#86bf60', '#0088ff',
1197 1199 '#7700b3', '#593a16', '#073300', '#1d4b73', '#ac60bf', '#e59539',
1198 1200 '#4f8c46', '#368dd9', '#5c0073'
1199 1201 ]
1200 1202
1201 1203 def rgb_to_hex_color(self, rgb_tuple):
1202 1204 """
1203 1205 Converts an rgb_tuple passed to an hex color.
1204 1206
1205 1207 :param rgb_tuple: tuple with 3 ints represents rgb color space
1206 1208 """
1207 1209 return '#' + ("".join(map(chr, rgb_tuple)).encode('hex'))
1208 1210
1209 1211 def email_to_int_list(self, email_str):
1210 1212 """
1211 1213 Get every byte of the hex digest value of email and turn it to integer.
1212 1214 It's going to be always between 0-255
1213 1215 """
1214 1216 digest = md5_safe(email_str.lower())
1215 1217 return [int(digest[i * 2:i * 2 + 2], 16) for i in range(16)]
1216 1218
1217 1219 def pick_color_bank_index(self, email_str, color_bank):
1218 1220 return self.email_to_int_list(email_str)[0] % len(color_bank)
1219 1221
1220 1222 def str2color(self, email_str):
1221 1223 """
1222 1224 Tries to map in a stable algorithm an email to color
1223 1225
1224 1226 :param email_str:
1225 1227 """
1226 1228 color_bank = self.get_color_bank()
1227 1229 # pick position (module it's length so we always find it in the
1228 1230 # bank even if it's smaller than 256 values
1229 1231 pos = self.pick_color_bank_index(email_str, color_bank)
1230 1232 return color_bank[pos]
1231 1233
1232 1234 def normalize_email(self, email_address):
1233 import unicodedata
1234 1235 # default host used to fill in the fake/missing email
1235 1236 default_host = 'localhost'
1236 1237
1237 1238 if not email_address:
1238 email_address = '%s@%s' % (User.DEFAULT_USER, default_host)
1239
1240 email_address = safe_unicode(email_address)
1241
1242 if u'@' not in email_address:
1243 email_address = u'%s@%s' % (email_address, default_host)
1244
1245 if email_address.endswith(u'@'):
1246 email_address = u'%s%s' % (email_address, default_host)
1247
1248 email_address = unicodedata.normalize('NFKD', email_address)\
1249 .encode('ascii', 'ignore')
1239 email_address = f'{User.DEFAULT_USER}@{default_host}'
1240
1241 email_address = safe_str(email_address)
1242
1243 if '@' not in email_address:
1244 email_address = f'{email_address}@{default_host}'
1245
1246 if email_address.endswith('@'):
1247 email_address = f'{email_address}{default_host}'
1248
1249 email_address = convert_special_chars(email_address)
1250
1250 1251 return email_address
1251 1252
1252 1253 def get_initials(self):
1253 1254 """
1254 1255 Returns 2 letter initials calculated based on the input.
1255 1256 The algorithm picks first given email address, and takes first letter
1256 1257 of part before @, and then the first letter of server name. In case
1257 1258 the part before @ is in a format of `somestring.somestring2` it replaces
1258 1259 the server letter with first letter of somestring2
1259 1260
1260 1261 In case function was initialized with both first and lastname, this
1261 1262 overrides the extraction from email by first letter of the first and
1262 1263 last name. We add special logic to that functionality, In case Full name
1263 1264 is compound, like Guido Von Rossum, we use last part of the last name
1264 1265 (Von Rossum) picking `R`.
1265 1266
1266 1267 Function also normalizes the non-ascii characters to they ascii
1267 1268 representation, eg Δ„ => A
1268 1269 """
1269 import unicodedata
1270 1270 # replace non-ascii to ascii
1271 first_name = unicodedata.normalize(
1272 'NFKD', safe_unicode(self.first_name)).encode('ascii', 'ignore')
1273 last_name = unicodedata.normalize(
1274 'NFKD', safe_unicode(self.last_name)).encode('ascii', 'ignore')
1271 first_name = convert_special_chars(self.first_name)
1272 last_name = convert_special_chars(self.last_name)
1273 # multi word last names, Guido Von Rossum, we take the last part only
1274 last_name = last_name.split(' ', 1)[-1]
1275 1275
1276 1276 # do NFKD encoding, and also make sure email has proper format
1277 1277 email_address = self.normalize_email(self.email_address)
1278 1278
1279 1279 # first push the email initials
1280 1280 prefix, server = email_address.split('@', 1)
1281 1281
1282 1282 # check if prefix is maybe a 'first_name.last_name' syntax
1283 1283 _dot_split = prefix.rsplit('.', 1)
1284 1284 if len(_dot_split) == 2 and _dot_split[1]:
1285 1285 initials = [_dot_split[0][0], _dot_split[1][0]]
1286 1286 else:
1287 1287 initials = [prefix[0], server[0]]
1288 1288
1289 # then try to replace either first_name or last_name
1289 # get first letter of first and last names to create initials
1290 1290 fn_letter = (first_name or " ")[0].strip()
1291 ln_letter = (last_name.split(' ', 1)[-1] or " ")[0].strip()
1291 ln_letter = (last_name or " ")[0].strip()
1292 1292
1293 1293 if fn_letter:
1294 1294 initials[0] = fn_letter
1295 1295
1296 1296 if ln_letter:
1297 1297 initials[1] = ln_letter
1298 1298
1299 1299 return ''.join(initials).upper()
1300 1300
1301 1301 def get_img_data_by_type(self, font_family, img_type):
1302 1302 default_user = """
1303 1303 <svg xmlns="http://www.w3.org/2000/svg"
1304 1304 version="1.1" x="0px" y="0px" width="{size}" height="{size}"
1305 1305 viewBox="-15 -10 439.165 429.164"
1306 1306
1307 1307 xml:space="preserve"
1308 font-family="{font_family}
1308 1309 style="background:{background};" >
1309 1310
1310 1311 <path d="M204.583,216.671c50.664,0,91.74-48.075,
1311 1312 91.74-107.378c0-82.237-41.074-107.377-91.74-107.377
1312 1313 c-50.668,0-91.74,25.14-91.74,107.377C112.844,
1313 1314 168.596,153.916,216.671,
1314 1315 204.583,216.671z" fill="{text_color}"/>
1315 1316 <path d="M407.164,374.717L360.88,
1316 1317 270.454c-2.117-4.771-5.836-8.728-10.465-11.138l-71.83-37.392
1317 1318 c-1.584-0.823-3.502-0.663-4.926,0.415c-20.316,
1318 1319 15.366-44.203,23.488-69.076,23.488c-24.877,
1319 1320 0-48.762-8.122-69.078-23.488
1320 1321 c-1.428-1.078-3.346-1.238-4.93-0.415L58.75,
1321 1322 259.316c-4.631,2.41-8.346,6.365-10.465,11.138L2.001,374.717
1322 1323 c-3.191,7.188-2.537,15.412,1.75,22.005c4.285,
1323 1324 6.592,11.537,10.526,19.4,10.526h362.861c7.863,0,15.117-3.936,
1324 1325 19.402-10.527 C409.699,390.129,
1325 1326 410.355,381.902,407.164,374.717z" fill="{text_color}"/>
1326 1327 </svg>""".format(
1327 1328 size=self.size,
1328 1329 background='#979797', # @grey4
1329 1330 text_color=self.text_color,
1330 1331 font_family=font_family)
1331 1332
1332 1333 return {
1333 1334 "default_user": default_user
1334 1335 }[img_type]
1335 1336
1336 1337 def get_img_data(self, svg_type=None):
1337 1338 """
1338 1339 generates the svg metadata for image
1339 1340 """
1340 1341 fonts = [
1341 1342 '-apple-system',
1342 1343 'BlinkMacSystemFont',
1343 1344 'Segoe UI',
1344 1345 'Roboto',
1345 1346 'Oxygen-Sans',
1346 1347 'Ubuntu',
1347 1348 'Cantarell',
1348 1349 'Helvetica Neue',
1349 1350 'sans-serif'
1350 1351 ]
1351 1352 font_family = ','.join(fonts)
1352 1353 if svg_type:
1353 1354 return self.get_img_data_by_type(font_family, svg_type)
1354 1355
1355 1356 initials = self.get_initials()
1356 1357 img_data = """
1357 1358 <svg xmlns="http://www.w3.org/2000/svg" pointer-events="none"
1358 1359 width="{size}" height="{size}"
1359 1360 style="width: 100%; height: 100%; background-color: {background}"
1360 1361 viewBox="0 0 {size} {size}">
1361 1362 <text text-anchor="middle" y="50%" x="50%" dy="0.35em"
1362 1363 pointer-events="auto" fill="{text_color}"
1363 1364 font-family="{font_family}"
1364 1365 style="font-weight: 400; font-size: {f_size}px;">{text}
1365 1366 </text>
1366 1367 </svg>""".format(
1367 1368 size=self.size,
1368 1369 f_size=self.size/2.05, # scale the text inside the box nicely
1369 1370 background=self.background,
1370 1371 text_color=self.text_color,
1371 1372 text=initials.upper(),
1372 1373 font_family=font_family)
1373 1374
1374 1375 return img_data
1375 1376
1376 1377 def generate_svg(self, svg_type=None):
1377 img_data = self.get_img_data(svg_type)
1378 return "data:image/svg+xml;base64,%s" % base64.b64encode(img_data)
1378 img_data = safe_bytes(self.get_img_data(svg_type))
1379 return "data:image/svg+xml;base64,%s" % safe_str(base64.b64encode(img_data))
1379 1380
1380 1381
1381 1382 def initials_gravatar(request, email_address, first_name, last_name, size=30, store_on_disk=False):
1382 1383
1383 1384 svg_type = None
1384 1385 if email_address == User.DEFAULT_USER_EMAIL:
1385 1386 svg_type = 'default_user'
1386 1387
1387 1388 klass = InitialsGravatar(email_address, first_name, last_name, size)
1388 1389
1389 1390 if store_on_disk:
1390 1391 from rhodecode.apps.file_store import utils as store_utils
1391 1392 from rhodecode.apps.file_store.exceptions import FileNotAllowedException, \
1392 1393 FileOverSizeException
1393 1394 from rhodecode.model.db import Session
1394 1395
1395 1396 image_key = md5_safe(email_address.lower()
1396 1397 + first_name.lower() + last_name.lower())
1397 1398
1398 1399 storage = store_utils.get_file_storage(request.registry.settings)
1399 1400 filename = '{}.svg'.format(image_key)
1400 1401 subdir = 'gravatars'
1401 1402 # since final name has a counter, we apply the 0
1402 1403 uid = storage.apply_counter(0, store_utils.uid_filename(filename, randomized=False))
1403 1404 store_uid = os.path.join(subdir, uid)
1404 1405
1405 1406 db_entry = FileStore.get_by_store_uid(store_uid)
1406 1407 if db_entry:
1407 1408 return request.route_path('download_file', fid=store_uid)
1408 1409
1409 1410 img_data = klass.get_img_data(svg_type=svg_type)
1410 1411 img_file = store_utils.bytes_to_file_obj(img_data)
1411 1412
1412 1413 try:
1413 1414 store_uid, metadata = storage.save_file(
1414 1415 img_file, filename, directory=subdir,
1415 1416 extensions=['.svg'], randomized_name=False)
1416 1417 except (FileNotAllowedException, FileOverSizeException):
1417 1418 raise
1418 1419
1419 1420 try:
1420 1421 entry = FileStore.create(
1421 1422 file_uid=store_uid, filename=metadata["filename"],
1422 1423 file_hash=metadata["sha256"], file_size=metadata["size"],
1423 1424 file_display_name=filename,
1424 file_description=u'user gravatar `{}`'.format(safe_unicode(filename)),
1425 file_description=f'user gravatar `{safe_str(filename)}`',
1425 1426 hidden=True, check_acl=False, user_id=1
1426 1427 )
1427 1428 Session().add(entry)
1428 1429 Session().commit()
1429 1430 log.debug('Stored upload in DB as %s', entry)
1430 1431 except Exception:
1431 1432 raise
1432 1433
1433 1434 return request.route_path('download_file', fid=store_uid)
1434 1435
1435 1436 else:
1436 1437 return klass.generate_svg(svg_type=svg_type)
1437 1438
1438 1439
1439 1440 def gravatar_external(request, gravatar_url_tmpl, email_address, size=30):
1440 1441 return safe_str(gravatar_url_tmpl)\
1441 1442 .replace('{email}', email_address) \
1442 1443 .replace('{md5email}', md5_safe(email_address.lower())) \
1443 1444 .replace('{netloc}', request.host) \
1444 1445 .replace('{scheme}', request.scheme) \
1445 1446 .replace('{size}', safe_str(size))
1446 1447
1447 1448
1448 1449 def gravatar_url(email_address, size=30, request=None):
1449 1450 request = request or get_current_request()
1450 1451 _use_gravatar = request.call_context.visual.use_gravatar
1451 1452
1452 1453 email_address = email_address or User.DEFAULT_USER_EMAIL
1453 1454 if isinstance(email_address, str):
1454 1455 # hashlib crashes on unicode items
1455 1456 email_address = safe_str(email_address)
1456 1457
1457 1458 # empty email or default user
1458 1459 if not email_address or email_address == User.DEFAULT_USER_EMAIL:
1459 1460 return initials_gravatar(request, User.DEFAULT_USER_EMAIL, '', '', size=size)
1460 1461
1461 1462 if _use_gravatar:
1462 1463 gravatar_url_tmpl = request.call_context.visual.gravatar_url \
1463 1464 or User.DEFAULT_GRAVATAR_URL
1464 1465 return gravatar_external(request, gravatar_url_tmpl, email_address, size=size)
1465 1466
1466 1467 else:
1467 1468 return initials_gravatar(request, email_address, '', '', size=size)
1468 1469
1469 1470
1470 1471 def breadcrumb_repo_link(repo):
1471 1472 """
1472 1473 Makes a breadcrumbs path link to repo
1473 1474
1474 1475 ex::
1475 1476 group >> subgroup >> repo
1476 1477
1477 1478 :param repo: a Repository instance
1478 1479 """
1479 1480
1480 1481 path = [
1481 1482 link_to(group.name, route_path('repo_group_home', repo_group_name=group.group_name),
1482 1483 title='last change:{}'.format(format_date(group.last_commit_change)))
1483 1484 for group in repo.groups_with_parents
1484 1485 ] + [
1485 1486 link_to(repo.just_name, route_path('repo_summary', repo_name=repo.repo_name),
1486 1487 title='last change:{}'.format(format_date(repo.last_commit_change)))
1487 1488 ]
1488 1489
1489 1490 return literal(' &raquo; '.join(path))
1490 1491
1491 1492
1492 1493 def breadcrumb_repo_group_link(repo_group):
1493 1494 """
1494 1495 Makes a breadcrumbs path link to repo
1495 1496
1496 1497 ex::
1497 1498 group >> subgroup
1498 1499
1499 1500 :param repo_group: a Repository Group instance
1500 1501 """
1501 1502
1502 1503 path = [
1503 1504 link_to(group.name,
1504 1505 route_path('repo_group_home', repo_group_name=group.group_name),
1505 1506 title='last change:{}'.format(format_date(group.last_commit_change)))
1506 1507 for group in repo_group.parents
1507 1508 ] + [
1508 1509 link_to(repo_group.name,
1509 1510 route_path('repo_group_home', repo_group_name=repo_group.group_name),
1510 1511 title='last change:{}'.format(format_date(repo_group.last_commit_change)))
1511 1512 ]
1512 1513
1513 1514 return literal(' &raquo; '.join(path))
1514 1515
1515 1516
1516 1517 def format_byte_size_binary(file_size):
1517 1518 """
1518 1519 Formats file/folder sizes to standard.
1519 1520 """
1520 1521 if file_size is None:
1521 1522 file_size = 0
1522 1523
1523 1524 formatted_size = format_byte_size(file_size, binary=True)
1524 1525 return formatted_size
1525 1526
1526 1527
1527 1528 def urlify_text(text_, safe=True, **href_attrs):
1528 1529 """
1529 1530 Extract urls from text and make html links out of them
1530 1531 """
1531 1532
1532 1533 url_pat = re.compile(r'''(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@#.&+]'''
1533 1534 '''|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)''')
1534 1535
1535 1536 def url_func(match_obj):
1536 1537 url_full = match_obj.groups()[0]
1537 1538 a_options = dict(href_attrs)
1538 1539 a_options['href'] = url_full
1539 1540 a_text = url_full
1540 1541 return HTML.tag("a", a_text, **a_options)
1541 1542
1542 1543 _new_text = url_pat.sub(url_func, text_)
1543 1544
1544 1545 if safe:
1545 1546 return literal(_new_text)
1546 1547 return _new_text
1547 1548
1548 1549
1549 1550 def urlify_commits(text_, repo_name):
1550 1551 """
1551 1552 Extract commit ids from text and make link from them
1552 1553
1553 1554 :param text_:
1554 1555 :param repo_name: repo name to build the URL with
1555 1556 """
1556 1557
1557 1558 url_pat = re.compile(r'(^|\s)([0-9a-fA-F]{12,40})($|\s)')
1558 1559
1559 1560 def url_func(match_obj):
1560 1561 commit_id = match_obj.groups()[1]
1561 1562 pref = match_obj.groups()[0]
1562 1563 suf = match_obj.groups()[2]
1563 1564
1564 1565 tmpl = (
1565 1566 '%(pref)s<a class="tooltip-hovercard %(cls)s" href="%(url)s" data-hovercard-alt="%(hovercard_alt)s" data-hovercard-url="%(hovercard_url)s">'
1566 1567 '%(commit_id)s</a>%(suf)s'
1567 1568 )
1568 1569 return tmpl % {
1569 1570 'pref': pref,
1570 1571 'cls': 'revision-link',
1571 1572 'url': route_url(
1572 1573 'repo_commit', repo_name=repo_name, commit_id=commit_id),
1573 1574 'commit_id': commit_id,
1574 1575 'suf': suf,
1575 1576 'hovercard_alt': 'Commit: {}'.format(commit_id),
1576 1577 'hovercard_url': route_url(
1577 1578 'hovercard_repo_commit', repo_name=repo_name, commit_id=commit_id)
1578 1579 }
1579 1580
1580 1581 new_text = url_pat.sub(url_func, text_)
1581 1582
1582 1583 return new_text
1583 1584
1584 1585
1585 1586 def _process_url_func(match_obj, repo_name, uid, entry,
1586 1587 return_raw_data=False, link_format='html'):
1587 1588 pref = ''
1588 1589 if match_obj.group().startswith(' '):
1589 1590 pref = ' '
1590 1591
1591 1592 issue_id = ''.join(match_obj.groups())
1592 1593
1593 1594 if link_format == 'html':
1594 1595 tmpl = (
1595 1596 '%(pref)s<a class="tooltip %(cls)s" href="%(url)s" title="%(title)s">'
1596 1597 '%(issue-prefix)s%(id-repr)s'
1597 1598 '</a>')
1598 1599 elif link_format == 'html+hovercard':
1599 1600 tmpl = (
1600 1601 '%(pref)s<a class="tooltip-hovercard %(cls)s" href="%(url)s" data-hovercard-url="%(hovercard_url)s">'
1601 1602 '%(issue-prefix)s%(id-repr)s'
1602 1603 '</a>')
1603 1604 elif link_format in ['rst', 'rst+hovercard']:
1604 1605 tmpl = '`%(issue-prefix)s%(id-repr)s <%(url)s>`_'
1605 1606 elif link_format in ['markdown', 'markdown+hovercard']:
1606 1607 tmpl = '[%(pref)s%(issue-prefix)s%(id-repr)s](%(url)s)'
1607 1608 else:
1608 1609 raise ValueError('Bad link_format:{}'.format(link_format))
1609 1610
1610 1611 (repo_name_cleaned,
1611 1612 parent_group_name) = RepoGroupModel()._get_group_name_and_parent(repo_name)
1612 1613
1613 1614 # variables replacement
1614 1615 named_vars = {
1615 1616 'id': issue_id,
1616 1617 'repo': repo_name,
1617 1618 'repo_name': repo_name_cleaned,
1618 1619 'group_name': parent_group_name,
1619 1620 # set dummy keys so we always have them
1620 1621 'hostname': '',
1621 1622 'netloc': '',
1622 1623 'scheme': ''
1623 1624 }
1624 1625
1625 1626 request = get_current_request()
1626 1627 if request:
1627 1628 # exposes, hostname, netloc, scheme
1628 1629 host_data = get_host_info(request)
1629 1630 named_vars.update(host_data)
1630 1631
1631 1632 # named regex variables
1632 1633 named_vars.update(match_obj.groupdict())
1633 1634 _url = string.Template(entry['url']).safe_substitute(**named_vars)
1634 1635 desc = string.Template(escape(entry['desc'])).safe_substitute(**named_vars)
1635 1636 hovercard_url = string.Template(entry.get('hovercard_url', '')).safe_substitute(**named_vars)
1636 1637
1637 1638 def quote_cleaner(input_str):
1638 1639 """Remove quotes as it's HTML"""
1639 1640 return input_str.replace('"', '')
1640 1641
1641 1642 data = {
1642 1643 'pref': pref,
1643 1644 'cls': quote_cleaner('issue-tracker-link'),
1644 1645 'url': quote_cleaner(_url),
1645 1646 'id-repr': issue_id,
1646 1647 'issue-prefix': entry['pref'],
1647 1648 'serv': entry['url'],
1648 1649 'title': bleach.clean(desc, strip=True),
1649 1650 'hovercard_url': hovercard_url
1650 1651 }
1651 1652
1652 1653 if return_raw_data:
1653 1654 return {
1654 1655 'id': issue_id,
1655 1656 'url': _url
1656 1657 }
1657 1658 return tmpl % data
1658 1659
1659 1660
1660 1661 def get_active_pattern_entries(repo_name):
1661 1662 repo = None
1662 1663 if repo_name:
1663 1664 # Retrieving repo_name to avoid invalid repo_name to explode on
1664 1665 # IssueTrackerSettingsModel but still passing invalid name further down
1665 1666 repo = Repository.get_by_repo_name(repo_name, cache=True)
1666 1667
1667 1668 settings_model = IssueTrackerSettingsModel(repo=repo)
1668 1669 active_entries = settings_model.get_settings(cache=True)
1669 1670 return active_entries
1670 1671
1671 1672
1672 1673 pr_pattern_re = regex.compile(r'(?:(?:^!)|(?: !))(\d+)')
1673 1674
1674 1675 allowed_link_formats = [
1675 1676 'html', 'rst', 'markdown', 'html+hovercard', 'rst+hovercard', 'markdown+hovercard']
1676 1677
1677 1678 compile_cache = {
1678 1679
1679 1680 }
1680 1681
1681 1682
1682 1683 def process_patterns(text_string, repo_name, link_format='html', active_entries=None):
1683 1684
1684 1685 if link_format not in allowed_link_formats:
1685 1686 raise ValueError('Link format can be only one of:{} got {}'.format(
1686 1687 allowed_link_formats, link_format))
1687 1688 issues_data = []
1688 1689 errors = []
1689 1690 new_text = text_string
1690 1691
1691 1692 if active_entries is None:
1692 1693 log.debug('Fetch active issue tracker patterns for repo: %s', repo_name)
1693 1694 active_entries = get_active_pattern_entries(repo_name)
1694 1695
1695 1696 log.debug('Got %s pattern entries to process', len(active_entries))
1696 1697
1697 for uid, entry in active_entries.items():
1698 for uid, entry in list(active_entries.items()):
1698 1699
1699 1700 if not (entry['pat'] and entry['url']):
1700 1701 log.debug('skipping due to missing data')
1701 1702 continue
1702 1703
1703 1704 log.debug('issue tracker entry: uid: `%s` PAT:%s URL:%s PREFIX:%s',
1704 1705 uid, entry['pat'], entry['url'], entry['pref'])
1705 1706
1706 1707 if entry.get('pat_compiled'):
1707 1708 pattern = entry['pat_compiled']
1708 1709 elif entry['pat'] in compile_cache:
1709 1710 pattern = compile_cache[entry['pat']]
1710 1711 else:
1711 1712 try:
1712 1713 pattern = regex.compile(r'%s' % entry['pat'])
1713 1714 except regex.error as e:
1714 1715 regex_err = ValueError('{}:{}'.format(entry['pat'], e))
1715 1716 log.exception('issue tracker pattern: `%s` failed to compile', regex_err)
1716 1717 errors.append(regex_err)
1717 1718 continue
1718 1719 compile_cache[entry['pat']] = pattern
1719 1720
1720 1721 data_func = partial(
1721 1722 _process_url_func, repo_name=repo_name, entry=entry, uid=uid,
1722 1723 return_raw_data=True)
1723 1724
1724 1725 for match_obj in pattern.finditer(text_string):
1725 1726 issues_data.append(data_func(match_obj))
1726 1727
1727 1728 url_func = partial(
1728 1729 _process_url_func, repo_name=repo_name, entry=entry, uid=uid,
1729 1730 link_format=link_format)
1730 1731
1731 1732 new_text = pattern.sub(url_func, new_text)
1732 1733 log.debug('processed prefix:uid `%s`', uid)
1733 1734
1734 1735 # finally use global replace, eg !123 -> pr-link, those will not catch
1735 1736 # if already similar pattern exists
1736 1737 server_url = '${scheme}://${netloc}'
1737 1738 pr_entry = {
1738 1739 'pref': '!',
1739 1740 'url': server_url + '/_admin/pull-requests/${id}',
1740 1741 'desc': 'Pull Request !${id}',
1741 1742 'hovercard_url': server_url + '/_hovercard/pull_request/${id}'
1742 1743 }
1743 1744 pr_url_func = partial(
1744 1745 _process_url_func, repo_name=repo_name, entry=pr_entry, uid=None,
1745 1746 link_format=link_format+'+hovercard')
1746 1747 new_text = pr_pattern_re.sub(pr_url_func, new_text)
1747 1748 log.debug('processed !pr pattern')
1748 1749
1749 1750 return new_text, issues_data, errors
1750 1751
1751 1752
1752 1753 def urlify_commit_message(commit_text, repository=None, active_pattern_entries=None,
1753 1754 issues_container_callback=None, error_container=None):
1754 1755 """
1755 1756 Parses given text message and makes proper links.
1756 1757 issues are linked to given issue-server, and rest is a commit link
1757 1758 """
1758 1759
1759 1760 def escaper(_text):
1760 1761 return _text.replace('<', '&lt;').replace('>', '&gt;')
1761 1762
1762 1763 new_text = escaper(commit_text)
1763 1764
1764 1765 # extract http/https links and make them real urls
1765 1766 new_text = urlify_text(new_text, safe=False)
1766 1767
1767 1768 # urlify commits - extract commit ids and make link out of them, if we have
1768 1769 # the scope of repository present.
1769 1770 if repository:
1770 1771 new_text = urlify_commits(new_text, repository)
1771 1772
1772 1773 # process issue tracker patterns
1773 1774 new_text, issues, errors = process_patterns(
1774 1775 new_text, repository or '', active_entries=active_pattern_entries)
1775 1776
1776 1777 if issues_container_callback is not None:
1777 1778 for issue in issues:
1778 1779 issues_container_callback(issue)
1779 1780
1780 1781 if error_container is not None:
1781 1782 error_container.extend(errors)
1782 1783
1783 1784 return literal(new_text)
1784 1785
1785 1786
1786 1787 def render_binary(repo_name, file_obj):
1787 1788 """
1788 1789 Choose how to render a binary file
1789 1790 """
1790 1791
1791 1792 # unicode
1792 1793 filename = file_obj.name
1793 1794
1794 1795 # images
1795 1796 for ext in ['*.png', '*.jpeg', '*.jpg', '*.ico', '*.gif']:
1796 1797 if fnmatch.fnmatch(filename, pat=ext):
1797 1798 src = route_path(
1798 1799 'repo_file_raw', repo_name=repo_name,
1799 1800 commit_id=file_obj.commit.raw_id,
1800 1801 f_path=file_obj.path)
1801 1802
1802 1803 return literal(
1803 1804 '<img class="rendered-binary" alt="rendered-image" src="{}">'.format(src))
1804 1805
1805 1806
1806 1807 def renderer_from_filename(filename, exclude=None):
1807 1808 """
1808 1809 choose a renderer based on filename, this works only for text based files
1809 1810 """
1810 1811
1811 1812 # ipython
1812 1813 for ext in ['*.ipynb']:
1813 1814 if fnmatch.fnmatch(filename, pat=ext):
1814 1815 return 'jupyter'
1815 1816
1816 1817 is_markup = MarkupRenderer.renderer_from_filename(filename, exclude=exclude)
1817 1818 if is_markup:
1818 1819 return is_markup
1819 1820 return None
1820 1821
1821 1822
1822 1823 def render(source, renderer='rst', mentions=False, relative_urls=None,
1823 1824 repo_name=None, active_pattern_entries=None, issues_container_callback=None):
1824 1825
1825 1826 def maybe_convert_relative_links(html_source):
1826 1827 if relative_urls:
1827 1828 return relative_links(html_source, relative_urls)
1828 1829 return html_source
1829 1830
1830 1831 if renderer == 'plain':
1831 1832 return literal(
1832 1833 MarkupRenderer.plain(source, leading_newline=False))
1833 1834
1834 1835 elif renderer == 'rst':
1835 1836 if repo_name:
1836 1837 # process patterns on comments if we pass in repo name
1837 1838 source, issues, errors = process_patterns(
1838 1839 source, repo_name, link_format='rst',
1839 1840 active_entries=active_pattern_entries)
1840 1841 if issues_container_callback is not None:
1841 1842 for issue in issues:
1842 1843 issues_container_callback(issue)
1843 1844
1844 return literal(
1845 '<div class="rst-block">%s</div>' %
1846 maybe_convert_relative_links(
1847 MarkupRenderer.rst(source, mentions=mentions)))
1845 rendered_block = maybe_convert_relative_links(
1846 MarkupRenderer.rst(source, mentions=mentions))
1847
1848 return literal(f'<div class="rst-block">{rendered_block}</div>')
1848 1849
1849 1850 elif renderer == 'markdown':
1850 1851 if repo_name:
1851 1852 # process patterns on comments if we pass in repo name
1852 1853 source, issues, errors = process_patterns(
1853 1854 source, repo_name, link_format='markdown',
1854 1855 active_entries=active_pattern_entries)
1855 1856 if issues_container_callback is not None:
1856 1857 for issue in issues:
1857 1858 issues_container_callback(issue)
1858 1859
1859
1860 return literal(
1861 '<div class="markdown-block">%s</div>' %
1862 maybe_convert_relative_links(
1863 MarkupRenderer.markdown(source, flavored=True,
1864 mentions=mentions)))
1860 rendered_block = maybe_convert_relative_links(
1861 MarkupRenderer.markdown(source, flavored=True, mentions=mentions))
1862 return literal(f'<div class="markdown-block">{rendered_block}</div>')
1865 1863
1866 1864 elif renderer == 'jupyter':
1867 return literal(
1868 '<div class="ipynb">%s</div>' %
1869 maybe_convert_relative_links(
1870 MarkupRenderer.jupyter(source)))
1865 rendered_block = maybe_convert_relative_links(
1866 MarkupRenderer.jupyter(source))
1867 return literal(f'<div class="ipynb">{rendered_block}</div>')
1871 1868
1872 1869 # None means just show the file-source
1873 1870 return None
1874 1871
1875 1872
1876 1873 def commit_status(repo, commit_id):
1877 1874 return ChangesetStatusModel().get_status(repo, commit_id)
1878 1875
1879 1876
1880 1877 def commit_status_lbl(commit_status):
1881 1878 return dict(ChangesetStatus.STATUSES).get(commit_status)
1882 1879
1883 1880
1884 1881 def commit_time(repo_name, commit_id):
1885 1882 repo = Repository.get_by_repo_name(repo_name)
1886 1883 commit = repo.get_commit(commit_id=commit_id)
1887 1884 return commit.date
1888 1885
1889 1886
1890 1887 def get_permission_name(key):
1891 1888 return dict(Permission.PERMS).get(key)
1892 1889
1893 1890
1894 1891 def journal_filter_help(request):
1895 1892 _ = request.translate
1896 1893 from rhodecode.lib.audit_logger import ACTIONS
1897 1894 actions = '\n'.join(textwrap.wrap(', '.join(sorted(ACTIONS.keys())), 80))
1898 1895
1899 1896 return _(
1900 1897 'Example filter terms:\n' +
1901 1898 ' repository:vcs\n' +
1902 1899 ' username:marcin\n' +
1903 1900 ' username:(NOT marcin)\n' +
1904 1901 ' action:*push*\n' +
1905 1902 ' ip:127.0.0.1\n' +
1906 1903 ' date:20120101\n' +
1907 1904 ' date:[20120101100000 TO 20120102]\n' +
1908 1905 '\n' +
1909 1906 'Actions: {actions}\n' +
1910 1907 '\n' +
1911 1908 'Generate wildcards using \'*\' character:\n' +
1912 1909 ' "repository:vcs*" - search everything starting with \'vcs\'\n' +
1913 1910 ' "repository:*vcs*" - search for repository containing \'vcs\'\n' +
1914 1911 '\n' +
1915 1912 'Optional AND / OR operators in queries\n' +
1916 1913 ' "repository:vcs OR repository:test"\n' +
1917 1914 ' "username:test AND repository:test*"\n'
1918 1915 ).format(actions=actions)
1919 1916
1920 1917
1921 1918 def not_mapped_error(repo_name):
1922 1919 from rhodecode.translation import _
1923 1920 flash(_('%s repository is not mapped to db perhaps'
1924 1921 ' it was created or renamed from the filesystem'
1925 1922 ' please run the application again'
1926 1923 ' in order to rescan repositories') % repo_name, category='error')
1927 1924
1928 1925
1929 1926 def ip_range(ip_addr):
1930 1927 from rhodecode.model.db import UserIpMap
1931 1928 s, e = UserIpMap._get_ip_range(ip_addr)
1932 1929 return '%s - %s' % (s, e)
1933 1930
1934 1931
1935 1932 def form(url, method='post', needs_csrf_token=True, **attrs):
1936 1933 """Wrapper around webhelpers.tags.form to prevent CSRF attacks."""
1937 1934 if method.lower() != 'get' and needs_csrf_token:
1938 1935 raise Exception(
1939 1936 'Forms to POST/PUT/DELETE endpoints should have (in general) a ' +
1940 1937 'CSRF token. If the endpoint does not require such token you can ' +
1941 1938 'explicitly set the parameter needs_csrf_token to false.')
1942 1939
1943 1940 return insecure_form(url, method=method, **attrs)
1944 1941
1945 1942
1946 1943 def secure_form(form_url, method="POST", multipart=False, **attrs):
1947 1944 """Start a form tag that points the action to an url. This
1948 1945 form tag will also include the hidden field containing
1949 1946 the auth token.
1950 1947
1951 1948 The url options should be given either as a string, or as a
1952 1949 ``url()`` function. The method for the form defaults to POST.
1953 1950
1954 1951 Options:
1955 1952
1956 1953 ``multipart``
1957 1954 If set to True, the enctype is set to "multipart/form-data".
1958 1955 ``method``
1959 1956 The method to use when submitting the form, usually either
1960 1957 "GET" or "POST". If "PUT", "DELETE", or another verb is used, a
1961 1958 hidden input with name _method is added to simulate the verb
1962 1959 over POST.
1963 1960
1964 1961 """
1965 1962
1966 1963 if 'request' in attrs:
1967 1964 session = attrs['request'].session
1968 1965 del attrs['request']
1969 1966 else:
1970 1967 raise ValueError(
1971 1968 'Calling this form requires request= to be passed as argument')
1972 1969
1973 1970 _form = insecure_form(form_url, method, multipart, **attrs)
1974 1971 token = literal(
1975 1972 '<input type="hidden" name="{}" value="{}">'.format(
1976 1973 csrf_token_key, get_csrf_token(session)))
1977 1974
1978 1975 return literal("%s\n%s" % (_form, token))
1979 1976
1980 1977
1981 1978 def dropdownmenu(name, selected, options, enable_filter=False, **attrs):
1982 1979 select_html = select(name, selected, options, **attrs)
1983 1980
1984 1981 select2 = """
1985 1982 <script>
1986 1983 $(document).ready(function() {
1987 1984 $('#%s').select2({
1988 1985 containerCssClass: 'drop-menu %s',
1989 1986 dropdownCssClass: 'drop-menu-dropdown',
1990 1987 dropdownAutoWidth: true%s
1991 1988 });
1992 1989 });
1993 1990 </script>
1994 1991 """
1995 1992
1996 1993 filter_option = """,
1997 1994 minimumResultsForSearch: -1
1998 1995 """
1999 1996 input_id = attrs.get('id') or name
2000 1997 extra_classes = ' '.join(attrs.pop('extra_classes', []))
2001 1998 filter_enabled = "" if enable_filter else filter_option
2002 1999 select_script = literal(select2 % (input_id, extra_classes, filter_enabled))
2003 2000
2004 2001 return literal(select_html+select_script)
2005 2002
2006 2003
2007 2004 def get_visual_attr(tmpl_context_var, attr_name):
2008 2005 """
2009 2006 A safe way to get a variable from visual variable of template context
2010 2007
2011 2008 :param tmpl_context_var: instance of tmpl_context, usually present as `c`
2012 2009 :param attr_name: name of the attribute we fetch from the c.visual
2013 2010 """
2014 2011 visual = getattr(tmpl_context_var, 'visual', None)
2015 2012 if not visual:
2016 2013 return
2017 2014 else:
2018 2015 return getattr(visual, attr_name, None)
2019 2016
2020 2017
2021 2018 def get_last_path_part(file_node):
2022 2019 if not file_node.path:
2023 return u'/'
2024
2025 path = safe_unicode(file_node.path.split('/')[-1])
2026 return u'../' + path
2020 return '/'
2021
2022 path = safe_str(file_node.path.split('/')[-1])
2023 return '../' + path
2027 2024
2028 2025
2029 2026 def route_url(*args, **kwargs):
2030 2027 """
2031 2028 Wrapper around pyramids `route_url` (fully qualified url) function.
2032 2029 """
2033 2030 req = get_current_request()
2034 2031 return req.route_url(*args, **kwargs)
2035 2032
2036 2033
2037 2034 def route_path(*args, **kwargs):
2038 2035 """
2039 2036 Wrapper around pyramids `route_path` function.
2040 2037 """
2041 2038 req = get_current_request()
2042 2039 return req.route_path(*args, **kwargs)
2043 2040
2044 2041
2045 2042 def route_path_or_none(*args, **kwargs):
2046 2043 try:
2047 2044 return route_path(*args, **kwargs)
2048 2045 except KeyError:
2049 2046 return None
2050 2047
2051 2048
2052 2049 def current_route_path(request, **kw):
2053 2050 new_args = request.GET.mixed()
2054 2051 new_args.update(kw)
2055 2052 return request.current_route_path(_query=new_args)
2056 2053
2057 2054
2058 2055 def curl_api_example(method, args):
2059 2056 args_json = json.dumps(OrderedDict([
2060 2057 ('id', 1),
2061 2058 ('auth_token', 'SECRET'),
2062 2059 ('method', method),
2063 2060 ('args', args)
2064 2061 ]))
2065 2062
2066 2063 return "curl {api_url} -X POST -H 'content-type:text/plain' --data-binary '{args_json}'".format(
2067 2064 api_url=route_url('apiv2'),
2068 2065 args_json=args_json
2069 2066 )
2070 2067
2071 2068
2072 2069 def api_call_example(method, args):
2073 2070 """
2074 2071 Generates an API call example via CURL
2075 2072 """
2076 2073 curl_call = curl_api_example(method, args)
2077 2074
2078 2075 return literal(
2079 2076 curl_call +
2080 2077 "<br/><br/>SECRET can be found in <a href=\"{token_url}\">auth-tokens</a> page, "
2081 2078 "and needs to be of `api calls` role."
2082 2079 .format(token_url=route_url('my_account_auth_tokens')))
2083 2080
2084 2081
2085 2082 def notification_description(notification, request):
2086 2083 """
2087 2084 Generate notification human readable description based on notification type
2088 2085 """
2089 2086 from rhodecode.model.notification import NotificationModel
2090 2087 return NotificationModel().make_description(
2091 2088 notification, translate=request.translate)
2092 2089
2093 2090
2094 2091 def go_import_header(request, db_repo=None):
2095 2092 """
2096 2093 Creates a header for go-import functionality in Go Lang
2097 2094 """
2098 2095
2099 2096 if not db_repo:
2100 2097 return
2101 2098 if 'go-get' not in request.GET:
2102 2099 return
2103 2100
2104 2101 clone_url = db_repo.clone_url()
2105 2102 prefix = re.split(r'^https?:\/\/', clone_url)[-1]
2106 2103 # we have a repo and go-get flag,
2107 2104 return literal('<meta name="go-import" content="{} {} {}">'.format(
2108 2105 prefix, db_repo.repo_type, clone_url))
2109 2106
2110 2107
2111 2108 def reviewer_as_json(*args, **kwargs):
2112 2109 from rhodecode.apps.repository.utils import reviewer_as_json as _reviewer_as_json
2113 2110 return _reviewer_as_json(*args, **kwargs)
2114 2111
2115 2112
2116 2113 def get_repo_view_type(request):
2117 2114 route_name = request.matched_route.name
2118 2115 route_to_view_type = {
2119 2116 'repo_changelog': 'commits',
2120 2117 'repo_commits': 'commits',
2121 2118 'repo_files': 'files',
2122 2119 'repo_summary': 'summary',
2123 2120 'repo_commit': 'commit'
2124 2121 }
2125 2122
2126 2123 return route_to_view_type.get(route_name)
2127 2124
2128 2125
2129 2126 def is_active(menu_entry, selected):
2130 2127 """
2131 2128 Returns active class for selecting menus in templates
2132 2129 <li class=${h.is_active('settings', current_active)}></li>
2133 2130 """
2134 2131 if not isinstance(menu_entry, list):
2135 2132 menu_entry = [menu_entry]
2136 2133
2137 2134 if selected in menu_entry:
2138 2135 return "active"
2139 2136
2140 2137
2141 2138 class IssuesRegistry(object):
2142 2139 """
2143 2140 issue_registry = IssuesRegistry()
2144 2141 some_func(issues_callback=issues_registry(...))
2145 2142 """
2146 2143
2147 2144 def __init__(self):
2148 2145 self.issues = []
2149 2146 self.unique_issues = collections.defaultdict(lambda: [])
2150 2147
2151 2148 def __call__(self, commit_dict=None):
2152 2149 def callback(issue):
2153 2150 if commit_dict and issue:
2154 2151 issue['commit'] = commit_dict
2155 2152 self.issues.append(issue)
2156 2153 self.unique_issues[issue['id']].append(issue)
2157 2154 return callback
2158 2155
2159 2156 def get_issues(self):
2160 2157 return self.issues
2161 2158
2162 2159 @property
2163 2160 def issues_unique_count(self):
2164 2161 return len(set(i['id'] for i in self.issues))
General Comments 0
You need to be logged in to leave comments. Login now