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