[debug-toolbar/display_source_code] add helper to render link to source file

Closes #17256791

authorLaurent Peuch <cortex@worlddomination.be>
changeseta2b8c201727f
branchdefault
phasepublic
hiddenno
parent revision#70597b447fb7 [debug-toolbar/display_source_code] add a pyramid view that display syntax highlighted python source file
child revision#3a38f779bed5 [debug-toolbar/display_source_code/security] add security mechanism to only read whitelisted files
files modified by this revision
cubicweb/pyramid/debug_source_code.py
# HG changeset patch
# User Laurent Peuch <cortex@worlddomination.be>
# Date 1569559889 -7200
# Fri Sep 27 06:51:29 2019 +0200
# Node ID a2b8c201727f27c33ba2804617ac4c0193f9080b
# Parent 70597b447fb7c53f6c649b5bc17909c384cdca84
[debug-toolbar/display_source_code] add helper to render link to source file

Closes #17256791

diff --git a/cubicweb/pyramid/debug_source_code.py b/cubicweb/pyramid/debug_source_code.py
@@ -20,20 +20,51 @@
1  """
2  Debug view for pyramid debug toolbar and others to help development
3  """
4 
5  import os
6 +import logging
7 +import inspect
8 
9  from pyramid.response import Response
10  from mako.template import Template
11 
12  from cubicweb.misc.source_highlight import highlight_html, generate_css, has_pygments
13 
14 
15  DEBUG_DISPLAY_SOURCE_CODE_PATH = '_debug_display_source_code'
16 
17 
18 +def source_code_url(object_or_class):
19 +    if object_or_class is None:
20 +        return ""
21 +
22 +    if not inspect.isclass(object_or_class):
23 +        object_or_class = object_or_class.__class__
24 +
25 +    try:
26 +        file_path = inspect.getsourcefile(object_or_class)
27 +    except TypeError:
28 +        logging.debug("Error while trying to source code of '%s'" % object_or_class)
29 +        return ""
30 +
31 +    try:
32 +        source_code, line = inspect.getsourcelines(object_or_class)
33 +    except OSError:  # when we couldn't read the source code/line
34 +        return '<a href="../%s?file=%s" target="_blank">&lt;&gt;</a>' % (
35 +            DEBUG_DISPLAY_SOURCE_CODE_PATH, file_path
36 +        )
37 +
38 +    # step back a bit so we have a bit of top padding wen displaying the page
39 +    # and the highlighted line isn't glued to top of the browser window
40 +    line_anchor = max(0, line - 10)
41 +
42 +    return '<a href="../%s?file=%s&line=%s&end=%s#line-%s" target="_blank">&lt;&gt;</a>' % (
43 +        DEBUG_DISPLAY_SOURCE_CODE_PATH, file_path, line, line + len(source_code), line_anchor
44 +    )
45 +
46 +
47  def debug_display_source_code(request):
48      """
49      This view display a python source file content for making debugging easier.
50 
51      It is only activated on debug mode (-D) for pyramid during development.