Salome HOME
fix apidoc sphinx ERROR: Unexpected indentation
[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
23 - print debug messages in sys.stderr for salomeTools
24 - show pretty print debug representation from instances of SAT classes
25   (pretty print src.pyconf.Config), and python dict/list etc. (as 'aVariable')
26
27 WARNING: obviously supposedly show messages in SAT development phase, not production
28
29 usage:
30 >> import debug as DBG
31 >> DBG.write("aTitle", aVariable)        # not shown in production 
32 >> DBG.write("aTitle", aVariable, True)  # unconditionaly shown (as show=True)
33
34 to set show message as development phase:
35 >> DBG.push_debug(True)
36
37 to set no show message as production phase:
38 >> DBG.push_debug(False)
39
40 to set show message temporary as development phase, only in a method:
41 >> def aMethodToDebug(...):
42 >>   DBG.push_debug(True)              #force show as appended status
43 >>   etc. method code with some DBG.write()
44 >>   DBG.pop_debug()                   #restore previous status (show or not show)
45 >>   return
46
47 to set a message for future fix, as temporary problem to not forget:
48 DBG.tofix("aTitle", aVariable, True/False) #True/False in production shown, or not
49 """
50
51 import os
52 import sys
53 import StringIO as SIO
54 import pprint as PP
55
56 _debug = [False] #support push/pop for temporary activate debug outputs
57
58 def indent(text, amount=2, ch=' '):
59     """indent multi lines message"""
60     padding = amount * ch
61     return ''.join(padding + line for line in text.splitlines(True))
62
63 def write(title, var="", force=None, fmt="\n#### DEBUG: %s:\n%s\n"):
64     """write sys.stderr a message if _debug[-1]==True or optionaly force=True"""
65     if _debug[-1] or force:
66         if 'src.pyconf.' in str(type(var)): 
67             sys.stderr.write(fmt % (title, indent(getStrConfigDbg(var))))
68         elif type(var) is not str:
69             sys.stderr.write(fmt % (title, indent(PP.pformat(var))))
70         else:
71             sys.stderr.write(fmt % (title, indent(var)))
72     return
73
74 def tofix(title, var="", force=None):
75     """\
76     write sys.stderr a message if _debug[-1]==True or optionaly force=True
77     use this only if no logger accessible for classic 
78     logger.warning(message) or logger.debug(message)
79     """
80     fmt = "\n#### TOFIX: %s:\n%s\n"
81     write(title, var, force, fmt)
82
83 def push_debug(aBool):
84     """set debug outputs activated, or not"""
85     _debug.append(aBool)
86
87 def pop_debug():
88     """restore previous debug outputs status"""
89     if len(_debug) > 1:
90         return _debug.pop()
91     else:
92         sys.stderr.write("\nERROR: pop_debug: too much pop.")
93         return None
94
95 ###############################################
96 # utilitaires divers pour debug
97 ###############################################
98
99 class OutStream(SIO.StringIO):
100     """utility class for pyconf.Config output iostream"""
101     def close(self):
102       """because Config.__save__ calls close() stream as file
103       keep value before lost as self.value
104       """
105       self.value = self.getvalue()
106       SIO.StringIO.close(self)
107     
108 class InStream(SIO.StringIO):
109     """utility class for pyconf.Config input iostream"""
110     pass
111
112 def getLocalEnv():
113     """get string for environment variables representation"""
114     res = ""
115     for i in sorted(os.environ):
116         res += "%s : %s\n" % (i, os.environ[i])
117     return res
118
119 # save as initial Config.save() moved as Config.__save__() 
120 def saveConfigStd(config, aStream):
121     """returns as file .pyconf"""
122     indent =  0
123     config.__save__(aStream, indent) 
124
125 def getStrConfigStd(config):
126     """set string as saveConfigStd, as file .pyconf"""
127     outStream = OutStream()
128     saveConfigStd(config, outStream)
129     return outStream.value
130
131 def getStrConfigDbg(config):
132     """\
133     set string as saveConfigDbg, 
134     as (path expression evaluation) for debug
135     """
136     outStream = OutStream()
137     saveConfigDbg(config, outStream)
138     return outStream.value
139
140 def saveConfigDbg(config, aStream, indent=0, path=""):
141     """pyconf returns multilines (path expression evaluation) for debug"""
142     _saveConfigRecursiveDbg(config, aStream, indent, path)
143     aStream.close() # as config.__save__()
144
145 def _saveConfigRecursiveDbg(config, aStream, indent, path):
146     """pyconf inspired from Mapping.__save__"""
147     debug = False
148     if indent <= 0: 
149       indentp = 0
150     else:
151       indentp = indentp + 2
152     indstr = indent * ' ' # '':no indent, ' ':indent
153     strType = str(type(config))
154     if "Sequence" in strType:
155       for i in range(len(config)):
156         _saveConfigRecursiveDbg(config[i], aStream, indentp, path+"[%i]" % i)
157       return
158     try: 
159       order = object.__getattribute__(config, 'order')
160       data = object.__getattribute__(config, 'data')
161     except:
162       aStream.write("%s%s : '%s'\n" % (indstr, path, str(config)))
163       return     
164     for key in sorted(order):
165       value = data[key]
166       strType = str(type(value))
167       if debug: print indstr + 'strType = %s' % strType, key
168       if "Config" in strType:
169         _saveConfigRecursiveDbg(value, aStream, indentp, path+"."+key)
170         continue
171       if "Mapping" in strType:
172         _saveConfigRecursiveDbg(value, aStream, indentp, path+"."+key)
173         continue
174       if "Sequence" in strType:
175         for i in range(len(value)):
176           _saveConfigRecursiveDbg(value[i], aStream, indentp, path+"."+key+"[%i]" % i)
177         continue
178       if "Expression" in strType:
179         try:
180           evaluate = value.evaluate(config)
181           aStream.write("%s%s.%s : %s --> '%s'\n" % (indstr, path, key, str(value), evaluate))
182         except Exception as e:      
183           aStream.write("%s%s.%s : !!! ERROR: %s !!!\n" % (indstr, path, key, e.message))     
184         continue
185       if "Reference" in strType:
186         try:
187           evaluate = value.resolve(config)
188           aStream.write("%s%s.%s : %s --> '%s'\n" % (indstr, path, key, str(value), evaluate))
189         except Exception as e:  
190           aStream.write("%s%s.%s : !!! ERROR: %s !!!\n" % (indstr, path, key, e.message))     
191         continue
192       if type(value) in [str, bool, int, type(None), unicode]:
193         aStream.write("%s%s.%s : '%s'\n" % (indstr, path, key, str(value)))
194         continue
195       try:
196         aStream.write("!!! TODO fix that %s %s%s.%s : %s\n" % (type(value), indstr, path, key, str(value)))
197       except Exception as e:      
198         aStream.write("%s%s.%s : !!! %s\n" % (indstr, path, key, e.message))