Salome HOME
Add help prints and terminal command mechanism
[tools/sat.git] / src / config.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2012  CEA/DEN
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18
19 import os
20 import sys
21 import common
22 import platform
23 import datetime
24 import glob
25 import re
26 import shutil
27
28 # Define all possible option for config command :  sat config <options>
29 parser = common.options.Options()
30 parser.add_option('v', 'value', 'string', 'value', "print the value of CONFIG_VARIABLE.")
31
32 '''
33 class MergeHandler:
34     def __init__(self):
35         pass
36
37     def __call__(self, map1, map2, key):
38         if '__overwrite__' in map2 and key in map2.__overwrite__:
39             return "overwrite"
40         else:
41             return common.config_pyconf.overwriteMergeResolve(map1, map2, key)
42 '''
43
44 class ConfigOpener:
45     def __init__(self, pathList):
46         self.pathList = pathList
47
48     def __call__(self, name):
49         if os.path.isabs(name):
50             return common.config_pyconf.ConfigInputStream(open(name, 'rb'))
51         else:
52             return common.config_pyconf.ConfigInputStream( open(os.path.join( self.getPath(name), name ), 'rb') )
53         raise IOError(_("Configuration file '%s' not found") % name)
54
55     def getPath( self, name ):
56         for path in self.pathList:
57             if os.path.exists(os.path.join(path, name)):
58                 return path
59         raise IOError(_("Configuration file '%s' not found") % name)
60
61 class ConfigManager:
62     '''Class that manages the read of all the configuration files of salomeTools
63     '''
64     def __init__(self, dataDir=None):
65         pass
66
67     def _create_vars(self, application=None, command=None, dataDir=None):
68         '''Create a dictionary that stores all information about machine, user, date, repositories, etc...
69         :param application str: The application for which salomeTools is called.
70         :param command str: The command that is called.
71         :param dataDir str: The repository that contain external data for salomeTools.
72         :return: The dictionary that stores all information.
73         :rtype: dict
74         '''
75         var = {}      
76         var['user'] = common.architecture.get_user()
77         var['salometoolsway'] = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
78         var['srcDir'] = os.path.join(var['salometoolsway'], 'src')
79         var['sep']= os.path.sep
80         
81         # dataDir has a default location
82         var['dataDir'] = os.path.join(var['salometoolsway'], 'data')
83         if dataDir is not None:
84             var['dataDir'] = dataDir
85
86         var['personalDir'] = os.path.join(os.path.expanduser('~'), '.salomeTools')
87
88         # read linux distributions dictionary
89         distrib_cfg = common.config_pyconf.Config(os.path.join(var['dataDir'], "distrib.pyconf"))
90
91         # set platform parameters
92         dist_name = common.architecture.get_distribution(codes=distrib_cfg.DISTRIBUTIONS)
93         dist_version = common.architecture.get_distrib_version(dist_name, codes=distrib_cfg.VERSIONS)
94         dist = dist_name + dist_version
95         
96         # Forcing architecture with env variable ARCH on Windows
97         if common.architecture.is_windows() and "ARCH" in os.environ :
98             bitsdict={"Win32":"32","Win64":"64"}
99             nb_bits = bitsdict[os.environ["ARCH"]]
100         else :
101             nb_bits = common.architecture.get_nb_bit()
102
103         var['dist_name'] = dist_name
104         var['dist_version'] = dist_version
105         var['dist'] = dist
106         var['arch'] = dist + '_' + nb_bits
107         var['bits'] = nb_bits
108         var['python'] = common.architecture.get_python_version()
109
110         var['nb_proc'] = common.architecture.get_nb_proc()
111         node_name = platform.node()
112         var['node'] = node_name
113         var['hostname'] = node_name
114         # particular win case 
115         if common.architecture.is_windows() :
116             var['hostname'] = node_name+'-'+nb_bits
117
118         # set date parameters
119         dt = datetime.datetime.now()
120         var['date'] = dt.strftime('%Y%m%d')
121         var['datehour'] = dt.strftime('%Y%m%d_%H%M%S')
122         var['hour'] = dt.strftime('%H%M%S')
123
124         var['command'] = str(command)
125         var['application'] = str(application)
126
127         # Root dir for temporary files 
128         var['tmp_root'] = os.sep + 'tmp' + os.sep + var['user']
129         # particular win case 
130         if common.architecture.is_windows() : 
131             var['tmp_root'] =  os.path.expanduser('~') + os.sep + 'tmp'
132         
133         return var
134
135     def get_command_line_overrides(self, options, sections):
136         '''get all the overwrites that are in the command line
137         :param options : TO DO
138         :param sections str: The command that is called.
139         :return: The list of all the overwrites of the command line.
140         :rtype: list
141         '''
142         # when there are no options or not the overwrite option, return an empty list
143         if options is None or options.overwrite is None:
144             return []
145
146         over = []
147         for section in sections:
148             over.extend(filter(lambda l: l.startswith(section + "."), options.overwrite))
149         return over
150
151     def getConfig(self, application=None, options=None, command=None, dataDir=None):
152         '''get the config from all the configuration files.
153         :param application str: The application for which salomeTools is called.
154         :param options TODO
155         :param command str: The command that is called.
156         :param dataDir str: The repository that contain external data for salomeTools.
157         :return: The final config.
158         :rtype: class 'common.config_pyconf.Config'
159         '''        
160         
161         # create a ConfigMerger to handle merge
162         merger = common.config_pyconf.ConfigMerger()#MergeHandler())
163         
164         # create the configuration instance
165         cfg = common.config_pyconf.Config()
166         
167         # =======================================================================================
168         # create VARS section
169         var = self._create_vars(application=application, command=command, dataDir=dataDir)
170         # add VARS to config
171         cfg.VARS = common.config_pyconf.Mapping(cfg)
172         for variable in var:
173             cfg.VARS[variable] = var[variable]
174
175         for rule in self.get_command_line_overrides(options, ["VARS"]):
176             exec('cfg.' + rule) # this cannot be factorized because of the exec
177         
178         # =======================================================================================
179         # Load INTERNAL config
180         # read src/common/internal_config/salomeTools.pyconf
181         common.config_pyconf.streamOpener = ConfigOpener([os.path.join(cfg.VARS.srcDir, 'common', 'internal_config')])
182         try:
183             internal_cfg = common.config_pyconf.Config(open(os.path.join(cfg.VARS.srcDir, 'common', 'internal_config', 'salomeTools.pyconf')))
184         except common.config_pyconf.ConfigError as e:
185             raise common.SatException(_("Error in configuration file: salomeTools.pyconf\n  %(error)s") % \
186                 {'error': str(e) })
187
188         merger.merge(cfg, internal_cfg)
189
190         for rule in self.get_command_line_overrides(options, ["INTERNAL"]):
191             exec('cfg.' + rule) # this cannot be factorized because of the exec        
192         
193         # =======================================================================================
194         # Load SITE config file
195         # search only in the data directory
196         common.config_pyconf.streamOpener = ConfigOpener([cfg.VARS.dataDir])
197         try:
198             site_cfg = common.config_pyconf.Config(open(os.path.join(cfg.VARS.dataDir, 'site.pyconf')))
199         except common.config_pyconf.ConfigError as e:
200             raise common.SatException(_("Error in configuration file: site.pyconf\n  %(error)s") % \
201                 {'error': str(e) })
202         except IOError as error:
203             e = str(error)
204             if "site.pyconf" in e :
205                 e += "\nYou can copy data" + cfg.VARS.sep + "site.template.pyconf to data" + cfg.VARS.sep + "site.pyconf and edit the file"
206             raise common.SatException( e );
207
208         merger.merge(cfg, site_cfg)
209
210         for rule in self.get_command_line_overrides(options, ["SITE"]):
211             exec('cfg.' + rule) # this cannot be factorized because of the exec
212         
213         # =======================================================================================
214         # Load APPLICATION config file
215         if application is not None:
216             # search APPLICATION file in all directories in configPath
217             cp = cfg.SITE.config.configPath
218             common.config_pyconf.streamOpener = ConfigOpener(cp)
219             try:
220                 application_cfg = common.config_pyconf.Config(application + '.pyconf')
221             except IOError as e:
222                 raise common.SatException(_("%s, use 'config --list' to get the list of available applications.") %e)
223             except common.config_pyconf.ConfigError as e:
224                 raise common.SatException(_("Error in configuration file: %(application)s.pyconf\n  %(error)s") % \
225                     { 'application': application, 'error': str(e) } )
226
227             merger.merge(cfg, application_cfg)
228
229             for rule in self.get_command_line_overrides(options, ["APPLICATION"]):
230                 exec('cfg.' + rule) # this cannot be factorized because of the exec
231         
232         # =======================================================================================
233         # load USER config
234         self.setUserConfigFile(cfg)
235         user_cfg_file = self.getUserConfigFile()
236         user_cfg = common.config_pyconf.Config(open(user_cfg_file))
237         merger.merge(cfg, user_cfg)
238
239         for rule in self.get_command_line_overrides(options, ["USER"]):
240             exec('cfg.' + rule) # this cannot be factorize because of the exec
241
242         return cfg
243
244     def setUserConfigFile(self, config):
245         '''Set the user config file name and path.
246         If necessary, build it from another one or create it from scratch.
247         '''
248         if not config:
249             raise common.SatException(_("Error in setUserConfigFile: config is None"))
250         sat_version = config.INTERNAL.sat_version
251         self.config_file_name = 'salomeTools-%s.pyconf'%sat_version
252         self.user_config_file_path = os.path.join(config.VARS.personalDir, self.config_file_name)
253         if not os.path.isfile(self.user_config_file_path):
254             # if pyconf does not exist, 
255             # Make a copy of an existing  salomeTools-<sat_version>.pyconf
256             # or at least a copy of salomeTools.pyconf
257             # If there is no pyconf file at all, create it from scratch 
258             already_exisiting_pyconf_file = self.getAlreadyExistingUserPyconf( config.VARS.personalDir, sat_version )
259             if already_exisiting_pyconf_file:  
260                 # copy
261                 shutil.copyfile( already_exisiting_pyconf_file, self.user_config_file_path )
262                 cfg = common.config_pyconf.Config(open(self.user_config_file_path))
263             else: # create from scratch
264                 self.createConfigFile(config)
265     
266     def getAlreadyExistingUserPyconf(self, dir, sat_version ):
267         '''Get a pyconf file younger than the given sat version in the given directory
268         The file basename can be one of salometools-<younger version>.pyconf or salomeTools.pyconf
269         Returns the file path or None if no file has been found.
270         '''
271         file_path = None  
272         # Get a younger pyconf version   
273         pyconfFiles = glob.glob( os.path.join(dir, 'salomeTools-*.pyconf') )
274         sExpr = "^salomeTools-(.*)\.pyconf$"
275         oExpr = re.compile(sExpr)
276         younger_version = None
277         for s in pyconfFiles:
278             oSreMatch = oExpr.search( os.path.basename(s) )
279             if oSreMatch:
280                 pyconf_version = oSreMatch.group(1)
281                 if pyconf_version < sat_version: 
282                     younger_version = pyconf_version 
283
284         # Build the pyconf filepath
285         if younger_version :   
286             file_path = os.path.join( dir, 'salomeTools-%s.pyconf'%younger_version )
287         elif os.path.isfile( os.path.join(dir, 'salomeTools.pyconf') ):
288             file_path = os.path.join( dir, 'salomeTools.pyconf' )
289         
290         return file_path 
291     
292     def createConfigFile(self, config):
293         
294         cfg_name = self.getUserConfigFile()
295
296         user_cfg = common.config_pyconf.Config()
297         #
298         user_cfg.addMapping('USER', common.config_pyconf.Mapping(user_cfg), "")
299
300         #
301         user_cfg.USER.addMapping('workDir', os.path.expanduser('~'),
302             "This is where salomeTools will work. You may (and probably do) change it.\n")
303         user_cfg.USER.addMapping('cvs_user', config.VARS.user,
304             "This is the user name used to access salome cvs base.\n")
305         user_cfg.USER.addMapping('svn_user', config.VARS.user,
306             "This is the user name used to access salome svn base.\n")
307         user_cfg.USER.addMapping('output_level', 3,
308             "This is the default output_level you want. 0=>no output, 5=>debug.\n")
309         user_cfg.USER.addMapping('publish_dir', os.path.join(os.path.expanduser('~'), 'websupport', 'satreport'), "")
310         user_cfg.USER.addMapping('editor', 'vi', "This is the editor used to modify configuration files\n")
311         user_cfg.USER.addMapping('browser', 'firefox', "This is the browser used to read html documentation\n")
312         user_cfg.USER.addMapping('pdf_viewer', 'evince', "This is the pdf_viewer used to read pdf documentation\n")
313         # 
314         common.ensure_path_exists(config.VARS.personalDir)
315         common.ensure_path_exists(os.path.join(config.VARS.personalDir, 'Applications'))
316
317         f = open(cfg_name, 'w')
318         user_cfg.__save__(f)
319         f.close()
320         print(_("You can edit it to configure salomeTools (use: sat config --edit).\n"))
321
322         return user_cfg   
323
324     def getUserConfigFile(self):
325         '''Get the user config file
326         '''
327         if not self.user_config_file_path:
328             raise common.SatException(_("Error in getUserConfigFile: missing user config file path"))
329         return self.user_config_file_path     
330         
331     
332 def print_value(config, path, show_label, level=0, show_full_path=False):
333     '''Prints a value from the configuration. Prints recursively the values under the initial path.
334     :param config class 'common.config_pyconf.Config': The configuration from which the value is displayed.
335     :param path str : the path in the configuration of the value to print.
336     :param show_label boolean: if True, do a basic display. (useful for bash completion)
337     :param level int: The number of spaces to add before display.
338     :param show_full_path :
339     :return: The final config.
340     :rtype: class 'common.config_pyconf.Config'
341     '''            
342     
343     # display all the path or not
344     if show_full_path:
345         vname = path
346     else:
347         vname = path.split('.')[-1]
348
349     # number of spaces before the display
350     tab_level = "  " * level
351     
352     # call to the function that gets the value of the path.
353     try:
354         val = config.getByPath(path)
355     except Exception as e:
356         sys.stdout.write(tab_level)
357         sys.stdout.write("%s: ERROR %s\n" % (common.printcolors.printcLabel(vname), common.printcolors.printcError(str(e))))
358         return
359
360     # in this case, display only the value
361     if show_label:
362         sys.stdout.write(tab_level)
363         sys.stdout.write("%s: " % common.printcolors.printcLabel(vname))
364
365     # The case where the value has under values, do a recursive call to the function
366     if dir(val).__contains__('keys'):
367         if show_label: sys.stdout.write("\n")
368         for v in sorted(val.keys()):
369             print_value(config, path + '.' + v, show_label, level + 1)
370     elif val.__class__ == common.config_pyconf.Sequence or isinstance(val, list): # in this case, value is a list (or a Sequence)
371         if show_label: sys.stdout.write("\n")
372         index = 0
373         for v in val:
374             print_value(config, path + "[" + str(index) + "]", show_label, level + 1)
375             index = index + 1
376     else: # case where val is just a str
377         sys.stdout.write("%s\n" % val)
378
379 def description():
380     return _("The config command allows manipulation and operation on config files.")
381     
382
383 def run(args, runner):
384     (options, args) = parser.parse_args(args)
385     print('Je suis dans la commande config ! Bien jouĂ© ! COUCOU')
386     if options.value:
387         print_value(runner.cfg, options.value, True, level=0, show_full_path=False)
388