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