[debug/debug_source_code] add helper to render link to source file draft
authorLaurent Peuch <cortex@worlddomination.be>
Fri, 27 Sep 2019 06:51:29 +0200
changeset 13432 20c33beec0e8
parent 13431 5a334735a4eb
child 13433 18deb53bb418
[debug/debug_source_code] add helper to render link to source file
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
 
@@ -31,6 +33,33 @@
 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 the source code/line
+        return '<a href="../%s?file=%s" target="_blank">&lt;&gt;</a>' % (
+            DEBUG_DISPLAY_SOURCE_CODE_PATH, file_path
+        )
+
+    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.