Salome HOME
Add completion mechanism
[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         # =====================================================================
279         # Load softwares config files in SOFTWARE section
280        
281         # The directory containing the softwares definition
282         softsDir = os.path.join(cfg.VARS.dataDir, 'softwares')
283         
284         # Loop on all files that are in softsDir directory 
285         # and read their config
286         for fName in os.listdir(softsDir):
287             if fName.endswith(".pyconf"):
288                 src.pyconf.streamOpener = ConfigOpener([softsDir])
289                 try:
290                     soft_cfg = src.pyconf.Config(open(
291                                                 os.path.join(softsDir, fName)))
292                 except src.pyconf.ConfigError as e:
293                     raise src.SatException(_(
294                         "Error in configuration file: %(soft)s\n  %(error)s") % \
295                         {'soft' :  fName, 'error': str(e) })
296                 except IOError as error:
297                     e = str(error)
298                     raise src.SatException( e );
299                 
300                 merger.merge(cfg, soft_cfg)
301
302         # apply overwrite from command line if needed
303         for rule in self.get_command_line_overrides(options, ["SOFTWARE"]):
304             exec('cfg.' + rule) # this cannot be factorized because of the exec
305
306         
307         # =====================================================================
308         # load USER config
309         self.set_user_config_file(cfg)
310         user_cfg_file = self.get_user_config_file()
311         user_cfg = src.pyconf.Config(open(user_cfg_file))
312         merger.merge(cfg, user_cfg)
313
314         # apply overwrite from command line if needed
315         for rule in self.get_command_line_overrides(options, ["USER"]):
316             exec('cfg.' + rule) # this cannot be factorize because of the exec
317
318         return cfg
319
320     def set_user_config_file(self, config):
321         '''Set the user config file name and path.
322         If necessary, build it from another one or create it from scratch.
323         
324         :param config class 'src.pyconf.Config': The global config 
325                                                  (containing all pyconf).
326         '''
327         # get the expected name and path of the file
328         self.config_file_name = 'salomeTools.pyconf'
329         self.user_config_file_path = os.path.join(config.VARS.personalDir,
330                                                    self.config_file_name)
331         
332         # if pyconf does not exist, create it from scratch
333         if not os.path.isfile(self.user_config_file_path): 
334             self.create_config_file(config)
335     
336     def create_config_file(self, config):
337         '''This method is called when there are no user config file. 
338            It build it from scratch.
339         
340         :param config class 'src.pyconf.Config': The global config.
341         :return: the config corresponding to the file created.
342         :rtype: config class 'src.pyconf.Config'
343         '''
344         
345         cfg_name = self.get_user_config_file()
346
347         user_cfg = src.pyconf.Config()
348         #
349         user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
350
351         #
352         user_cfg.USER.addMapping('workDir', os.path.expanduser('~'),
353             "This is where salomeTools will work. "
354             "You may (and probably do) change it.\n")
355         user_cfg.USER.addMapping('cvs_user', config.VARS.user,
356             "This is the user name used to access salome cvs base.\n")
357         user_cfg.USER.addMapping('svn_user', config.VARS.user,
358             "This is the user name used to access salome svn base.\n")
359         user_cfg.USER.addMapping('output_level', 3,
360             "This is the default output_level you want."
361             " 0=>no output, 5=>debug.\n")
362         user_cfg.USER.addMapping('publish_dir', 
363                                  os.path.join(os.path.expanduser('~'),
364                                  'websupport', 
365                                  'satreport'), 
366                                  "")
367         user_cfg.USER.addMapping('editor',
368                                  'vi', 
369                                  "This is the editor used to "
370                                  "modify configuration files\n")
371         user_cfg.USER.addMapping('browser', 
372                                  'firefox', 
373                                  "This is the browser used to "
374                                  "read html documentation\n")
375         user_cfg.USER.addMapping('pdf_viewer', 
376                                  'evince', 
377                                  "This is the pdf_viewer used "
378                                  "to read pdf documentation\n")
379         # 
380         src.ensure_path_exists(config.VARS.personalDir)
381         src.ensure_path_exists(os.path.join(config.VARS.personalDir, 
382                                             'Applications'))
383
384         f = open(cfg_name, 'w')
385         user_cfg.__save__(f)
386         f.close()
387         print(_("You can edit it to configure salomeTools "
388                 "(use: sat config --edit).\n"))
389
390         return user_cfg   
391
392     def get_user_config_file(self):
393         '''Get the user config file
394         :return: path to the user config file.
395         :rtype: str
396         '''
397         if not self.user_config_file_path:
398             raise src.SatException(_("Error in get_user_config_file: "
399                                      "missing user config file path"))
400         return self.user_config_file_path     
401         
402     
403 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
404     '''Prints a value from the configuration. Prints recursively the values 
405        under the initial path.
406     
407     :param config class 'src.pyconf.Config': The configuration 
408                                              from which the value is displayed.
409     :param path str : the path in the configuration of the value to print.
410     :param show_label boolean: if True, do a basic display. 
411                                (useful for bash completion)
412     :param logger Logger: the logger instance
413     :param level int: The number of spaces to add before display.
414     :param show_full_path :
415     '''            
416     
417     # Make sure that the path does not ends with a point
418     if path.endswith('.'):
419         path = path[:-1]
420     
421     # display all the path or not
422     if show_full_path:
423         vname = path
424     else:
425         vname = path.split('.')[-1]
426
427     # number of spaces before the display
428     tab_level = "  " * level
429     
430     # call to the function that gets the value of the path.
431     try:
432         val = config.getByPath(path)
433     except Exception as e:
434         logger.write(tab_level)
435         logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname), 
436                                          src.printcolors.printcError(str(e))))
437         return
438
439     # in this case, display only the value
440     if show_label:
441         logger.write(tab_level)
442         logger.write("%s: " % src.printcolors.printcLabel(vname))
443
444     # The case where the value has under values, 
445     # do a recursive call to the function
446     if dir(val).__contains__('keys'):
447         if show_label: logger.write("\n")
448         for v in sorted(val.keys()):
449             print_value(config, path + '.' + v, show_label, logger, level + 1)
450     elif val.__class__ == src.pyconf.Sequence or isinstance(val, list): 
451         # in this case, value is a list (or a Sequence)
452         if show_label: logger.write("\n")
453         index = 0
454         for v in val:
455             print_value(config, path + "[" + str(index) + "]", 
456                         show_label, logger, level + 1)
457             index = index + 1
458     else: # case where val is just a str
459         logger.write("%s\n" % val)
460
461 def get_config_children(config, args):
462     '''Gets the names of the children of the given parameter.
463     
464     :param config Config: The configuration where to read the values
465     :param args: The path in the config from which get the keys
466     '''
467     vals = []
468     rootkeys = config.keys()
469     
470     if len(args) == 0:
471         # no parameter returns list of root keys
472         vals = rootkeys
473     else:
474         parent = args[0]
475         pos = parent.rfind('.')
476         if pos < 0:
477             # Case where there is only on key as parameter.
478             # For example VARS
479             vals = [m for m in rootkeys if m.startswith(parent)]
480         else:
481             # Case where there is a part from a key
482             # for example VARS.us  (for VARS.user)
483             head = parent[0:pos]
484             tail = parent[pos+1:]
485             try:
486                 a = config.getByPath(head)
487                 if dir(a).__contains__('keys'):
488                     vals = map(lambda x: head + '.' + x, [m for m in a.keys() if m.startswith(tail)])
489             except:
490                 pass
491
492     for v in sorted(vals):
493         sys.stdout.write("%s\n" % v)
494
495 def description():
496     '''method that is called when salomeTools is called with --help option.
497     
498     :return: The text to display for the config command description.
499     :rtype: str
500     '''
501     return _("The config command allows manipulation "
502              "and operation on config files.")
503     
504
505 def run(args, runner, logger):
506     '''method that is called when salomeTools is called with config parameter.
507     '''
508     # Parse the options
509     (options, args) = parser.parse_args(args)
510
511     # Only useful for completion mechanism : print the keys of the config
512     if options.schema:
513         get_config_children(runner.cfg, args)
514         return
515     
516     # case : print a value of the config
517     if options.value:
518         if options.value == ".":
519             # if argument is ".", print all the config
520             for val in sorted(runner.cfg.keys()):
521                 print_value(runner.cfg, val, not options.no_label, logger)
522         else:
523             print_value(runner.cfg, options.value, not options.no_label, logger, 
524                         level=0, show_full_path=False)
525     
526     # case : edit user pyconf file or application file
527     elif options.edit:
528         editor = runner.cfg.USER.editor
529         if 'APPLICATION' not in runner.cfg: # edit user pyconf
530             usercfg = os.path.join(runner.cfg.VARS.personalDir, 
531                                    'salomeTools.pyconf')
532             src.system.show_in_editor(editor, usercfg, logger)
533         else:
534             # search for file <application>.pyconf and open it
535             for path in runner.cfg.SITE.config.config_path:
536                 pyconf_path = os.path.join(path, 
537                                     runner.cfg.VARS.application + ".pyconf")
538                 if os.path.exists(pyconf_path):
539                     src.system.show_in_editor(editor, pyconf_path, logger)
540                     break
541     
542     # case : copy an existing <application>.pyconf 
543     # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
544     elif options.copy:
545         # product is required
546         src.check_config_has_application( runner.cfg )
547
548         # get application file path 
549         source = runner.cfg.VARS.application + '.pyconf'
550         source_full_path = ""
551         for path in runner.cfg.SITE.config.config_path:
552             # ignore personal directory
553             if path == runner.cfg.VARS.personalDir:
554                 continue
555             # loop on all directories that can have pyconf applications
556             zz = os.path.join(path, source)
557             if os.path.exists(zz):
558                 source_full_path = zz
559                 break
560
561         if len(source_full_path) == 0:
562             raise src.SatException(_(
563                         "Config file for product %s not found\n") % source)
564         else:
565             if len(args) > 0:
566                 # a name is given as parameter, use it
567                 dest = args[0]
568             elif 'copy_prefix' in runner.cfg.SITE.config:
569                 # use prefix
570                 dest = (runner.cfg.SITE.config.copy_prefix 
571                         + runner.cfg.VARS.application)
572             else:
573                 # use same name as source
574                 dest = runner.cfg.VARS.application
575                 
576             # the full path
577             dest_file = os.path.join(runner.cfg.VARS.personalDir, 
578                                      'Applications', dest + '.pyconf')
579             if os.path.exists(dest_file):
580                 raise src.SatException(_("A personal application"
581                                          " '%s' already exists") % dest)
582             
583             # perform the copy
584             shutil.copyfile(source_full_path, dest_file)
585             logger.write(_("%s has been created.\n") % dest_file)
586     
587     # case : display all the available pyconf applications
588     elif options.list:
589         lproduct = list()
590         # search in all directories that can have pyconf applications
591         for path in runner.cfg.SITE.config.config_path:
592             # print a header
593             if not options.no_label:
594                 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
595
596             if not os.path.exists(path):
597                 logger.write(src.printcolors.printcError(_(
598                                             "Directory not found")) + "\n")
599             else:
600                 for f in sorted(os.listdir(path)):
601                     # ignore file that does not ends with .pyconf
602                     if not f.endswith('.pyconf'):
603                         continue
604
605                     appliname = f[:-len('.pyconf')]
606                     if appliname not in lproduct:
607                         lproduct.append(appliname)
608                         if path.startswith(runner.cfg.VARS.personalDir) \
609                                     and not options.no_label:
610                             logger.write("%s*\n" % appliname)
611                         else:
612                             logger.write("%s\n" % appliname)
613                             
614             logger.write("\n")
615     
616