Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 155 lines (131 sloc) 4.643 kB
59ba994 @mcdonc first cut; haven't run yet
mcdonc authored
1 import os.path
2 import sys
e739d91 @mcdonc - The ``debugtoolbar.intercept_exc`` setting is now a tri-state setti…
mcdonc authored
3 from logging import getLogger
4
c50770d @mcdonc general cleanup and refactoring
mcdonc authored
5 from pyramid.util import DottedNameResolver
e739d91 @mcdonc - The ``debugtoolbar.intercept_exc`` setting is now a tri-state setti…
mcdonc authored
6 from pyramid.settings import asbool
59ba994 @mcdonc first cut; haven't run yet
mcdonc authored
7
aea5fc7 @mcdonc fucking kill me
mcdonc authored
8 from pyramid_debugtoolbar.compat import binary_type
9 from pyramid_debugtoolbar.compat import text_type
10 from pyramid_debugtoolbar.compat import string_types
59deef6 @mcdonc - Fix Python 3 compatibility in SQLAlchemy panel.
mcdonc authored
11 from pyramid_debugtoolbar.compat import text_
aea5fc7 @mcdonc fucking kill me
mcdonc authored
12
13
ef0cd12 @blaflamme initial sqlalchemy debug panel
blaflamme authored
14 try:
15 from pygments import highlight
16 from pygments.formatters import HtmlFormatter
17 from pygments.lexers import SqlLexer
18 from pygments.styles import get_style_by_name
19 PYGMENT_STYLE = get_style_by_name('colorful')
20 HAVE_PYGMENTS = True
879c582 @mcdonc bring test coverage for original code back up to 100%
mcdonc authored
21 except ImportError: # pragma: no cover
ef0cd12 @blaflamme initial sqlalchemy debug panel
blaflamme authored
22 HAVE_PYGMENTS = False
23
2b8214e @mcdonc more utils tests
mcdonc authored
24 SETTINGS_PREFIX = 'debugtoolbar.'
3ec2e52 @mcdonc move STATIC_PATH to utils (avoid circular imports)
mcdonc authored
25 STATIC_PATH = 'pyramid_debugtoolbar:static/'
b92760b @mcdonc dynamicize debugger urls
mcdonc authored
26 ROOT_ROUTE_NAME = 'debugtoolbar.root'
e739d91 @mcdonc - The ``debugtoolbar.intercept_exc`` setting is now a tri-state setti…
mcdonc authored
27 EXC_ROUTE_NAME = 'debugtoolbar.exception'
2b8214e @mcdonc more utils tests
mcdonc authored
28
fac62b0 @caseman Fix format_fname() to properly remove sys.path prefixes. Previous imp…
caseman authored
29 def format_fname(value, _sys_path=None):
30 if _sys_path is None:
31 _sys_path = sys.path # dependency injection
59ba994 @mcdonc first cut; haven't run yet
mcdonc authored
32 # If the value is not an absolute path, the it is a builtin or
33 # a relative file (thus a project file).
34 if not os.path.isabs(value):
35 if value.startswith(('{', '<')):
36 return value
37 if value.startswith('.' + os.path.sep):
38 return value
39 return '.' + os.path.sep + value
40
41 # Loop through sys.path to find the longest match and return
42 # the relative path from there.
43 prefix_len = 0
fac62b0 @caseman Fix format_fname() to properly remove sys.path prefixes. Previous imp…
caseman authored
44 value_segs = value.split(os.path.sep)
45 for path in _sys_path:
46 count = common_segment_count(path.split(os.path.sep), value_segs)
47 if count > prefix_len:
48 prefix_len = count
49 return '<%s>' % os.path.sep.join(value_segs[prefix_len:])
59ba994 @mcdonc first cut; haven't run yet
mcdonc authored
50
fac62b0 @caseman Fix format_fname() to properly remove sys.path prefixes. Previous imp…
caseman authored
51 def common_segment_count(path, value):
52 """Return the number of path segments common to both"""
53 i = 0
54 if len(path) <= len(value):
55 for x1, x2 in zip(path, value):
56 if x1 == x2:
57 i += 1
58 else:
59 return 0
60 return i
59ba994 @mcdonc first cut; haven't run yet
mcdonc authored
61
879c582 @mcdonc bring test coverage for original code back up to 100%
mcdonc authored
62 def format_sql(query):
63 if not HAVE_PYGMENTS: # pragma: no cover
59deef6 @mcdonc - Fix Python 3 compatibility in SQLAlchemy panel.
mcdonc authored
64 return text_(query)
ef0cd12 @blaflamme initial sqlalchemy debug panel
blaflamme authored
65
59deef6 @mcdonc - Fix Python 3 compatibility in SQLAlchemy panel.
mcdonc authored
66 return text_(
67 highlight(
68 query,
69 SqlLexer(encoding='utf-8'),
70 HtmlFormatter(encoding='utf-8', noclasses=True,
71 style=PYGMENT_STYLE)
72 )
73 )
ef0cd12 @blaflamme initial sqlalchemy debug panel
blaflamme authored
74
c44b7c6 @mcdonc work towards an interactive debugger (steal armin's debugger guts)
mcdonc authored
75 def escape(s, quote=False):
76 """Replace special characters "&", "<" and ">" to HTML-safe sequences. If
77 the optional flag `quote` is `True`, the quotation mark character is
78 also translated.
79
80 There is a special handling for `None` which escapes to an empty string.
81
82 :param s: the string to escape.
83 :param quote: set to true to also escape double quotes.
84 """
85 if s is None:
86 return ''
9057f74 @mcdonc make repr tests pass on both py2 and py3
mcdonc authored
87 if hasattr(s, '__html__'):
c44b7c6 @mcdonc work towards an interactive debugger (steal armin's debugger guts)
mcdonc authored
88 return s.__html__()
9057f74 @mcdonc make repr tests pass on both py2 and py3
mcdonc authored
89 if not isinstance(s, (text_type, binary_type)):
90 s = text_type(s)
c44b7c6 @mcdonc work towards an interactive debugger (steal armin's debugger guts)
mcdonc authored
91 s = s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
92 if quote:
93 s = s.replace('"', "&quot;")
94 return s
95
c50770d @mcdonc general cleanup and refactoring
mcdonc authored
96 def replace_insensitive(string, target, replacement):
97 """Similar to string.replace() but is case insensitive
98 Code borrowed from: http://forums.devshed.com/python-programming-11/case-insensitive-string-replace-490921.html
99 """
100 no_case = string.lower()
101 index = no_case.rfind(target.lower())
102 if index >= 0:
103 return string[:index] + replacement + string[index + len(target):]
104 else: # no results so return the original string
105 return string
106
107 resolver = DottedNameResolver(None)
c44b7c6 @mcdonc work towards an interactive debugger (steal armin's debugger guts)
mcdonc authored
108
d377d08 @mcdonc accept single-line space-separated values as list items
mcdonc authored
109 def as_cr_separated_list(value):
aea5fc7 @mcdonc fucking kill me
mcdonc authored
110 if isinstance(value, string_types):
c50770d @mcdonc general cleanup and refactoring
mcdonc authored
111 value = filter(None, [x.strip() for x in value.splitlines()])
42fe2ee @mcdonc add hosts setting
mcdonc authored
112 return value
113
d377d08 @mcdonc accept single-line space-separated values as list items
mcdonc authored
114 def as_list(value):
115 values = as_cr_separated_list(value)
116 result = []
117 for value in values:
118 subvalues = value.split()
119 result.extend(subvalues)
120 return result
121
42fe2ee @mcdonc add hosts setting
mcdonc authored
122 def as_globals_list(value):
123 L = []
124 value = as_list(value)
c50770d @mcdonc general cleanup and refactoring
mcdonc authored
125 for dottedname in value:
126 obj = resolver.resolve(dottedname)
127 L.append(obj)
128 return L
c44b7c6 @mcdonc work towards an interactive debugger (steal armin's debugger guts)
mcdonc authored
129
e739d91 @mcdonc - The ``debugtoolbar.intercept_exc`` setting is now a tri-state setti…
mcdonc authored
130 def as_display_debug_or_false(value):
aea5fc7 @mcdonc fucking kill me
mcdonc authored
131 if isinstance(value, string_types):
e739d91 @mcdonc - The ``debugtoolbar.intercept_exc`` setting is now a tri-state setti…
mcdonc authored
132 val = value.lower().strip()
133 if val in ('display', 'debug'):
134 return val
135 b = asbool(value)
136 if b: # bw compat for dbt <=0.9
137 return 'debug'
138 return False
139
2b8214e @mcdonc more utils tests
mcdonc authored
140 def get_setting(settings, name, default=None):
141 return settings.get('%s%s' % (SETTINGS_PREFIX, name), default)
9660328 @mcdonc - Some renderings of the request vars and renderer values would raise an
mcdonc authored
142
143 def dictrepr(d):
144 out = {}
145 for val in d:
146 try:
147 out[val] = repr(d[val])
148 except:
149 # defensive
150 out[val] = '<unknown>'
151 return sorted(out.items())
e739d91 @mcdonc - The ``debugtoolbar.intercept_exc`` setting is now a tri-state setti…
mcdonc authored
152
153 logger = getLogger('pyramid_debugtoolbar')
154
Something went wrong with that request. Please try again.