[debug-toolbar/display_source_code] add helper to render link to source file
authorLaurent Peuch <cortex@worlddomination.be>
Fri, 27 Sep 2019 06:51:29 +0200
changeset 12772 a2b8c201727f
parent 12771 70597b447fb7
child 12773 3a38f779bed5
[debug-toolbar/display_source_code] add helper to render link to source file Closes #17256791
cubicweb/pyramid/debug_source_code.py
--- a/cubicweb/pyramid/debug_source_code.py	Tue Oct 08 22:14:06 2019 +0200
+++ b/cubicweb/pyramid/debug_source_code.py	Fri Sep 27 06:51:29 2019 +0200
@@ -22,6 +22,8 @@
 """
 
 import os
+import logging
+import inspect
 
 from pyramid.response import Response
 from mako.template import Template
@@ -32,6 +34,35 @@
 DEBUG_DISPLAY_SOURCE_CODE_PATH = '_debug_display_source_code'
 
 
+def source_code_url(object_or_class):
+    if object_or_class is None:
+        return ""
+
+    if not inspect.isclass(object_or_class):
+        object_or_class = object_or_class.__class__
+
+    try:
+        file_path = inspect.getsourcefile(object_or_class)
+    except TypeError:
+        logging.debug("Error while trying to source code of '%s'" % object_or_class)
+        return ""
+
+    try:
+        source_code, line = inspect.getsourcelines(object_or_class)
+    except OSError:  # when we couldn't read the source code/line
+        return '<a href="../%s?file=%s" target="_blank">&lt;&gt;</a>' % (
+            DEBUG_DISPLAY_SOURCE_CODE_PATH, file_path
+        )
+
+    # step back a bit so we have a bit of top padding wen displaying the page
+    # and the highlighted line isn't glued to top of the browser window
+    line_anchor = max(0, line - 10)
+
+    return '<a href="../%s?file=%s&line=%s&end=%s#line-%s" target="_blank">&lt;&gt;</a>' % (
+        DEBUG_DISPLAY_SOURCE_CODE_PATH, file_path, line, line + len(source_code), line_anchor
+    )
+
+
 def debug_display_source_code(request):
     """
     This view display a python source file content for making debugging easier.