]> SALOME platform Git repositories - tools/sat.git/blob - commands/config.py
Salome HOME
c4942122c99b9d65419ddb6eb2683b164e1cce5a
[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         # 
389         src.ensure_path_exists(config.VARS.personalDir)
390         src.ensure_path_exists(os.path.join(config.VARS.personalDir, 
391                                             'Applications'))
392
393         f = open(cfg_name, 'w')
394         user_cfg.__save__(f)
395         f.close()
396         print(_("You can edit it to configure salomeTools "
397                 "(use: sat config --edit).\n"))
398
399         return user_cfg   
400
401     def get_user_config_file(self):
402         '''Get the user config file
403         :return: path to the user config file.
404         :rtype: str
405         '''
406         if not self.user_config_file_path:
407             raise src.SatException(_("Error in get_user_config_file: "
408                                      "missing user config file path"))
409         return self.user_config_file_path     
410         
411     
412 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
413     '''Prints a value from the configuration. Prints recursively the values 
414        under the initial path.
415     
416     :param config class 'src.pyconf.Config': The configuration 
417                                              from which the value is displayed.
418     :param path str : the path in the configuration of the value to print.
419     :param show_label boolean: if True, do a basic display. 
420                                (useful for bash completion)
421     :param logger Logger: the logger instance
422     :param level int: The number of spaces to add before display.
423     :param show_full_path :
424     '''            
425     
426     # Make sure that the path does not ends with a point
427     if path.endswith('.'):
428         path = path[:-1]
429     
430     # display all the path or not
431     if show_full_path:
432         vname = path
433     else:
434         vname = path.split('.')[-1]
435
436     # number of spaces before the display
437     tab_level = "  " * level
438     
439     # call to the function that gets the value of the path.
440     try:
441         val = config.getByPath(path)
442     except Exception as e:
443         logger.write(tab_level)
444         logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname), 
445                                          src.printcolors.printcError(str(e))))
446         return
447
448     # in this case, display only the value
449     if show_label:
450         logger.write(tab_level)
451         logger.write("%s: " % src.printcolors.printcLabel(vname))
452
453     # The case where the value has under values, 
454     # do a recursive call to the function
455     if dir(val).__contains__('keys'):
456         if show_label: logger.write("\n")
457         for v in sorted(val.keys()):
458             print_value(config, path + '.' + v, show_label, logger, level + 1)
459     elif val.__class__ == src.pyconf.Sequence or isinstance(val, list): 
460         # in this case, value is a list (or a Sequence)
461         if show_label: logger.write("\n")
462         index = 0
463         for v in val:
464             print_value(config, path + "[" + str(index) + "]", 
465                         show_label, logger, level + 1)
466             index = index + 1
467     else: # case where val is just a str
468         logger.write("%s\n" % val)
469
470 def get_config_children(config, args):
471     '''Gets the names of the children of the given parameter.
472        Useful only for completion mechanism
473     
474     :param config Config: The configuration where to read the values
475     :param args: The path in the config from which get the keys
476     '''
477     vals = []
478     rootkeys = config.keys()
479     
480     if len(args) == 0:
481         # no parameter returns list of root keys
482         vals = rootkeys
483     else:
484         parent = args[0]
485         pos = parent.rfind('.')
486         if pos < 0:
487             # Case where there is only on key as parameter.
488             # For example VARS
489             vals = [m for m in rootkeys if m.startswith(parent)]
490         else:
491             # Case where there is a part from a key
492             # for example VARS.us  (for VARS.user)
493             head = parent[0:pos]
494             tail = parent[pos+1:]
495             try:
496                 a = config.getByPath(head)
497                 if dir(a).__contains__('keys'):
498                     vals = map(lambda x: head + '.' + x,
499                                [m for m in a.keys() if m.startswith(tail)])
500             except:
501                 pass
502
503     for v in sorted(vals):
504         sys.stdout.write("%s\n" % v)
505
506 def description():
507     '''method that is called when salomeTools is called with --help option.
508     
509     :return: The text to display for the config command description.
510     :rtype: str
511     '''
512     return _("The config command allows manipulation "
513              "and operation on config files.")
514     
515
516 def run(args, runner, logger):
517     '''method that is called when salomeTools is called with config parameter.
518     '''
519     # Parse the options
520     (options, args) = parser.parse_args(args)
521
522     # Only useful for completion mechanism : print the keys of the config
523     if options.schema:
524         get_config_children(runner.cfg, args)
525         return
526     
527     # case : print a value of the config
528     if options.value:
529         if options.value == ".":
530             # if argument is ".", print all the config
531             for val in sorted(runner.cfg.keys()):
532                 print_value(runner.cfg, val, not options.no_label, logger)
533         else:
534             print_value(runner.cfg, options.value, not options.no_label, logger, 
535                         level=0, show_full_path=False)
536     
537     # case : edit user pyconf file or application file
538     elif options.edit:
539         editor = runner.cfg.USER.editor
540         if 'APPLICATION' not in runner.cfg: # edit user pyconf
541             usercfg = os.path.join(runner.cfg.VARS.personalDir, 
542                                    'salomeTools.pyconf')
543             src.system.show_in_editor(editor, usercfg, logger)
544         else:
545             # search for file <application>.pyconf and open it
546             for path in runner.cfg.SITE.config.config_path:
547                 pyconf_path = os.path.join(path, 
548                                     runner.cfg.VARS.application + ".pyconf")
549                 if os.path.exists(pyconf_path):
550                     src.system.show_in_editor(editor, pyconf_path, logger)
551                     break
552     
553     # case : copy an existing <application>.pyconf 
554     # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
555     elif options.copy:
556         # product is required
557         src.check_config_has_application( runner.cfg )
558
559         # get application file path 
560         source = runner.cfg.VARS.application + '.pyconf'
561         source_full_path = ""
562         for path in runner.cfg.SITE.config.config_path:
563             # ignore personal directory
564             if path == runner.cfg.VARS.personalDir:
565                 continue
566             # loop on all directories that can have pyconf applications
567             zz = os.path.join(path, source)
568             if os.path.exists(zz):
569                 source_full_path = zz
570                 break
571
572         if len(source_full_path) == 0:
573             raise src.SatException(_(
574                         "Config file for product %s not found\n") % source)
575         else:
576             if len(args) > 0:
577                 # a name is given as parameter, use it
578                 dest = args[0]
579             elif 'copy_prefix' in runner.cfg.SITE.config:
580                 # use prefix
581                 dest = (runner.cfg.SITE.config.copy_prefix 
582                         + runner.cfg.VARS.application)
583             else:
584                 # use same name as source
585                 dest = runner.cfg.VARS.application
586                 
587             # the full path
588             dest_file = os.path.join(runner.cfg.VARS.personalDir, 
589                                      'Applications', dest + '.pyconf')
590             if os.path.exists(dest_file):
591                 raise src.SatException(_("A personal application"
592                                          " '%s' already exists") % dest)
593             
594             # perform the copy
595             shutil.copyfile(source_full_path, dest_file)
596             logger.write(_("%s has been created.\n") % dest_file)
597     
598     # case : display all the available pyconf applications
599     elif options.list:
600         lproduct = list()
601         # search in all directories that can have pyconf applications
602         for path in runner.cfg.SITE.config.config_path:
603             # print a header
604             if not options.no_label:
605                 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
606
607             if not os.path.exists(path):
608                 logger.write(src.printcolors.printcError(_(
609                                             "Directory not found")) + "\n")
610             else:
611                 for f in sorted(os.listdir(path)):
612                     # ignore file that does not ends with .pyconf
613                     if not f.endswith('.pyconf'):
614                         continue
615
616                     appliname = f[:-len('.pyconf')]
617                     if appliname not in lproduct:
618                         lproduct.append(appliname)
619                         if path.startswith(runner.cfg.VARS.personalDir) \
620                                     and not options.no_label:
621                             logger.write("%s*\n" % appliname)
622                         else:
623                             logger.write("%s\n" % appliname)
624                             
625             logger.write("\n")
626     
627