Salome HOME
a3bc109e4c3bf3d9a3187987bb366f8663b860aa
[tools/sat.git] / commands / 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 platform
21 import datetime
22 import shutil
23 import gettext
24
25 import src
26
27 # internationalization
28 satdir  = os.path.dirname(os.path.realpath(__file__))
29 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
30
31 # Define all possible option for config command :  sat config <options>
32 parser = src.options.Options()
33 parser.add_option('v', 'value', 'string', 'value',
34                    _("print the value of CONFIG_VARIABLE."))
35 parser.add_option('e', 'edit', 'boolean', 'edit',
36                    _("edit the product configuration file."))
37 parser.add_option('l', 'list', 'boolean', 'list',
38                   _("list all available applications."))
39 parser.add_option('c', 'copy', 'boolean', 'copy',
40     _("""copy a config file to the personnal config files directory.
41 \tWARNING the included files are not copied.
42 \tIf a name is given the new config file takes the given name."""))
43
44 class ConfigOpener:
45     '''Class that helps to find an application pyconf 
46        in all the possible directories (pathList)
47     '''
48     def __init__(self, pathList):
49         '''Initialization
50         
51         :param pathList list: The list of paths where to serach a pyconf.
52         '''
53         self.pathList = pathList
54
55     def __call__(self, name):
56         if os.path.isabs(name):
57             return src.pyconf.ConfigInputStream(open(name, 'rb'))
58         else:
59             return src.pyconf.ConfigInputStream( 
60                         open(os.path.join( self.get_path(name), name ), 'rb') )
61         raise IOError(_("Configuration file '%s' not found") % name)
62
63     def get_path( self, name ):
64         '''The method that returns the entire path of the pyconf searched
65         :param name str: The name of the searched pyconf.
66         '''
67         for path in self.pathList:
68             if os.path.exists(os.path.join(path, name)):
69                 return path
70         raise IOError(_("Configuration file '%s' not found") % name)
71
72 class ConfigManager:
73     '''Class that manages the read of all the configuration files of salomeTools
74     '''
75     def __init__(self, dataDir=None):
76         pass
77
78     def _create_vars(self, application=None, command=None, dataDir=None):
79         '''Create a dictionary that stores all information about machine,
80            user, date, repositories, etc...
81         
82         :param application str: The application for which salomeTools is called.
83         :param command str: The command that is called.
84         :param dataDir str: The repository that contain external data 
85                             for salomeTools.
86         :return: The dictionary that stores all information.
87         :rtype: dict
88         '''
89         var = {}      
90         var['user'] = src.architecture.get_user()
91         var['salometoolsway'] = os.path.dirname(
92                                     os.path.dirname(os.path.abspath(__file__)))
93         var['srcDir'] = os.path.join(var['salometoolsway'], 'src')
94         var['sep']= os.path.sep
95         
96         # dataDir has a default location
97         var['dataDir'] = os.path.join(var['salometoolsway'], 'data')
98         if dataDir is not None:
99             var['dataDir'] = dataDir
100
101         var['personalDir'] = os.path.join(os.path.expanduser('~'),
102                                            '.salomeTools')
103
104         # read linux distributions dictionary
105         distrib_cfg = src.pyconf.Config(os.path.join(var['srcDir'],
106                                                       'internal_config',
107                                                       'distrib.pyconf'))
108         
109         # set platform parameters
110         dist_name = src.architecture.get_distribution(
111                                             codes=distrib_cfg.DISTRIBUTIONS)
112         dist_version = src.architecture.get_distrib_version(dist_name, 
113                                                     codes=distrib_cfg.VERSIONS)
114         dist = dist_name + dist_version
115         
116         var['dist_name'] = dist_name
117         var['dist_version'] = dist_version
118         var['dist'] = dist
119         var['python'] = src.architecture.get_python_version()
120
121         var['nb_proc'] = src.architecture.get_nb_proc()
122         node_name = platform.node()
123         var['node'] = node_name
124         var['hostname'] = node_name
125
126         # set date parameters
127         dt = datetime.datetime.now()
128         var['date'] = dt.strftime('%Y%m%d')
129         var['datehour'] = dt.strftime('%Y%m%d_%H%M%S')
130         var['hour'] = dt.strftime('%H%M%S')
131
132         var['command'] = str(command)
133         var['application'] = str(application)
134
135         # Root dir for temporary files 
136         var['tmp_root'] = os.sep + 'tmp' + os.sep + var['user']
137         # particular win case 
138         if src.architecture.is_windows() : 
139             var['tmp_root'] =  os.path.expanduser('~') + os.sep + 'tmp'
140         
141         return var
142
143     def get_command_line_overrides(self, options, sections):
144         '''get all the overwrites that are in the command line
145         
146         :param options: the options from salomeTools class 
147                         initialization (like -l5 or --overwrite)
148         :param sections str: The config section to overwrite.
149         :return: The list of all the overwrites to apply.
150         :rtype: list
151         '''
152         # when there are no options or not the overwrite option, 
153         # return an empty list
154         if options is None or options.overwrite is None:
155             return []
156         
157         over = []
158         for section in sections:
159             # only overwrite the sections that correspond to the option 
160             over.extend(filter(lambda l: l.startswith(section + "."), 
161                                options.overwrite))
162         return over
163
164     def get_config(self, application=None, options=None, command=None,
165                     dataDir=None):
166         '''get the config from all the configuration files.
167         
168         :param application str: The application for which salomeTools is called.
169         :param options class Options: The general salomeToos
170                                       options (--overwrite or -l5, for example)
171         :param command str: The command that is called.
172         :param dataDir str: The repository that contain 
173                             external data for salomeTools.
174         :return: The final config.
175         :rtype: class 'src.pyconf.Config'
176         '''        
177         
178         # create a ConfigMerger to handle merge
179         merger = src.pyconf.ConfigMerger()#MergeHandler())
180         
181         # create the configuration instance
182         cfg = src.pyconf.Config()
183         
184         # =====================================================================
185         # create VARS section
186         var = self._create_vars(application=application, command=command, 
187                                 dataDir=dataDir)
188         # add VARS to config
189         cfg.VARS = src.pyconf.Mapping(cfg)
190         for variable in var:
191             cfg.VARS[variable] = var[variable]
192         
193         # apply overwrite from command line if needed
194         for rule in self.get_command_line_overrides(options, ["VARS"]):
195             exec('cfg.' + rule) # this cannot be factorized because of the exec
196         
197         # =====================================================================
198         # Load INTERNAL config
199         # read src/internal_config/salomeTools.pyconf
200         src.pyconf.streamOpener = ConfigOpener([
201                             os.path.join(cfg.VARS.srcDir, 'internal_config')])
202         try:
203             internal_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.srcDir, 
204                                     'internal_config', 'salomeTools.pyconf')))
205         except src.pyconf.ConfigError as e:
206             raise src.SatException(_("Error in configuration file:"
207                                      " salomeTools.pyconf\n  %(error)s") % \
208                                    {'error': str(e) })
209         
210         merger.merge(cfg, internal_cfg)
211
212         # apply overwrite from command line if needed
213         for rule in self.get_command_line_overrides(options, ["INTERNAL"]):
214             exec('cfg.' + rule) # this cannot be factorized because of the exec        
215         
216         # =====================================================================
217         # Load SITE config file
218         # search only in the data directory
219         src.pyconf.streamOpener = ConfigOpener([cfg.VARS.dataDir])
220         try:
221             site_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.dataDir, 
222                                                            'site.pyconf')))
223         except src.pyconf.ConfigError as e:
224             raise src.SatException(_("Error in configuration file: "
225                                      "site.pyconf\n  %(error)s") % \
226                 {'error': str(e) })
227         except IOError as error:
228             e = str(error)
229             if "site.pyconf" in e :
230                 e += ("\nYou can copy data"
231                   + cfg.VARS.sep
232                   + "site.template.pyconf to data"
233                   + cfg.VARS.sep 
234                   + "site.pyconf and edit the file")
235             raise src.SatException( e );
236         
237         # add user local path for configPath
238         site_cfg.SITE.config.configPath.append(
239                         os.path.join(cfg.VARS.personalDir, 'Applications'), 
240                         "User applications path")
241         
242         merger.merge(cfg, site_cfg)
243
244         # apply overwrite from command line if needed
245         for rule in self.get_command_line_overrides(options, ["SITE"]):
246             exec('cfg.' + rule) # this cannot be factorized because of the exec
247   
248         
249         # =====================================================================
250         # Load APPLICATION config file
251         if application is not None:
252             # search APPLICATION file in all directories in configPath
253             cp = cfg.SITE.config.configPath
254             src.pyconf.streamOpener = ConfigOpener(cp)
255             try:
256                 application_cfg = src.pyconf.Config(application + '.pyconf')
257             except IOError as e:
258                 raise src.SatException(_("%s, use 'config --list' to get the"
259                                          " list of available applications.") %e)
260             except src.pyconf.ConfigError as e:
261                 raise src.SatException(_("Error in configuration file:"
262                                 " %(application)s.pyconf\n  %(error)s") % \
263                     { 'application': application, 'error': str(e) } )
264
265             merger.merge(cfg, application_cfg)
266
267             # apply overwrite from command line if needed
268             for rule in self.get_command_line_overrides(options,
269                                                          ["APPLICATION"]):
270                 # this cannot be factorized because of the exec
271                 exec('cfg.' + rule) 
272         
273         # =====================================================================
274         # Load softwares config files in SOFTWARE section
275        
276         # The directory containing the softwares definition
277         softsDir = os.path.join(cfg.VARS.dataDir, 'softwares')
278         
279         # Loop on all files that are in softsDir directory 
280         # and read their config
281         for fName in os.listdir(softsDir):
282             if fName.endswith(".pyconf"):
283                 src.pyconf.streamOpener = ConfigOpener([softsDir])
284                 try:
285                     soft_cfg = src.pyconf.Config(open(
286                                                 os.path.join(softsDir, fName)))
287                 except src.pyconf.ConfigError as e:
288                     raise src.SatException(_(
289                         "Error in configuration file: %(soft)s\n  %(error)s") % \
290                         {'soft' :  fName, 'error': str(e) })
291                 except IOError as error:
292                     e = str(error)
293                     raise src.SatException( e );
294                 
295                 merger.merge(cfg, soft_cfg)
296
297         # apply overwrite from command line if needed
298         for rule in self.get_command_line_overrides(options, ["SOFTWARE"]):
299             exec('cfg.' + rule) # this cannot be factorized because of the exec
300
301         
302         # =====================================================================
303         # load USER config
304         self.set_user_config_file(cfg)
305         user_cfg_file = self.get_user_config_file()
306         user_cfg = src.pyconf.Config(open(user_cfg_file))
307         merger.merge(cfg, user_cfg)
308
309         # apply overwrite from command line if needed
310         for rule in self.get_command_line_overrides(options, ["USER"]):
311             exec('cfg.' + rule) # this cannot be factorize because of the exec
312
313         return cfg
314
315     def set_user_config_file(self, config):
316         '''Set the user config file name and path.
317         If necessary, build it from another one or create it from scratch.
318         
319         :param config class 'src.pyconf.Config': The global config 
320                                                  (containing all pyconf).
321         '''
322         # get the expected name and path of the file
323         self.config_file_name = 'salomeTools.pyconf'
324         self.user_config_file_path = os.path.join(config.VARS.personalDir,
325                                                    self.config_file_name)
326         
327         # if pyconf does not exist, create it from scratch
328         if not os.path.isfile(self.user_config_file_path): 
329             self.create_config_file(config)
330     
331     def create_config_file(self, config):
332         '''This method is called when there are no user config file. 
333            It build it from scratch.
334         
335         :param config class 'src.pyconf.Config': The global config.
336         :return: the config corresponding to the file created.
337         :rtype: config class 'src.pyconf.Config'
338         '''
339         
340         cfg_name = self.get_user_config_file()
341
342         user_cfg = src.pyconf.Config()
343         #
344         user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
345
346         #
347         user_cfg.USER.addMapping('workDir', os.path.expanduser('~'),
348             "This is where salomeTools will work. "
349             "You may (and probably do) change it.\n")
350         user_cfg.USER.addMapping('cvs_user', config.VARS.user,
351             "This is the user name used to access salome cvs base.\n")
352         user_cfg.USER.addMapping('svn_user', config.VARS.user,
353             "This is the user name used to access salome svn base.\n")
354         user_cfg.USER.addMapping('output_level', 3,
355             "This is the default output_level you want."
356             " 0=>no output, 5=>debug.\n")
357         user_cfg.USER.addMapping('publish_dir', 
358                                  os.path.join(os.path.expanduser('~'),
359                                  'websupport', 
360                                  'satreport'), 
361                                  "")
362         user_cfg.USER.addMapping('editor',
363                                  'vi', 
364                                  "This is the editor used to "
365                                  "modify configuration files\n")
366         user_cfg.USER.addMapping('browser', 
367                                  'firefox', 
368                                  "This is the browser used to "
369                                  "read html documentation\n")
370         user_cfg.USER.addMapping('pdf_viewer', 
371                                  'evince', 
372                                  "This is the pdf_viewer used "
373                                  "to read pdf documentation\n")
374         # 
375         src.ensure_path_exists(config.VARS.personalDir)
376         src.ensure_path_exists(os.path.join(config.VARS.personalDir, 
377                                             'Applications'))
378
379         f = open(cfg_name, 'w')
380         user_cfg.__save__(f)
381         f.close()
382         print(_("You can edit it to configure salomeTools "
383                 "(use: sat config --edit).\n"))
384
385         return user_cfg   
386
387     def get_user_config_file(self):
388         '''Get the user config file
389         :return: path to the user config file.
390         :rtype: str
391         '''
392         if not self.user_config_file_path:
393             raise src.SatException(_("Error in get_user_config_file: "
394                                      "missing user config file path"))
395         return self.user_config_file_path     
396         
397     
398 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
399     '''Prints a value from the configuration. Prints recursively the values 
400        under the initial path.
401     
402     :param config class 'src.pyconf.Config': The configuration 
403                                              from which the value is displayed.
404     :param path str : the path in the configuration of the value to print.
405     :param show_label boolean: if True, do a basic display. 
406                                (useful for bash completion)
407     :param logger Logger: the logger instance
408     :param level int: The number of spaces to add before display.
409     :param show_full_path :
410     '''            
411     
412     # display all the path or not
413     if show_full_path:
414         vname = path
415     else:
416         vname = path.split('.')[-1]
417
418     # number of spaces before the display
419     tab_level = "  " * level
420     
421     # call to the function that gets the value of the path.
422     try:
423         val = config.getByPath(path)
424     except Exception as e:
425         logger.write(tab_level)
426         logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname), 
427                                          src.printcolors.printcError(str(e))))
428         return
429
430     # in this case, display only the value
431     if show_label:
432         logger.write(tab_level)
433         logger.write("%s: " % src.printcolors.printcLabel(vname))
434
435     # The case where the value has under values, 
436     # do a recursive call to the function
437     if dir(val).__contains__('keys'):
438         if show_label: logger.write("\n")
439         for v in sorted(val.keys()):
440             print_value(config, path + '.' + v, show_label, logger, level + 1)
441     elif val.__class__ == src.pyconf.Sequence or isinstance(val, list): 
442         # in this case, value is a list (or a Sequence)
443         if show_label: logger.write("\n")
444         index = 0
445         for v in val:
446             print_value(config, path + "[" + str(index) + "]", 
447                         show_label, logger, level + 1)
448             index = index + 1
449     else: # case where val is just a str
450         logger.write("%s\n" % val)
451
452 def description():
453     '''method that is called when salomeTools is called with --help option.
454     
455     :return: The text to display for the config command description.
456     :rtype: str
457     '''
458     return _("The config command allows manipulation "
459              "and operation on config files.")
460     
461
462 def run(args, runner, logger):
463     '''method that is called when salomeTools is called with config parameter.
464     '''
465     # Parse the options
466     (options, args) = parser.parse_args(args)
467     
468     # case : print a value of the config
469     if options.value:
470         if options.value == ".":
471             # if argument is ".", print all the config
472             for val in sorted(runner.cfg.keys()):
473                 print_value(runner.cfg, val, True, logger)
474         else:
475             print_value(runner.cfg, options.value, True, logger, 
476                         level=0, show_full_path=False)
477     
478     # case : edit user pyconf file or application file
479     elif options.edit:
480         editor = runner.cfg.USER.editor
481         if 'APPLICATION' not in runner.cfg: # edit user pyconf
482             usercfg = os.path.join(runner.cfg.VARS.personalDir, 
483                                    'salomeTools.pyconf')
484             src.system.show_in_editor(editor, usercfg, logger)
485         else:
486             # search for file <application>.pyconf and open it
487             for path in runner.cfg.SITE.config.configPath:
488                 pyconf_path = os.path.join(path, 
489                                     runner.cfg.VARS.application + ".pyconf")
490                 if os.path.exists(pyconf_path):
491                     src.system.show_in_editor(editor, pyconf_path, logger)
492                     break
493     
494     # case : copy an existing <application>.pyconf 
495     # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
496     elif options.copy:
497         # product is required
498         src.check_config_has_application( runner.cfg )
499
500         # get application file path 
501         source = runner.cfg.VARS.application + '.pyconf'
502         source_full_path = ""
503         for path in runner.cfg.SITE.config.configPath:
504             # ignore personal directory
505             if path == runner.cfg.VARS.personalDir:
506                 continue
507             # loop on all directories that can have pyconf applications
508             zz = os.path.join(path, source)
509             if os.path.exists(zz):
510                 source_full_path = zz
511                 break
512
513         if len(source_full_path) == 0:
514             raise src.SatException(_(
515                         "Config file for product %s not found\n") % source)
516         else:
517             if len(args) > 0:
518                 # a name is given as parameter, use it
519                 dest = args[0]
520             elif 'copy_prefix' in runner.cfg.SITE.config:
521                 # use prefix
522                 dest = (runner.cfg.SITE.config.copy_prefix 
523                         + runner.cfg.VARS.application)
524             else:
525                 # use same name as source
526                 dest = runner.cfg.VARS.application
527                 
528             # the full path
529             dest_file = os.path.join(runner.cfg.VARS.personalDir, 
530                                      'Applications', dest + '.pyconf')
531             if os.path.exists(dest_file):
532                 raise src.SatException(_("A personal application"
533                                          " '%s' already exists") % dest)
534             
535             # perform the copy
536             shutil.copyfile(source_full_path, dest_file)
537             logger.write(_("%s has been created.\n") % dest_file)
538     
539     # case : display all the available pyconf applications
540     elif options.list:
541         lproduct = list()
542         # search in all directories that can have pyconf applications
543         for path in runner.cfg.SITE.config.configPath:
544             # print a header
545             logger.write("------ %s\n" % src.printcolors.printcHeader(path))
546
547             if not os.path.exists(path):
548                 logger.write(src.printcolors.printcError(_(
549                                             "Directory not found")) + "\n")
550             else:
551                 for f in sorted(os.listdir(path)):
552                     # ignore file that does not ends with .pyconf
553                     if not f.endswith('.pyconf'):
554                         continue
555
556                     appliname = f[:-len('.pyconf')]
557                     if appliname not in lproduct:
558                         lproduct.append(appliname)
559                         if path.startswith(runner.cfg.VARS.personalDir):
560                             logger.write("%s*\n" % appliname)
561                         else:
562                             logger.write("%s\n" % appliname)
563                             
564             logger.write("\n")
565     
566