Salome HOME
spns #26801 : bug sat package, le lanceur ne faisait pas le réinit
[tools/sat.git] / src / debug.py
index 4d0b046fdcc2eb81ff250d3b95e72fe02a85da08..1fbdcd47b39827ac27eed8a147492be0b651dc7d 100755 (executable)
@@ -54,15 +54,32 @@ Show pretty print debug representation from instances of SAT classes
 import os
 import sys
 import traceback
-import StringIO as SIO
 import pprint as PP
+import inspect
+import src
+
+# Compatibility python 2/3 for unicode
+try:
+    _test = unicode
+except:
+    unicode = str
+
+# Compatibility python 2/3 for StringIO
+try:
+    from StringIO import StringIO
+except ImportError:
+    from io import StringIO
 
 _debug = [False] #support push/pop for temporary activate debug outputs
 
-_user = os.environ['USER']
 # wambeke is christian at home
-_developpers = ["christian", "wambeke", "crouzet"] # crouzet, kloss ...
+_developers = ["xchristian", "xwambeke"]
+
 
+def isDeveloper():
+    """if you are a developer, sometimes you want verbose traces etc."""
+    res = src.architecture.get_user()  in _developers
+    return res
 
 def indent(text, amount=2, ch=' '):
     """indent multi lines message"""
@@ -79,13 +96,17 @@ def isTypeConfig(var):
     # print "NOT isTypeConfig %s" % typ
     return False
     
-def write(title, var="", force=None, fmt="\n#### DEBUG: %s:\n%s\n"):
+def write(title, var="", force=None, fmt="  %s:\n%s\n####\n"):
     """write sys.stderr a message if _debug[-1]==True or optionaly force=True"""
     if _debug[-1] or force:
+      callerframerecord = inspect.stack()[1] # get info of the caller
+      frame = callerframerecord[0]
+      info = inspect.getframeinfo(frame)
+      sys.stderr.write("\n#### DEBUG - %s:%s (%s) ####\n" % (info.filename, info.lineno, info.function))
       tvar = type(var)
       typ = str(tvar)
       if isTypeConfig(var):
-        sys.stderr.write(fmt % (title, indent(COLS.toColor(getStrConfigDbg(var)))))
+        sys.stderr.write(fmt % (title, indent(getStrConfigDbg(var))))
         return
       if 'UnittestStream' in typ:
         sys.stderr.write(fmt % (title, indent(var.getLogs())))
@@ -102,8 +123,13 @@ def tofix(title, var="", force=None):
     write sys.stderr a message if _debug[-1]==True or optionaly force=True
     use this only if no logger accessible for classic logger.warning(message)
     """
-    fmt = "\n#### TOFIX: %s:\n%s\n"
-    write(title, var, force, fmt)
+    if _debug[-1] or isDeveloper():
+        callerframerecord = inspect.stack()[1] # get info of the caller
+        frame = callerframerecord[0]
+        info = inspect.getframeinfo(frame)
+        fmt = "#### TOFIX - " + str(info.filename) + ":" + str(info.lineno) +\
+              " (" + str(info.function) + ") ####\n   %s:\n%s\n"
+        write(title, var, force, fmt)
 
 def push_debug(aBool):
     """set debug outputs activated, or not"""
@@ -122,30 +148,25 @@ def format_exception(msg, limit=None, trace=None):
   """
   Format a stack trace and the exception information.
   as traceback.format_exception(), without color
-  with traceback only if (_debug) or (DBG._user in DBG._developpers)
+  with traceback only if (_debug) or (DBG._user in DBG._developers)
   """
   etype, value, tb = sys.exc_info()
-  if (_debug[-1]) or (_user in _developpers):
-    res = msg
-    if tb:
-      res += "\nTraceback (most recent call last):\n"
-      res += "".join(traceback.format_tb(tb, limit))  # [:-1])
-    res += "\n"
-    res += "\n".join(traceback.format_exception_only(etype, value))
-    return res
-  else:
-    res = msg
-    res += "".join(traceback.format_exception_only(etype, value))
-    return res
+  res = msg
+  if tb:
+    res += "\nTraceback (most recent call last):\n"
+    res += "".join(traceback.format_tb(tb, limit))  # [:-1])
+  res += "\n"
+  res += "\n".join(traceback.format_exception_only(etype, value))
+  return res
 
 def format_color_exception(msg, limit=None, trace=None):
   """
   Format a stack trace and the exception information.
   as traceback.format_exception(), with color
-  with traceback only if (_debug) or (DBG._user in DBG._developpers)
+  with traceback only if _debug or isDeveloper())
   """
   etype, value, tb = sys.exc_info()
-  if (_debug[-1]) or (_user in _developpers):
+  if _debug[-1] or isDeveloper():
     res = "<red>" + msg
     if tb:
       res += "<yellow>\nTraceback (most recent call last):\n"
@@ -163,7 +184,7 @@ def format_color_exception(msg, limit=None, trace=None):
 # utilitaires divers pour debug
 ###############################################
 
-class OutStream(SIO.StringIO):
+class OutStream(StringIO):
     """
     utility class for pyconf.Config output iostream
     """
@@ -173,9 +194,9 @@ class OutStream(SIO.StringIO):
       keep value before lost as self.value
       """
       self.value = self.getvalue()
-      SIO.StringIO.close(self)
+      StringIO.close(self)
     
-class InStream(SIO.StringIO):
+class InStream(StringIO):
     """utility class for pyconf.Config input iostream"""
     pass
 
@@ -229,7 +250,7 @@ def _saveConfigRecursiveDbg(config, aStream, indent, path, nb):
     
     indstr = indent * ' ' # '':no indent, ' ':indent
     strType = str(type(config))
-    if debug: print "saveDbg Type", path, strType
+    if debug: print("saveDbg Type %s %s" % (path, strType))
     
     if "Sequence" in strType:
       for i in range(len(config)):
@@ -241,7 +262,7 @@ def _saveConfigRecursiveDbg(config, aStream, indent, path, nb):
         #evaluate = value.resolve(config)
         aStream.write("<header>%s%s<reset> : %s <yellow>--> '%s'<reset>\n" % (indstr, path, config, str(config)))
       except Exception as e:  
-        aStream.write("<header>%s%s<reset> : <red>!!! ERROR: %s !!!<reset>\n" % (indstr, path, e.message))     
+        aStream.write("<header>%s%s<reset> : <red>!!! ERROR: %s !!!<reset>\n" % (indstr, path, str(e)))     
       return
     '''
     
@@ -254,7 +275,7 @@ def _saveConfigRecursiveDbg(config, aStream, indent, path, nb):
     for key in sorted(data): #order): # data as sort alphabetical, order as initial order
       value = data[key]
       strType = str(type(value))
-      if debug: print 'strType', path, key, strType
+      if debug: print('strType %s %s %s' % (path, key, strType))
       if "Config" in strType:
         _saveConfigRecursiveDbg(value, aStream, indentp, path+"."+key, nbp)
         continue
@@ -270,14 +291,14 @@ def _saveConfigRecursiveDbg(config, aStream, indent, path, nb):
           evaluate = value.evaluate(config)
           aStream.write("%s%s.%s : %s --> '%s'\n" % (indstr, path, key, str(value), evaluate))
         except Exception as e:      
-          aStream.write("%s%s.%s : !!! ERROR: %s !!!\n" % (indstr, path, key, e.message))     
+          aStream.write("%s%s.%s : !!! ERROR: %s !!!\n" % (indstr, path, key, str(e)))     
         continue
       if "Reference" in strType:
         try:
           evaluate = value.resolve(config)
           aStream.write("%s%s.%s : %s --> '%s'\n" % (indstr, path, key, str(value), evaluate))
         except Exception as e:  
-          aStream.write("%s%s.%s : !!! ERROR: %s !!!\n" % (indstr, path, key, e.message))     
+          aStream.write("%s%s.%s : !!! ERROR: %s !!!\n" % (indstr, path, key, str(e)))     
         continue
       if type(value) in [str, bool, int, type(None), unicode]:
         aStream.write("%s%s.%s : '%s'\n" % (indstr, path, key, str(value)))
@@ -285,4 +306,4 @@ def _saveConfigRecursiveDbg(config, aStream, indent, path, nb):
       try:
         aStream.write("!!! TODO fix that %s %s%s.%s : %s\n" % (type(value), indstr, path, key, str(value)))
       except Exception as e:      
-        aStream.write("%s%s.%s : !!! %s\n" % (indstr, path, key, e.message))
+        aStream.write("%s%s.%s : !!! %s\n" % (indstr, path, key, str(e)))