Salome HOME
3054ed1f341eeb2154d3280befda32627afe1970
[modules/kernel.git] / bin / parseConfigFile.py
1 # Copyright (C) 2013-2014  CEA/DEN, EDF R&D, OPEN CASCADE
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19
20 import ConfigParser
21 import os
22 import logging
23 import re
24 from io import StringIO
25 import subprocess
26 from salomeContextUtils import SalomeContextException
27
28 logging.basicConfig()
29 logConfigParser = logging.getLogger(__name__)
30
31 ADD_TO_PREFIX = 'ADD_TO_'
32 UNSET_KEYWORD = 'UNSET'
33
34
35 def _expandSystemVariables(key, val):
36   expandedVal = os.path.expandvars(val) # expand environment variables
37   # Search for not expanded variables (i.e. non-existing environment variables)
38   pattern = re.compile('\${ ( [^}]* ) }', re.VERBOSE) # string enclosed in ${ and }
39   expandedVal = pattern.sub(r'', expandedVal) # remove matching patterns
40
41   if not "DLIM8VAR" in key: # special case: DISTENE licence key can contain double clons (::)
42     expandedVal = _trimColons(expandedVal)
43   return expandedVal
44 #
45
46 # :TRICKY: So ugly solution...
47 class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
48   def __init__(self):
49     ConfigParser.SafeConfigParser.__init__(self)
50
51   # copied from python 2.6.8 Lib.ConfigParser.py
52   # modified (see code comments) to handle duplicate keys
53   def _read(self, fp, fpname):
54     """Parse a sectioned setup file.
55
56     The sections in setup file contains a title line at the top,
57     indicated by a name in square brackets (`[]'), plus key/value
58     options lines, indicated by `name: value' format lines.
59     Continuations are represented by an embedded newline then
60     leading whitespace.  Blank lines, lines beginning with a '#',
61     and just about everything else are ignored.
62     """
63     cursect = None                        # None, or a dictionary
64     optname = None
65     lineno = 0
66     e = None                              # None, or an exception
67     while True:
68       line = fp.readline()
69       if not line:
70         break
71       lineno = lineno + 1
72       # comment or blank line?
73       if line.strip() == '' or line[0] in '#;':
74         continue
75       if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
76         # no leading whitespace
77         continue
78       # continuation line?
79       if line[0].isspace() and cursect is not None and optname:
80         value = line.strip()
81         if value:
82           cursect[optname].append(value)
83       # a section header or option header?
84       else:
85         # is it a section header?
86         mo = self.SECTCRE.match(line)
87         if mo:
88           sectname = mo.group('header')
89           if sectname in self._sections:
90             cursect = self._sections[sectname]
91           elif sectname == ConfigParser.DEFAULTSECT:
92             cursect = self._defaults
93           else:
94             cursect = self._dict()
95             cursect['__name__'] = sectname
96             self._sections[sectname] = cursect
97           # So sections can't start with a continuation line
98           optname = None
99         # no section header in the file?
100         elif cursect is None:
101           raise ConfigParser.MissingSectionHeaderError(fpname, lineno, line)
102         # an option line?
103         else:
104           mo = self.OPTCRE.match(line)
105           if mo:
106             optname, vi, optval = mo.group('option', 'vi', 'value')
107             optname = self.optionxform(optname.rstrip())
108             # This check is fine because the OPTCRE cannot
109             # match if it would set optval to None
110             if optval is not None:
111               if vi in ('=', ':') and ';' in optval:
112                 # ';' is a comment delimiter only if it follows
113                 # a spacing character
114                 pos = optval.find(';')
115                 if pos != -1 and optval[pos-1].isspace():
116                   optval = optval[:pos]
117               optval = optval.strip()
118               # ADD THESE LINES
119               splittedComments = optval.split('#')
120               s = _expandSystemVariables(optname, splittedComments[0])
121               optval = s.strip().strip("'").strip('"')
122               #if len(splittedComments) > 1:
123               #  optval += " #" + " ".join(splittedComments[1:])
124               # END OF ADD
125               # allow empty values
126               if optval == '""':
127                 optval = ''
128               # REPLACE following line (original):
129               #cursect[optname] = [optval]
130               # BY THESE LINES:
131               # Check if this optname already exists
132               if (optname in cursect) and (cursect[optname] is not None):
133                 cursect[optname][0] += ','+optval
134               else:
135                 cursect[optname] = [optval]
136               # END OF SUBSITUTION
137             else:
138               # valueless option handling
139               cursect[optname] = optval
140           else:
141             # a non-fatal parsing error occurred.  set up the
142             # exception but keep going. the exception will be
143             # raised at the end of the file and will contain a
144             # list of all bogus lines
145             if not e:
146               e = ConfigParser.ParsingError(fpname)
147             e.append(lineno, repr(line))
148     # if any parsing errors occurred, raise an exception
149     if e:
150       raise e
151
152     # join the multi-line values collected while reading
153     all_sections = [self._defaults]
154     all_sections.extend(self._sections.values())
155     for options in all_sections:
156       for name, val in options.items():
157         if isinstance(val, list):
158           options[name] = '\n'.join(val)
159   #
160
161
162 # Parse configuration file
163 # Input: filename, and a list of reserved keywords (environment variables)
164 # Output: a list of pairs (variable, value), and a dictionary associating a list of user-defined values to each reserved keywords
165 # Note: Does not support duplicate keys in a same section
166 def parseConfigFile(filename, reserved = []):
167   config = MultiOptSafeConfigParser()
168   config.optionxform = str # case sensitive
169
170   # :TODO: test file existence
171
172   # Read config file
173   try:
174     config.read(filename)
175   except ConfigParser.MissingSectionHeaderError:
176     logConfigParser.error("No section found in file: %s"%(filename))
177     return []
178
179   try:
180     return __processConfigFile(config, reserved, filename)
181   except ConfigParser.InterpolationMissingOptionError, e:
182     msg = "A variable may be undefined in SALOME context file: %s\nParser error is: %s\n"%(filename, e)
183     raise SalomeContextException(msg)
184 #
185
186 def __processConfigFile(config, reserved = [], filename="UNKNOWN FILENAME"):
187   # :TODO: may detect duplicated variables in the same section (raise a warning)
188   #        or even duplicate sections
189
190   unsetVariables = []
191   outputVariables = []
192   # Get raw items for each section, and make some processing for environment variables management
193   reservedKeys = [ADD_TO_PREFIX+str(x) for x in reserved] # produce [ 'ADD_TO_reserved_1', 'ADD_TO_reserved_2', ..., ADD_TO_reserved_n ]
194   reservedValues = dict([str(i),[]] for i in reserved) # create a dictionary in which keys are the 'ADD_TO_reserved_i' and associated values are empty lists: { 'reserved_1':[], 'reserved_2':[], ..., reserved_n:[] }
195   sections = config.sections()
196   for section in sections:
197     entries = config.items(section, raw=False) # use interpolation
198     if len(entries) == 0: # empty section
199       logConfigParser.warning("Empty section: %s in file: %s"%(section, filename))
200       pass
201     for key,val in entries:
202       if key in reserved:
203         logConfigParser.error("Invalid use of reserved variable: %s in file: %s"%(key, filename))
204       elif key == UNSET_KEYWORD:
205         unsetVariables += val.replace(',', ' ').split()
206       else:
207         expandedVal = _expandSystemVariables(key, val)
208
209         if key in reservedKeys:
210           shortKey = key[len(ADD_TO_PREFIX):]
211           vals = expandedVal.split(',')
212           reservedValues[shortKey] += vals
213           # remove left&right spaces on each element
214           vals = [v.strip(' \t\n\r') for v in vals]
215         else:
216           outputVariables.append((key, expandedVal))
217           pass
218         pass # end if key
219       pass # end for key,val
220     pass # end for section
221
222   # remove duplicate values
223   outVars = []
224   for (var, values) in outputVariables:
225     vals = values.split(',')
226     vals = list(set(vals))
227     outVars.append((var, ','.join(vals)))
228
229   return unsetVariables, outVars, reservedValues
230 #
231
232 def _trimColons(var):
233   v = var
234   # Remove leading and trailing colons (:)
235   pattern = re.compile('^:+ | :+$', re.VERBOSE)
236   v = pattern.sub(r'', v) # remove matching patterns
237   # Remove multiple colons
238   pattern = re.compile('::+', re.VERBOSE)
239   v = pattern.sub(r':', v) # remove matching patterns
240   return v
241 #
242
243 # This class is used to parse .sh environment file
244 # It deals with specific treatments:
245 #    - virtually add a section to configuration file
246 #    - process shell keywords (if, then...)
247 class EnvFileConverter(object):
248   def __init__(self, fp, section_name, reserved = [], outputFile=None):
249     self.fp = fp
250     self.sechead = '[' + section_name + ']\n'
251     self.reserved = reserved
252     self.outputFile = outputFile
253     self.allParsedVariableNames=[]
254     # exclude line that begin with:
255     self.exclude = [ 'if', 'then', 'else', 'fi', '#', 'echo', 'exit' ]
256     self.exclude.append('$gconfTool') # QUICK FIX :TODO: provide method to extend this variable
257     # discard the following keywords if at the beginning of line:
258     self.discard = [ 'export' ]
259     # the following keywords imply a special processing if at the beginning of line:
260     self.special = [ 'unset' ]
261
262   def readline(self):
263     if self.sechead:
264       try:
265         if self.outputFile is not None:
266           self.outputFile.write(self.sechead)
267         return self.sechead
268       finally:
269         self.sechead = None
270     else:
271       line = self.fp.readline()
272       # trim  whitespaces
273       line = line.strip(' \t\n\r')
274       # line of interest? (not beginning by a keyword of self.exclude)
275       for k in self.exclude:
276         if line.startswith(k):
277           return '\n'
278       # look for substrinsg beginning with sharp charcter ('#')
279       line = re.sub(r'#.*$', r'', line)
280       # line to be pre-processed? (beginning by a keyword of self.special)
281       for k in self.special:
282         if k == "unset" and line.startswith(k):
283           line = line[len(k):]
284           line = line.strip(' \t\n\r')
285           line = UNSET_KEYWORD + ": " + line
286       # line to be pre-processed? (beginning by a keyword of self.discard)
287       for k in self.discard:
288         if line.startswith(k):
289           line = line[len(k):]
290           line = line.strip(' \t\n\r')
291       # process reserved keywords
292       for k in self.reserved:
293         if line.startswith(k) and "=" in line:
294           variable, value = line.split('=')
295           value = self._purgeValue(value, k)
296           line = ADD_TO_PREFIX + k + ": " + value
297       # Update list of variable names
298       # :TODO: define excludeBlock variable (similar to exclude) and provide method to extend it
299       if "cleandup()" in line:
300         print "WARNING: parseConfigFile.py: skip cleandup and look for '# PRODUCT environment'"
301         while True:
302           line = self.fp.readline()
303           if "# PRODUCT environment" in line:
304             print "WARNING: parseConfigFile.py: '# PRODUCT environment' found"
305             break
306       while "clean " in line[0:6]: #skip clean calls with ending ";" crash
307         line = self.fp.readline()
308       # Extract variable=value
309       if "=" in line:
310         try:
311           variable, value = line.split('=')
312         except: #avoid error for complicated sh line xx=`...=...`, but warning
313           print "WARNING: parseConfigFile.py: line with multiples '=' character are hazardous: '"+line+"'"
314           variable, value = line.split('=',1)
315           pass
316
317         # Self-extending variables that are not in reserved keywords
318         # Example: FOO=something:${FOO}
319         # In this case, remove the ${FOO} in value
320         if variable in value:
321           value = self._purgeValue(value, variable)
322           line = "%s=%s"%(variable,value)
323
324         self.allParsedVariableNames.append(variable)
325       # End of extraction
326
327       if not line:
328         return line
329
330       #
331       # replace "${FOO}" and "$FOO" and ${FOO} and $FOO by %(FOO)s if FOO is
332       # defined in current file (i.e. it is not an external environment variable)
333       for k in self.allParsedVariableNames:
334         key = r'\$\{?'+k+'\}?'
335         pattern = re.compile(key, re.VERBOSE)
336         line = pattern.sub(r'%('+k+')s', line)
337         # Remove quotes (if line does not contain whitespaces)
338         try:
339           variable, value = line.split('=', 1)
340         except ValueError:
341           variable, value = line.split(':', 1)
342         if not ' ' in value.strip():
343           pattern = re.compile(r'\"', re.VERBOSE)
344           line = pattern.sub(r'', line)
345       #
346
347       # Replace `shell_command` by its result
348       def myrep(obj):
349         obj = re.sub('`', r'', obj.group(0)) # remove quotes
350         obj = obj.split()
351         res = subprocess.Popen(obj, stdout=subprocess.PIPE).communicate()[0]
352         res = res.strip(' \t\n\r') # trim whitespaces
353         return res
354       #
355       line = re.sub('`[^`]+`', myrep, line)
356       #
357       if self.outputFile is not None:
358         self.outputFile.write(line+'\n')
359       return line
360
361   def _purgeValue(self, value, name):
362     # Replace foo:${PATTERN}:bar or foo:$PATTERN:bar by foo:bar
363     key = r'\$\{?'+name+'\}?'
364     pattern = re.compile(key, re.VERBOSE)
365     value = pattern.sub(r'', value)
366
367     # trim colons
368     value = _trimColons(value)
369
370     return value
371   #
372
373 # Convert .sh environment file to configuration file format
374 def convertEnvFileToConfigFile(envFilename, configFilename, reserved=[]):
375   logConfigParser.debug('convert env file %s to %s'%(envFilename, configFilename))
376   fileContents = open(envFilename, 'r').read()
377
378   pattern = re.compile('\n[\n]+', re.VERBOSE) # multiple '\n'
379   fileContents = pattern.sub(r'\n', fileContents) # replace by a single '\n'
380
381   finput = StringIO(unicode(fileContents))
382   foutput = open(configFilename, 'w')
383
384   config = MultiOptSafeConfigParser()
385   config.optionxform = str # case sensitive
386   config.readfp(EnvFileConverter(finput, 'SALOME Configuration', reserved, outputFile=foutput))
387
388   foutput.close()
389
390   logConfigParser.info('Configuration file generated: %s'%configFilename)
391 #