Salome HOME
best docstring src/debug.py
[tools/sat.git] / src / debug.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3
4 #  Copyright (C) 2010-2018  CEA/DEN
5 #
6 #  This library is free software; you can redistribute it and/or
7 #  modify it under the terms of the GNU Lesser General Public
8 #  License as published by the Free Software Foundation; either
9 #  version 2.1 of the License.
10 #
11 #  This library is distributed in the hope that it will be useful,
12 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 #  Lesser General Public License for more details.
15 #
16 #  You should have received a copy of the GNU Lesser General Public
17 #  License along with this library; if not, write to the Free Software
18 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19
20 """
21 This file assume DEBUG functionalities use
22 - print debug messages in sys.stderr for salomeTools
23 - show pretty print debug representation from instances of SAT classes
24   (pretty print src.pyconf.Config), and python dict/list etc. (as 'aVariable')
25
26 WARNING: obviously supposedly show messages in SAT development phase, not production
27
28 usage:
29 >> import debug as DBG
30 >> DBG.write("aTitle", aVariable)        # not shown in production 
31 >> DBG.write("aTitle", aVariable, True)  # unconditionaly shown (as show=True)
32
33 to set show message as development phase:
34 >> DBG.push_debug(True)
35
36 to set no show message as production phase:
37 >> DBG.push_debug(False)
38
39 to set show message temporary as development phase, only in a method:
40 >> def aMethodToDebug(...):
41 >>   DBG.push_debug(True)              #force show as appended status
42 >>   etc. method code with some DBG.write()
43 >>   DBG.pop_debug()                   #restore previous status (show or not show)
44 >>   return
45
46 to set a message for future fix, as temporary problem to not forget:
47 DBG.tofix("aTitle", aVariable, True/False) #True/False in production shown, or not
48 """
49
50 import os
51 import sys
52 import StringIO as SIO
53 import pprint as PP
54
55 _debug = [False] #support push/pop for temporary activate debug outputs
56
57 def indent(text, amount=2, ch=' '):
58     """indent multi lines message"""
59     padding = amount * ch
60     return ''.join(padding + line for line in text.splitlines(True))
61
62 def write(title, var="", force=None, fmt="\n#### DEBUG: %s:\n%s\n"):
63     """write sys.stderr a message if _debug[-1]==True or optionaly force=True"""
64     if _debug[-1] or force:
65         if 'src.pyconf.' in str(type(var)): 
66             sys.stderr.write(fmt % (title, indent(getStrConfigDbg(var))))
67         elif type(var) is not str:
68             sys.stderr.write(fmt % (title, indent(PP.pformat(var))))
69         else:
70             sys.stderr.write(fmt % (title, indent(var)))
71     return
72
73 def tofix(title, var="", force=None):
74     """
75     write sys.stderr a message if _debug[-1]==True or optionaly force=True
76     use this only if no logger accessible for classic 
77     logger.warning(message) or logger.debug(message)
78     """
79     fmt = "\n#### TOFIX: %s:\n%s\n"
80     write(title, var, force, fmt)
81
82 def push_debug(aBool):
83     """set debug outputs activated, or not"""
84     _debug.append(aBool)
85
86 def pop_debug():
87     """restore previous debug outputs status"""
88     if len(_debug) > 1:
89         return _debug.pop()
90     else:
91         sys.stderr.write("\nERROR: pop_debug: too much pop.")
92         return None
93
94 ###############################################
95 # utilitaires divers pour debug
96 ###############################################
97
98 class OutStream(SIO.StringIO):
99     """utility class for pyconf.Config output iostream"""
100     def close(self):
101       """because Config.__save__ calls close() stream as file
102       keep value before lost as self.value
103       """
104       self.value = self.getvalue()
105       SIO.StringIO.close(self)
106     
107 class InStream(SIO.StringIO):
108     """utility class for pyconf.Config input iostream"""
109     pass
110
111 def getLocalEnv():
112     """get string for environment variables representation"""
113     res = ""
114     for i in sorted(os.environ):
115         res += "%s : %s\n" % (i, os.environ[i])
116     return res
117
118 # save as initial Config.save() moved as Config.__save__() 
119 def saveConfigStd(config, aStream):
120     """returns as file .pyconf"""
121     indent =  0
122     config.__save__(aStream, indent) 
123
124 def getStrConfigStd(config):
125     """set string as saveConfigStd, 
126     as file .pyconf"""
127     outStream = OutStream()
128     saveConfigStd(config, outStream)
129     return outStream.value
130
131 def getStrConfigDbg(config):
132     """set string as saveConfigDbg, 
133     as (path expression evaluation) for debug"""
134     outStream = OutStream()
135     saveConfigDbg(config, outStream)
136     return outStream.value
137
138 def saveConfigDbg(config, aStream, indent=0, path=""):
139     """pyconf returns multilines (path expression evaluation) for debug"""
140     _saveConfigRecursiveDbg(config, aStream, indent, path)
141     aStream.close() # as config.__save__()
142
143 def _saveConfigRecursiveDbg(config, aStream, indent, path):
144     """pyconf inspired from Mapping.__save__"""
145     debug = False
146     if indent <= 0: 
147       indentp = 0
148     else:
149       indentp = indentp + 2
150     indstr = indent * ' ' # '':no indent, ' ':indent
151     strType = str(type(config))
152     if "Sequence" in strType:
153       for i in range(len(config)):
154         _saveConfigRecursiveDbg(config[i], aStream, indentp, path+"[%i]" % i)
155       return
156     try: 
157       order = object.__getattribute__(config, 'order')
158       data = object.__getattribute__(config, 'data')
159     except:
160       aStream.write("%s%s : '%s'\n" % (indstr, path, str(config)))
161       return     
162     for key in sorted(order):
163       value = data[key]
164       strType = str(type(value))
165       if debug: print indstr + 'strType = %s' % strType, key
166       if "Config" in strType:
167         _saveConfigRecursiveDbg(value, aStream, indentp, path+"."+key)
168         continue
169       if "Mapping" in strType:
170         _saveConfigRecursiveDbg(value, aStream, indentp, path+"."+key)
171         continue
172       if "Sequence" in strType:
173         for i in range(len(value)):
174           _saveConfigRecursiveDbg(value[i], aStream, indentp, path+"."+key+"[%i]" % i)
175         continue
176       if "Expression" in strType:
177         try:
178           evaluate = value.evaluate(config)
179           aStream.write("%s%s.%s : %s --> '%s'\n" % (indstr, path, key, str(value), evaluate))
180         except Exception as e:      
181           aStream.write("%s%s.%s : !!! ERROR: %s !!!\n" % (indstr, path, key, e.message))     
182         continue
183       if "Reference" in strType:
184         try:
185           evaluate = value.resolve(config)
186           aStream.write("%s%s.%s : %s --> '%s'\n" % (indstr, path, key, str(value), evaluate))
187         except Exception as e:  
188           aStream.write("%s%s.%s : !!! ERROR: %s !!!\n" % (indstr, path, key, e.message))     
189         continue
190       if type(value) in [str, bool, int, type(None), unicode]:
191         aStream.write("%s%s.%s : '%s'\n" % (indstr, path, key, str(value)))
192         continue
193       try:
194         aStream.write("!!! TODO fix that %s %s%s.%s : %s\n" % (type(value), indstr, path, key, str(value)))
195       except Exception as e:      
196         aStream.write("%s%s.%s : !!! %s\n" % (indstr, path, key, e.message))